ROLES AND PERMISSIONS - FIRST CHECK-IN

=======================================

WARNING:  DEV IS CURRENTLY VERY UNSTABLE.

This is a mega-checkin of the new Roles system.   A lot of changes have
been made in core and modules.

Currently there are a lot of rough edges and known problems.  We are
working hard on these .. .the reason for getting this into HEAD at this
stage is enable us to move faster (our branch was diverging from HEAD
too much).

Please keep an eye on http://docs.moodle.org/en/Roles for current status
and information for developers on how to use the new Roles system.
This commit is contained in:
moodler 2006-08-08 05:13:06 +00:00
parent 394577c3e4
commit bbbf2d4015
139 changed files with 40452 additions and 2001 deletions

View file

@ -117,6 +117,8 @@
} }
} }
} }
// Delete the capabilities that were defined by this block
capabilities_cleanup('block/'.$block->name);
$a->block = $strblockname; $a->block = $strblockname;
$a->directory = $CFG->dirroot.'/blocks/'.$block->name; $a->directory = $CFG->dirroot.'/blocks/'.$block->name;

View file

@ -7,7 +7,8 @@
if ($site = get_site()) { // If false then this is a new installation if ($site = get_site()) { // If false then this is a new installation
require_login(); require_login();
if (!isadmin()) { $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
if (!has_capability('moodle/site:config', $context->id)) {
error('Only the admin can use this page'); error('Only the admin can use this page');
} }
} }
@ -23,7 +24,7 @@
if ($config = data_submitted($match)) { if ($config = data_submitted($match)) {
if (!empty($USER->id)) { // Additional identity check if (!empty($USER->id)) { // Additional identity check
if (!confirm_sesskey()) { if (!confirm_sesskey()) {
error(get_string('confirmsesskeybad', 'error')); error(get_string('confirmsesskeybad', 'error'));
} }

View file

@ -4,8 +4,9 @@
require_login(); require_login();
if (!isadmin()) { $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
error('Only admins can access this page'); if (!has_capability('moodle/site:config', $context->id)) {
error('Only the admin can use this page');
} }
if (!$site = get_site()) { if (!$site = get_site()) {

View file

@ -28,9 +28,8 @@
$confirmupgrade = optional_param('confirmupgrade', 0, PARAM_BOOL); $confirmupgrade = optional_param('confirmupgrade', 0, PARAM_BOOL);
$agreelicence = optional_param('agreelicence',0, PARAM_BOOL); $agreelicence = optional_param('agreelicence',0, PARAM_BOOL);
/// check upgrade status first /// check upgrade status first
upgrade_check_running("Upgrade already running, please wait!", 10); #upgrade_check_running("Upgrade already running, please wait!", 10);
/// Check some PHP server settings /// Check some PHP server settings
@ -79,6 +78,12 @@
$CFG->version = ""; $CFG->version = "";
} }
/// Turn off time limits and try to flush everything all the time, sometimes upgrades can be slow.
@set_time_limit(0);
@ob_implicit_flush(true);
@ob_end_flush();
/// Check if the main tables have been installed yet or not. /// Check if the main tables have been installed yet or not.
if (! $tables = $db->Metatables() ) { // No tables yet at all. if (! $tables = $db->Metatables() ) { // No tables yet at all.
@ -165,6 +170,12 @@
print_heading($strdatabasechecking); print_heading($strdatabasechecking);
$db->debug=true; $db->debug=true;
if (main_upgrade($CFG->version)) { if (main_upgrade($CFG->version)) {
if (empty($CFG->rolesactive)) {
moodle_upgrade_roles_system_17();
}
if (!update_capabilities()) {
error('Had trouble upgrading the core capabilities for Roles');
}
$db->debug=false; $db->debug=false;
if (set_config("version", $version)) { if (set_config("version", $version)) {
remove_dir($CFG->dataroot . '/cache', true); // flush cache remove_dir($CFG->dataroot . '/cache', true); // flush cache
@ -240,6 +251,7 @@
redirect("config.php"); redirect("config.php");
} }
/// Find and check all main modules and load them up or upgrade them if necessary /// Find and check all main modules and load them up or upgrade them if necessary
upgrade_activity_modules("$CFG->wwwroot/$CFG->admin/index.php"); // Return here afterwards upgrade_activity_modules("$CFG->wwwroot/$CFG->admin/index.php"); // Return here afterwards
@ -304,7 +316,10 @@
/// Check for valid admin user /// Check for valid admin user
require_login(); require_login();
if (!isadmin()) { $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
if (!isadmin()) {
//if (!has_capability('moodle/site:config', $context->id)) {
error("You need to be an admin user to use this page.", "$CFG->wwwroot/login/index.php"); error("You need to be an admin user to use this page.", "$CFG->wwwroot/login/index.php");
} }
@ -416,6 +431,12 @@
get_string('addnewuser').'</a> - <span class="explanation">'.get_string('adminhelpaddnewuser').'</span></div>'; get_string('addnewuser').'</a> - <span class="explanation">'.get_string('adminhelpaddnewuser').'</span></div>';
$userdata .= '<div class="adminlink"><a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/uploaduser.php?sesskey='.$USER->sesskey.'">'. $userdata .= '<div class="adminlink"><a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/uploaduser.php?sesskey='.$USER->sesskey.'">'.
get_string('uploadusers').'</a> - <span class="explanation">'.get_string('adminhelpuploadusers').'</span></div>'; get_string('uploadusers').'</a> - <span class="explanation">'.get_string('adminhelpuploadusers').'</span></div>';
$userdata .= '<div class="adminlink"><a href="roles/manage.php">'.
get_string('manageroles').'</a> - <span class="explanation">'.get_string('adminmanageroles').
' <img src="../pix/t/user.gif" height="11" width="11" alt="" /></span></div>';
$userdata .= '<div class="adminlink"><a href="roles/assign.php?contextid='.$context->id.'">'.
get_string('assignroles').'</a> - <span class="explanation">'.get_string('adminassignroles').
' <img src="../pix/t/user.gif" height="11" width="11" alt="" /></span></div>';
$table->data[] = array('<strong><a href="users.php">'.get_string('users').'</a></strong>', $userdata); $table->data[] = array('<strong><a href="users.php">'.get_string('users').'</a></strong>', $userdata);
@ -423,18 +444,26 @@
'</a> - <span class="explanation">'.get_string('adminhelpcourses').'</span></div>'; '</a> - <span class="explanation">'.get_string('adminhelpcourses').'</span></div>';
$coursedata .= '<div class="adminlink"><a href="enrol.php?sesskey='.$USER->sesskey.'">'.get_string('enrolmentplugins'). $coursedata .= '<div class="adminlink"><a href="enrol.php?sesskey='.$USER->sesskey.'">'.get_string('enrolmentplugins').
'</a> - <span class="explanation">'.get_string('adminhelpenrolments').'</span></div>'; '</a> - <span class="explanation">'.get_string('adminhelpenrolments').'</span></div>';
$coursedata .= '<div class="adminlink"><a href="../course/index.php?edit=off&amp;sesskey='.$USER->sesskey.'">'.
get_string('assignstudents').'</a> - <span class="explanation">'.get_string('adminhelpassignstudents').'</span></div>';
$coursedata .= '<div class="adminlink"><a href="../course/index.php?edit=on&amp;sesskey='.$USER->sesskey.'">'.
get_string('assignteachers').'</a> - <span class="explanation">'.get_string('adminhelpassignteachers').
' <img src="../pix/t/user.gif" height="11" width="11" alt="" /></span></div>';
$coursedata .= '<div class="adminlink"><a href="creators.php?sesskey='.$USER->sesskey.'">'.get_string('assigncreators').
'</a> - <span class="explanation">'.get_string('adminhelpassigncreators').'</span></div>';
$coursedata .= '<div class="adminlink"><a href="admin.php?sesskey='.$USER->sesskey.'">'.get_string('assignadmins').
'</a> - <span class="explanation">'.get_string('adminhelpassignadmins').'</span></div>';
$table->data[] = array('<strong><a href="courses.php">'.get_string('courses').'</a></strong>', $coursedata); $table->data[] = array('<strong><a href="courses.php">'.get_string('courses').'</a></strong>', $coursedata);
$table->data[] = array('<strong><a href="../files/index.php?id='.$site->id.'">'.get_string('sitefiles').'</a></strong>',
'<div class="explanation">'.get_string('adminhelpsitefiles').'</div>');
$table->data[] = array('<strong><a href="stickyblocks.php">'.get_string('stickyblocks','admin').'</a></strong>',
'<div class="explanation">'.get_string('adminhelpstickyblocks').'</div>');
$table->data[] = array('<strong><a href="report.php">'.get_string('reports').'</a></strong>',
'<div class="explanation">'.get_string('adminhelpreports').'</div>');
$testingdata = '<div class="adminlink"><a href="environment.php">'.get_string('environment', 'admin').
'</a> - <span class="explanation">'.get_string('adminhelpenvironment').'</span></div>';
$testingdata .= '<div class="adminlink"><a href="report/simpletest/index.php">'.get_string('simpletest', 'admin').
'</a> - <span class="explanation">'.get_string('adminhelpsimpletest').'</span></div>';
$table->data[] = array('<strong><a href="tests.php">'.get_string('tests','admin').'</a></strong>',
$testingdata);
$miscdata = '<div class="adminlink"><a href="../files/index.php?id='.$site->id.'">'.get_string('sitefiles'). $miscdata = '<div class="adminlink"><a href="../files/index.php?id='.$site->id.'">'.get_string('sitefiles').
'</a> - <span class="explanation">'.get_string('adminhelpsitefiles').'</span></div>'; '</a> - <span class="explanation">'.get_string('adminhelpsitefiles').'</span></div>';
$miscdata .= '<div class="adminlink"><a href="stickyblocks.php">'.get_string('stickyblocks','admin'). $miscdata .= '<div class="adminlink"><a href="stickyblocks.php">'.get_string('stickyblocks','admin').

View file

@ -126,8 +126,10 @@
} }
} }
} }
// Delete the capabilities that were defined by this module
capabilities_cleanup('mod/'.$module->name);
//rebuild_course_cache(); // Because things have changed // rebuild_course_cache(); // Because things have changed
$coursesaffected = true; $coursesaffected = true;
$a->module = $strmodulename; $a->module = $strmodulename;

99
admin/roles/assign.html Executable file
View file

@ -0,0 +1,99 @@
<form name="studentform" id="studentform" method="post" action="assign.php">
<input type="hidden" name="previoussearch" value="<?php echo $previoussearch ?>" />
<input type="hidden" name="sesskey" value="<?php echo sesskey() ?>" />
<input type="hidden" name="contextid" value="<?php echo $contextid ?>" />
<input type="hidden" name="roleid" value="<?php echo $roleid ?>" />
<table align="center" border="0" cellpadding="5" cellspacing="0">
<tr>
<td valign="top">
<?php
$a->count = count($contextusers);
$a->items = $strexistingusers;
print_string('counteditems', '', $a);
?>
</td>
<td></td>
<td valign="top">
<?php
$a->count = $usercount;
$a->items = $strpotentialusers;
print_string('counteditems', '', $a);
?>
</td>
</tr>
<tr>
<td valign="top">
<select name="removeselect[]" size="20" id="removeselect" multiple
onFocus="document.studentform.add.disabled=true;
document.studentform.remove.disabled=false;
document.studentform.addselect.selectedIndex=-1;" />
<?php
foreach ($contextusers as $contextuser) {
$fullname = fullname($contextuser, true);
echo "<option value=\"$contextuser->id\">".$fullname.", ".$student->email."</option>\n";
}
?>
</select></td>
<td valign="top">
<br />
<input name="add" type="submit" id="add" value="&larr;" />
<br />
<input name="remove" type="submit" id="remove" value="&rarr;" />
<br />
</td>
<td valign="top">
<select name="addselect[]" size="20" id="addselect" multiple
onFocus="document.studentform.add.disabled=false;
document.studentform.remove.disabled=true;
document.studentform.removeselect.selectedIndex=-1;">
<?php
if (!empty($searchusers)) {
echo "<optgroup label=\"$strsearchresults (" . count($searchusers) . ")\">\n";
foreach ($searchusers as $user) {
$fullname = fullname($user, true);
echo "<option value=\"$user->id\">".$fullname.", ".$user->email."</option>\n";
}
echo "</optgroup>\n";
}
else {
if ($usercount > MAX_USERS_PER_PAGE) {
echo '<optgroup label="'.get_string('toomanytoshow').'"><option></option></optgroup>'."\n"
.'<optgroup label="'.get_string('trysearching').'"><option></option></optgroup>'."\n";
}
else {
if ($usercount > 0) { //fix for bug#4455
foreach ($users as $user) {
$fullname = fullname($user, true);
echo "<option value=\"$user->id\">".$fullname.", ".$user->email."</option>\n";
}
}
}
}
?>
</select>
<br />
<input type="text" name="searchtext" size="30" value="<?php p($searchtext, true) ?>"
onFocus ="document.studentform.add.disabled=true;
document.studentform.remove.disabled=true;
document.studentform.removeselect.selectedIndex=-1;
document.studentform.addselect.selectedIndex=-1;"
onkeydown = "var keyCode = event.which ? event.which : event.keyCode;
if (keyCode == 13) {
document.studentform.previoussearch.value=1;
document.studentform.submit();
} " />
<input name="search" id="search" type="submit" value="<?php p($strsearch) ?>" />
<?php
if (!empty($searchusers)) {
echo '<input name="showall" id="showall" type="submit" value="'.$strshowall.'" />'."\n";
}
?>
</td>
</tr>
</table>
</form>

164
admin/roles/assign.php Executable file
View file

@ -0,0 +1,164 @@
<?php // $Id$
// Script to assign students to courses
require_once("../../config.php");
define("MAX_USERS_PER_PAGE", 5000);
$contextid = required_param('contextid',PARAM_INT); // context id
$roleid = optional_param('roleid', 0, PARAM_INT); // required role id
$add = optional_param('add', 0, PARAM_BOOL);
$remove = optional_param('remove', 0, PARAM_BOOL);
$showall = optional_param('showall', 0, PARAM_BOOL);
$searchtext = optional_param('searchtext', '', PARAM_RAW); // search string
$previoussearch = optional_param('previoussearch', 0, PARAM_BOOL);
$hidden = optional_param('hidden', 0, PARAM_BOOL); // whether this assignment is hidden
$previoussearch = ($searchtext != '') or ($previoussearch) ? 1:0;
$timestart = optional_param('timestart', 0, PARAM_INT);
$timeend = optional_param('timened', 0, PARAM_INT);
if (! $site = get_site()) {
redirect("$CFG->wwwroot/$CFG->admin/index.php");
}
if (! $context = get_record("context", "id", $contextid)) {
error("Context ID was incorrect (can't find it)");
}
/* permission check to see whether this user can assign people to this role
* needs to be:
* 1) has the capability to assign
* 2) not in role_deny_grant
* end of permission checking
*/
/*
if ($course->metacourse) {
redirect("$CFG->wwwroot/course/importstudents.php?id=$course->id");
}
*/
require_login($course->id);
if (!isteacheredit($course->id)) {
error("You must be an editing teacher in this course, or an admin");
}
$strassignusers = get_string('assignusers');
$strpotentialusers = get_string('potentialusers');
$strexistingusers = get_string('existingusers');
$strsearch = get_string('search');
$strshowall = get_string('showall');
/*
if ($course && $course->id != SITEID) { // course header
print_header("$course->shortname: $strassignusers",
"$site->fullname",
"<a href=\"view.php?id=$course->id\">$course->shortname</a> -> $strassignusers");
} else { // site header
print_header("$site->shortname: $strassignusers",
"$site->fullname",
"$strassignusers");
}
*/
$straction = get_string('roleassignment');
$context = get_record('context', 'id', $contextid);
$currenttab = '';
$tabsmode = 'assign';
include_once('tabs.php');
/// Don't allow restricted teachers to even see this page (because it contains
/// a lot of email addresses and access to all student on the server
check_for_restricted_user($USER->username, "$CFG->wwwroot/course/view.php?id=$course->id");
/// Print a help notice about the need to use this page
if (!$frm = data_submitted()) {
/// A form was submitted so process the input
} else {
if ($add and !empty($frm->addselect) and confirm_sesskey()) {
//$timestart = ????
// time end = ????
$timemodified = time();
foreach ($frm->addselect as $adduser) {
$adduser = clean_param($adduser, PARAM_INT);
if (! role_assign($roleid, $adduser, 0, $contextid, $timestart, $timeend, $hidden)) {
error("Could not add user with id $adduser to this role!");
}
}
} else if ($remove and !empty($frm->removeselect) and confirm_sesskey()) {
foreach ($frm->removeselect as $removeuser) {
$removeuser = clean_param($removeuser, PARAM_INT);
if (! role_unassign($roleid, $removeuser, 0, $contextid)) {
error("Could not remove user with id $removeuser from this role!");
}
}
} else if ($showall) {
$searchtext = '';
$previoussearch = 0;
}
}
/// Get all existing students and teachers for this course.
$existinguserarray = array();
$SQL = "select u.* from {$CFG->prefix}role_assignments r, {$CFG->prefix}user u where contextid = $contextid and roleid = $roleid and u.id = r.userid"; // join now so that we can just use fullname() later
if (!$contextusers = get_records_sql($SQL)) {
$contextusers = array();
}
foreach ($contextusers as $contextuser) {
$existinguserarray[] = $contextuser->id;
}
$existinguserlist = implode(',', $existinguserarray);
unset($existinguserarray);
/// Get search results excluding any users already in this course
if (($searchtext != '') and $previoussearch) {
$searchusers = get_users(true, $searchtext, true, $existinguserlist, 'firstname ASC, lastname ASC',
'', '', 0, 99999, 'id, firstname, lastname, email');
$usercount = get_users(false, '', true, $existinguserlist);
}
/// If no search results then get potential students for this course excluding users already in course
if (empty($searchusers)) {
$usercount = get_users(false, '', true, $existinguserlist, 'firstname ASC, lastname ASC', '', '',
0, 99999, 'id, firstname, lastname, email') ;
$users = array();
if ($usercount <= MAX_USERS_PER_PAGE) {
$users = get_users(true, '', true, $existinguserlist, 'firstname ASC, lastname ASC', '', '',
0, 99999, 'id, firstname, lastname, email');
}
}
// this needs to check capability too
$role = get_records('role');
foreach ($role as $rolex) {
$options[$rolex->id] = $rolex->name;
}
// prints a form to swap roles
print ('<form name="rolesform" action="assign.php" method="post">');
print ('<div align="center">Current Context: '.print_context_name($contextid).'<br/>');
print ('<input type="hidden" name="contextid" value="'.$contextid.'">Select a Role: ');
choose_from_menu ($options, 'roleid', $roleid, 'choose', $script='rolesform.submit()');
print ('</div></form>');
if ($roleid) {
print_simple_box_start("center");
include('assign.html');
print_simple_box_end();
}
print_footer($course);
?>

60
admin/roles/manage.html Executable file
View file

@ -0,0 +1,60 @@
<form name="rolesform" action="manage.php" method="post">
<input type="hidden" name="roleid" value="<?php echo $roleid; ?>">
<input type="hidden" name="sesskey" value="<?php print (sesskey()); ?>">
<input type="hidden" name="action" value="<?php echo $action; ?>">
<br/>Role Name: <input type="text" name="name" value="<?php echo $role->name; ?>">
<br/>Role Description: <input type="text" name="description" value="<?php echo $role->description; ?>">
<input type="hidden" name="contextid" value="<?php echo $contextid; ?>">
<p>
<table>
<tr>
<td>Capability Name</td><td>Inherit</td><td>Allow</td><td>Prevent</td><td>Prohibit</td>
</tr>
<?php
// init these 2
$contextlevel = 0;
$component = '';
foreach ($capabilities as $capability) {
// prints a breaker if component or name or context level
if ($capability->component != $component or $capability->contextlevel != $contextlevel) {
echo ('<tr><td colspan="4"><b>'.get_component_string($capability->component, $capability->contextlevel).'</b></td></tr>');
}
// these 2 are used to see to group same mod/core capabilities together
$contextlevel = $capability->contextlevel;
$component = $capability->component;
// check the capability override for this cap, this role in this context
$SQL = "select * from {$CFG->prefix}role_capabilities where
roleid = $roleid and capability = '$capability->name' and contextid = $contextid";
$localoverride = get_record_sql($SQL);
if (isset($r_caps[$capability->name])) {
$isallow = $r_caps[$capability->name] > 0;
$isprevent = $r_caps[$capability->name] < 0 && $r_caps[$capability->name] > -500;
$isprohibit = $r_caps[$capability->name] <= -500;
} else {
$isallow = 0;
$isprevent = 0;
$isprohibit = 0;
}
?>
<tr>
<td><?php echo get_capability_string($capability->name); ?></td>
<td><INPUT TYPE=radio NAME="<?php echo $capability->name; ?>" VALUE="0" <?php if (!isset($localoverride->permission) || $localoverride->permission==0){ echo 'checked="checked"'; }?>></td>
<td><INPUT TYPE=radio NAME="<?php echo $capability->name; ?>" VALUE="1" <?php if (isset($localoverride->permission) && $localoverride->permission==1){ echo 'checked="checked"'; }?>></td>
<td ><INPUT TYPE=radio NAME="<?php echo $capability->name; ?>" VALUE="-1" <?php if (isset($localoverride->permission) && $localoverride->permission==-1){ echo 'checked="checked"'; }?>></td>
<td ><INPUT TYPE=radio NAME="<?php echo $capability->name; ?>" VALUE="-1000" <?php if (isset($localoverride->permission) && $localoverride->permission==-1000){ echo 'checked="checked"'; }?>></td>
</tr>
<?php } ?>
</table>
</p>
<br/><input type="submit" value="<?php print_string($action);?>">
</form>

187
admin/roles/manage.php Executable file
View file

@ -0,0 +1,187 @@
<?php //$Id$
///dummy field names are used to help adding and dropping indexes. There's only 1 case now, in scorm_scoes_track
//testing
require_once('../../config.php');
require_login();
$roleid = optional_param('roleid', 0, PARAM_INT); // if set, we are editting a role
$action = optional_param('action', '', PARAM_ALPHA);
$name = optional_param('name', '', PARAM_ALPHA); // new role name
$description = optional_param('description', '', PARAM_NOTAGS); // new role desc
$confirm = optional_param('confirm', 0, PARAM_BOOL);
$sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
$contextid = $sitecontext->id;
if (!isadmin()) {
error('Only admins can access this page');
}
if (!$site = get_site()) {
redirect('index.php');
}
$stradministration = get_string('administration');
$strmanageroles = get_string('manageroles');
print_header("$site->shortname: $strmanageroles",
"$site->fullname",
"<a href=\"../index.php\">$stradministration</a> -> $strmanageroles");
// form processing, editting a role, adding a role or deleting a role
if ($action && confirm_sesskey()) {
switch ($action) {
case 'add':
$newrole = create_role($name, $description);
$ignore = array('roleid', 'sesskey', 'action', 'name', 'description', 'contextid');
$data = data_submitted();
foreach ($data as $capname => $value) {
if (in_array($capname, $ignore)) {
continue;
}
assign_capability($capname, $value, $newrole, $contextid);
}
break;
case 'edit':
$ignore = array('roleid', 'sesskey', 'action', 'name', 'description', 'contextid');
$data = data_submitted();
foreach ($data as $capname => $value) {
if (in_array($capname, $ignore)) {
continue;
}
// edit default caps
$SQL = "select * from {$CFG->prefix}role_capabilities where
roleid = $roleid and capability = '$capname' and contextid = $contextid";
$localoverride = get_record_sql($SQL);
if ($localoverride) { // update current overrides
if ($value == 0) { // inherit = delete
unassign_capability($capname, $roleid, $contextid);
} else {
$localoverride->permission = $value;
$localoverride->timemodified = time();
$localoverride->modifierid = $USER->id;
update_record('role_capabilities', $localoverride);
}
} else { // insert a record
assign_capability($capname, $value, $roleid, $contextid);
}
}
// update normal role settings
$role->id = $roleid;
$role->name = $name;
$role->description = $description;
update_record('role', $role);
break;
case 'delete':
if ($confirm) { // deletes a role
echo ('deleting...');
// check for depedencies
// delete all associated role-assignments?
delete_records('role', 'id', $roleid);
} else {
echo ('<form action="manage.php" method="POST">');
echo ('<input type="hidden" name="action" value="delete">');
echo ('<input type="hidden" name="roleid" value="'.$roleid.'">');
echo ('<input type="hidden" name="sesskey" value="'.sesskey().'">');
echo ('<input type="hidden" name="confirm" value="1">');
echo ('are you sure?');
echo ('<input type="submit" value="yes">');
print_footer($course);
exit;
// prints confirmation form
}
break;
/// add possible positioning switch here
default:
break;
}
}
if ($roleid) { // load the role if id is present
$role = get_record('role', 'id', $roleid);
$action = 'edit';
} else {
$role->name='';
$role->description='';
$action = 'add';
}
$roles = get_records('role');
foreach ($roles as $rolex) {
$options[$rolex->id] = $rolex->name;
}
// prints a form to swap roles
print ('<form name="rolesform1" action="manage.php" method="post">');
print ('<div align="center">Select a Role: ');
choose_from_menu ($options, 'roleid', $roleid, 'choose', $script='rolesform1.submit()');
print ('</div></form>');
$sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
$contextid = $sitecontext->id;
// this is the array holding capabilities of this role sorted till this context
$r_caps = role_context_capabilities($roleid, $sitecontext->id);
// this is the available capabilities assignable in this context
$capabilities = fetch_context_capabilities($sitecontext->id);
if (!$roleid) {
$action='add';
} else {
$action='edit';
}
print_simple_box_start();
include_once('manage.html');
print_simple_box_end();
/*************************************************
* List all roles and link them to override page *
*************************************************/
foreach ($roles as $role) {
echo ('<br><a href="roleoverride.php?contextid=1&roleid='.$role->id.'">'.$role->name.'</a>&nbsp;<a href="manage.php?action=delete&roleid='.$role->id.'&sesskey='.sesskey().'">delete</a>');
}
print_footer($course);
?>

54
admin/roles/override.html Executable file
View file

@ -0,0 +1,54 @@
<form action="override.php" method="post">
<input type="hidden" name="contextid" value="<?php echo $contextid; ?>">
<input type="hidden" name="roleid" value="<?php echo $roleid; ?>">
<table>
<tr>
<td>Capability Name</td><td>Inherit</td><td>Allow</td><td>Prevent</td><td>Prohibit</td>
</tr>
<?php
// init these 2
$contextlevel = 0;
$component = '';
foreach ($capabilities as $capability) {
// prints a breaker if component or name or context level
if ($capability->component != $component or $capability->contextlevel != $contextlevel) {
echo ('<tr><td colspan="4"><b>'.get_component_string($capability->component, $capability->contextlevel).'</b></td></tr>');
}
// these 2 are used to see to group same mod/core capabilities together
$contextlevel = $capability->contextlevel;
$component = $capability->component;
// check the capability override for this cap, this role in this context
$SQL = "select * from {$CFG->prefix}role_capabilities where
roleid = $roleid and capability = '$capability->name' and contextid = $contextid";
$localoverride = get_record_sql($SQL);
if (isset($r_caps[$capability->name])) {
$isallow = $r_caps[$capability->name] > 0;
$isprevent = $r_caps[$capability->name] < 0 && $r_caps[$capability->name] > -500;
$isprohibit = $r_caps[$capability->name] <= -500;
} else {
$isallow = 0;
$isprevent = 0;
$isprohibit = 0;
}
?>
<tr>
<td><?php echo get_capability_string($capability->name); ?></td>
<td><INPUT TYPE=radio NAME="<?php echo $capability->name; ?>" VALUE="0" <?php if (!isset($localoverride->permission) || $localoverride->permission==0){ echo 'checked="checked"';} if ($isprohibit || islegacy($capability->name)) {echo 'disabled="disabled"'; }?>></td>
<td <?php if ($isallow) {echo "bgcolor=#ffffff";} ?>><INPUT TYPE=radio NAME="<?php echo $capability->name; ?>" VALUE="1" <?php if (isset($localoverride->permission) && $localoverride->permission==1){ echo 'checked="checked"'; } if ($isprohibit || islegacy($capability->name)) {echo 'disabled="disabled"'; }?>></td>
<td <?php if ($isprevent) {echo "bgcolor=#ffffff";} ?>><INPUT TYPE=radio NAME="<?php echo $capability->name; ?>" VALUE="-1" <?php if (isset($localoverride->permission) && $localoverride->permission==-1){ echo 'checked="checked"'; } if ($isprohibit || islegacy($capability->name)) {echo 'disabled="disabled"'; }?>></td>
<td <?php if ($isprohibit) {echo "bgcolor=#ffffff";} ?>><INPUT TYPE=radio NAME="<?php echo $capability->name; ?>" VALUE="-1000" <?php if (isset($localoverride->permission) && $localoverride->permission==-1000){ echo 'checked="checked"'; } if ($isprohibit || islegacy($capability->name)) {echo 'disabled="disabled"'; }?>></td>
</tr>
<?php } ?>
</table>
<input type="submit" value="modify">
</form>

119
admin/roles/override.php Executable file
View file

@ -0,0 +1,119 @@
<?
/* interface page for writing role overrides */
require_once("../../config.php");
$contextid = required_param('contextid',PARAM_INT); // context id
$roleid = optional_param('roleid', 0, PARAM_INT); // required role id
$sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
if ($contextid == $sitecontext->id) {
error ('can not override base role capabilities');
}
if (! $site = get_site()) {
redirect("$CFG->wwwroot/$CFG->admin/index.php");
}
$stroverrides = get_string('roleoverries');
/*
if ($course && $course->id != SITEID) { // course header
print_header("$course->shortname: $stroverrides",
"$site->fullname",
"<a href=\"view.php?id=$course->id\">$course->shortname</a> -> $stroverrides");
} else { // site header
print_header("$site->shortname: $stroverrides",
"$site->fullname",
"$stroverrides");
}
*/
$context = get_record('context', 'id', $contextid);
$straction = get_string('editoverride');
$currenttab = '';
$tabsmode = 'override';
include_once('tabs.php');
/*************************
* form processing here *
*************************/
if ($data = data_submitted()) {
// add or update
foreach ($data as $capname => $value) {
// ignore contextid and roleid
if ($capname == "contextid" || $capname == "roleid") {
continue;
}
$SQL = "select * from {$CFG->prefix}role_capabilities where
roleid = $roleid and capability = '$capname' and contextid = $contextid";
$localoverride = get_record_sql($SQL);
if ($localoverride) { // update current overrides
if ($value == 0) { // inherit = delete
delete_records('role_capabilities', 'roleid', $roleid, 'contextid', $contextid, 'capability', $capname);
} else {
$localoverride->permission = $value;
$localoverride->timemodified = time();
$localoverride->modifierid = $USER->id;
update_record('role_capabilities', $localoverride);
}
} else { // insert a record
$override->capability = $capname;
$override->contextid = $contextid;
$override->roleid = $roleid;
$override->permission = $value;
$override->timemodified = time();
$override->modifierid = $USER->id;
insert_record('role_capabilities', $override);
}
}
}
/*****************************************
* drop down for swapping between roles *
*****************************************/
// this needs to check capability too
$role = get_records('role');
foreach ($role as $rolex) {
$options[$rolex->id] = $rolex->name;
}
print ('<form name="rolesform" action="override.php" method="post">');
print ('<div align="center">Current Context: '.print_context_name($contextid).'<br/>');
print ('<input type="hidden" name="contextid" value="'.$contextid.'">Select a Role: ');
choose_from_menu ($options, 'roleid', $roleid, 'choose', $script='rolesform.submit()');
print ('</div></form>');
/**************************************
* print html for editting overrides *
**************************************/
if ($roleid) {
// this is the array holding capabilities of this role sorted till this context
$r_caps = role_context_capabilities($roleid, $contextid);
// this is the available capabilities assignable in this context
$capabilities = fetch_context_capabilities($contextid);
print_simple_box_start("center");
include_once('override.html');
print_simple_box_end();
}
print_footer($course);
?>

116
admin/roles/tabs.php Executable file
View file

@ -0,0 +1,116 @@
<?php
// this deals with tabs, as well as print_headers for navigation
if ($currenttab != 'update') {
switch ($context->level) {
case CONTEXT_SYSTEM:
print_header($site->fullname, "$site->fullname","$straction");
break;
case CONTEXT_PERSONAL:
break;
case CONTEXT_USERID:
break;
case CONTEXT_COURSECAT:
$category = get_record('course_categories', 'id', $context->instanceid);
$strcategories = get_string("categories");
$strcategory = get_string("category");
$strcourses = get_string("courses");
print_header("$site->shortname: $category->name", "$site->fullname: $strcourses",
"<a href=\"$CFG->wwwroot/course/index.php\">$strcategories</a> -> <a href=\"$CFG->wwwroot/course/category.php?id=$category->id\">$category->name</a> -> $straction", "", "", true);
break;
case CONTEXT_COURSE:
$streditcoursesettings = get_string("editcoursesettings");
$course = get_record('course', 'id', $context->instanceid);
print_header($streditcoursesettings, "$course->fullname",
"<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a>
-> <a href=\"$CFG->wwwroot/course/edit.php?id=$course->id\">$streditcoursesettings</a> -> $straction");
break;
case CONTEXT_GROUP:
break;
case CONTEXT_MODULE:
// get module type?
$cm = get_record('course_modules','id',$context->instanceid);
$module = get_record('modules','id',$cm->module); //$module->name;
$course = get_record('course','id',$cm->course);
if (! $form = get_record($module->name, "id", $cm->instance)) {
error("The required instance of this module doesn't exist");
}
$strnav = "<a href=\"$CFG->wwwroot/mod/$module->name/view.php?id=$cm->id\">$form->name</a> ->";
$fullmodulename = get_string("modulename", $module->name);
$streditinga = get_string("editinga", "moodle", $fullmodulename);
$strmodulenameplural = get_string("modulenameplural", $module->name);
if ($module->name == "label") {
$focuscursor = "";
} else {
$focuscursor = "form.name";
}
print_header_simple($streditinga, '',
"<a href=\"$CFG->wwwroot/mod/$module->name/index.php?id=$course->id\">$strmodulenameplural</a> ->
$strnav <a href=\"$CFG->wwwroot/course/mod.php?update=$cm->id&sesskey=".sesskey()."\">$streditinga</a> -> $straction", $focuscursor, "", false);
break;
case CONTEXT_BLOCK:
print_header();
break;
default:
error ('This is an unknown context!');
return false;
}
}
// Printing the tabs
if ($context->level == CONTEXT_MODULE) { // only show update button if module?
$toprow[] = new tabobject('update', $CFG->wwwroot.'/course/mod.php?update='.$context->instanceid.'&amp;return=true&amp;sesskey='.sesskey(), get_string('update'));
}
$toprow[] = new tabobject('roles', $CFG->wwwroot.'/admin/roles/assign.php?contextid='.$context->id, get_string('roles'));
if (isset($tabsmode)) {
$inactive[] = 'roles';
$secondrow[] = new tabobject('assign', $CFG->wwwroot.'/admin/roles/assign.php?contextid='.$context->id, get_string('roleassignments'));
if ($context->level == CONTEXT_SYSTEM) {
$secondrow[] = new tabobject('override', '', get_string('roleoverrides'));
} else {
$secondrow[] = new tabobject('override', $CFG->wwwroot.'/admin/roles/override.php?contextid='.$context->id, get_string('roleoverrides'));
}
if ($tabsmode == 'override') {
$currenttab = 'override';
} elseif ($tabsmode == 'assign') {
$currenttab = 'assign';
}
} else {
$inactive[] = '';
}
if (!empty($secondrow)) {
$tabs = array($toprow, $secondrow);
} else {
$tabs = array($toprow);
}
print_tabs($tabs, $currenttab, $inactive);
?>

View file

@ -20,6 +20,8 @@
$admin = new object(); $admin = new object();
$teacher = new object(); $teacher = new object();
$context = get_context_instance(CONTEXT_SYSTEM, SITEID);
if (! record_exists("user_admins")) { // No admin user yet if (! record_exists("user_admins")) { // No admin user yet
$user->firstname = get_string("admin"); $user->firstname = get_string("admin");
@ -138,7 +140,7 @@
notify(get_string("usernotconfirmed", "", fullname($user, true))); notify(get_string("usernotconfirmed", "", fullname($user, true)));
} }
} else if ($delete and confirm_sesskey()) { // Delete a selected user, after confirmation } else if ($delete and confirm_sesskey() and has_capability('moodle/user:delete', $context->id)) { // Delete a selected user, after confirmation
if (!$user = get_record("user", "id", "$delete")) { if (!$user = get_record("user", "id", "$delete")) {
error("No such user!"); error("No such user!");
} }
@ -307,7 +309,10 @@
if ($user->id == $USER->id or $user->username == "changeme") { if ($user->id == $USER->id or $user->username == "changeme") {
$deletebutton = ""; $deletebutton = "";
} else { } else {
$deletebutton = "<a href=\"user.php?delete=$user->id&amp;sesskey=$USER->sesskey\">$strdelete</a>"; if (has_capability('moodle/user:delete', $context->id)) {
$deletebutton = "<a href=\"user.php?delete=$user->id&amp;sesskey=$USER->sesskey\">$strdelete</a>"; } else {
$deletebutton ="";
}
} }
if ($user->lastaccess) { if ($user->lastaccess) {
$strlastaccess = format_time(time() - $user->lastaccess); $strlastaccess = format_time(time() - $user->lastaccess);
@ -320,7 +325,10 @@
$confirmbutton = ""; $confirmbutton = "";
} }
$fullname = fullname($user, true); $fullname = fullname($user, true);
$table->data[] = array ("<a href=\"../user/view.php?id=$user->id&amp;course=$site->id\">$fullname</a>",
if (has_capability('moodle/user:edit', $context->id)) {
$table->data[] = array ("<a href=\"../user/view.php?id=$user->id&amp;course=$site->id\">$fullname</a>",
"$user->email", "$user->email",
"$user->city", "$user->city",
"$user->country", "$user->country",
@ -328,6 +336,16 @@
"<a href=\"../user/edit.php?id=$user->id&amp;course=$site->id\">$stredit</a>", "<a href=\"../user/edit.php?id=$user->id&amp;course=$site->id\">$stredit</a>",
$deletebutton, $deletebutton,
$confirmbutton); $confirmbutton);
} else {
$table->data[] = array ("<a href=\"../user/view.php?id=$user->id&amp;course=$site->id\">$fullname</a>",
"$user->email",
"$user->city",
"$user->country",
$strlastaccess,
$deletebutton,
$confirmbutton);
}
} }
} }
@ -340,14 +358,18 @@
} }
echo "</form>"; echo "</form>";
echo "</td></tr></table>"; echo "</td></tr></table>";
print_heading("<a href=\"user.php?newuser=true&amp;sesskey=$USER->sesskey\">".get_string("addnewuser")."</a>");
if (has_capability('moodle/user:create', $context->id)) {
print_heading("<a href=\"user.php?newuser=true&amp;sesskey=$USER->sesskey\">".get_string("addnewuser")."</a>");
}
if (!empty($table)) { if (!empty($table)) {
print_table($table); print_table($table);
print_paging_bar($usercount, $page, $perpage, print_paging_bar($usercount, $page, $perpage,
"user.php?sort=$sort&amp;dir=$dir&amp;perpage=$perpage". "user.php?sort=$sort&amp;dir=$dir&amp;perpage=$perpage".
"&amp;firstinitial=$firstinitial&amp;lastinitial=$lastinitial&amp;search=".urlencode(stripslashes($search))."&amp;"); "&amp;firstinitial=$firstinitial&amp;lastinitial=$lastinitial&amp;search=".urlencode(stripslashes($search))."&amp;");
print_heading("<a href=\"user.php?newuser=true&amp;sesskey=$USER->sesskey\">".get_string("addnewuser")."</a>"); if (has_capability('moodle/user:create', $context->id)) {
print_heading("<a href=\"user.php?newuser=true&amp;sesskey=$USER->sesskey\">".get_string("addnewuser")."</a>");
}
} }

View file

@ -11,7 +11,7 @@
if (!$site = get_site()) { if (!$site = get_site()) {
redirect("index.php"); redirect("index.php");
} }
$context = get_context_instance(CONTEXT_SYSTEM, SITEID);
$stradministration = get_string("administration"); $stradministration = get_string("administration");
$strusers = get_string("users"); $strusers = get_string("users");
@ -24,12 +24,33 @@
$table->data[] = array("<b><a href=\"auth.php?sesskey=$USER->sesskey\">".get_string("authentication")."</a></b>", $table->data[] = array("<b><a href=\"auth.php?sesskey=$USER->sesskey\">".get_string("authentication")."</a></b>",
get_string("adminhelpauthentication")); get_string("adminhelpauthentication"));
$table->data[] = array("<b><a href=\"user.php\">".get_string("edituser")."</a></b>",
if (has_capability('moodle/user:update', $context->id)) {
$table->data[] = array("<b><a href=\"user.php\">".get_string("edituser")."</a></b>",
get_string("adminhelpedituser")); get_string("adminhelpedituser"));
$table->data[] = array("<b><a href=\"$CFG->wwwroot/$CFG->admin/user.php?newuser=true&amp;sesskey=$USER->sesskey\">".get_string("addnewuser")."</a></b>", }
if (has_capability('moodle/user:create', $context->id)) {
$table->data[] = array("<b><a href=\"$CFG->wwwroot/$CFG->admin/user.php?newuser=true&amp;sesskey=$USER->sesskey\">".get_string("addnewuser")."</a></b>",
get_string("adminhelpaddnewuser")); get_string("adminhelpaddnewuser"));
$table->data[] = array("<b><a href=\"$CFG->wwwroot/$CFG->admin/uploaduser.php?sesskey=$USER->sesskey\">".get_string("uploadusers")."</a></b>", }
if (has_capability('moodle/user:create', $context->id)) {
$table->data[] = array("<b><a href=\"$CFG->wwwroot/$CFG->admin/uploaduser.php?sesskey=$USER->sesskey\">".get_string("uploadusers")."</a></b>",
get_string("adminhelpuploadusers")); get_string("adminhelpuploadusers"));
}
$table->data[] = array('', '<hr />');
$table->data[] = array("<b><a href=\"enrol.php?sesskey=$USER->sesskey\">".get_string("enrolmentplugins")."</a></b>",
get_string("adminhelpenrolments"));
$table->data[] = array("<b><a href=\"../course/index.php?edit=off&amp;sesskey=$USER->sesskey\">".get_string("assignstudents")."</a></b>",
get_string("adminhelpassignstudents"));
$table->data[] = array("<b><a href=\"../course/index.php?edit=on&amp;sesskey=$USER->sesskey\">".get_string("assignteachers")."</a></b>",
get_string("adminhelpassignteachers")." <img src=\"../pix/t/user.gif\" height=\"11\" width=\"11\" alt=\"\" />");
$table->data[] = array("<b><a href=\"creators.php?sesskey=$USER->sesskey\">".get_string("assigncreators")."</a></b>",
get_string("adminhelpassigncreators"));
$table->data[] = array("<b><a href=\"admin.php?sesskey=$USER->sesskey\">".get_string("assignadmins")."</a></b>",
get_string("adminhelpassignadmins"));
print_table($table); print_table($table);

View file

@ -1,7 +1,7 @@
<?php //$Id$ <?php //$Id$
///dummy field names are used to help adding and dropping indexes. There's only 1 case now, in scorm_scoes_track ///dummy field names are used to help adding and dropping indexes. There's only 1 case now, in scorm_scoes_track
//testing
require_once('../config.php'); require_once('../config.php');
require_once($CFG->libdir.'/adminlib.php'); require_once($CFG->libdir.'/adminlib.php');
require_once($CFG->libdir.'/environmentlib.php'); require_once($CFG->libdir.'/environmentlib.php');

View file

@ -32,16 +32,24 @@ class block_admin extends block_list {
function load_content_for_site() { function load_content_for_site() {
global $CFG, $USER; global $CFG, $USER;
if (isadmin()) { $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
if (has_capability('moodle/site:config', $context->id)) {
$this->content->items[] = '<a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/configure.php">'.get_string('configuration').'</a>'; $this->content->items[] = '<a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/configure.php">'.get_string('configuration').'</a>';
$this->content->icons[] = '<img src="'.$CFG->pixpath.'/i/admin.gif" alt="" />'; $this->content->icons[] = '<img src="'.$CFG->pixpath.'/i/admin.gif" alt="" />';
}
if (isadmin()) {
$this->content->items[] = '<a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/users.php">'.get_string('users').'</a>'; $this->content->items[] = '<a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/users.php">'.get_string('users').'</a>';
$this->content->icons[] = '<img src="'.$CFG->pixpath.'/i/users.gif" alt="" />'; $this->content->icons[] = '<img src="'.$CFG->pixpath.'/i/users.gif" alt="" />';
}
if (has_capability('moodle/site:backup', $context->id)) {
$this->content->items[]='<a href="'.$CFG->wwwroot.'/backup/backup.php?id='.SITEID.'">'.get_string('backup').'</a>'; $this->content->items[]='<a href="'.$CFG->wwwroot.'/backup/backup.php?id='.SITEID.'">'.get_string('backup').'</a>';
$this->content->icons[]='<img src="'.$CFG->pixpath.'/i/backup.gif" alt="" />'; $this->content->icons[]='<img src="'.$CFG->pixpath.'/i/backup.gif" alt="" />';
}
if (has_capability('moodle/site:restore', $context->id)) {
$this->content->items[]='<a href="'.$CFG->wwwroot.'/files/index.php?id='.SITEID.'&amp;wdir=/backupdata">'.get_string('restore').'</a>'; $this->content->items[]='<a href="'.$CFG->wwwroot.'/files/index.php?id='.SITEID.'&amp;wdir=/backupdata">'.get_string('restore').'</a>';
$this->content->icons[]='<img src="'.$CFG->pixpath.'/i/restore.gif" alt="" />'; $this->content->icons[]='<img src="'.$CFG->pixpath.'/i/restore.gif" alt="" />';
} }
@ -83,6 +91,7 @@ class block_admin extends block_list {
function load_content_for_course() { function load_content_for_course() {
global $CFG, $USER; global $CFG, $USER;
$context = get_context_instance(CONTEXT_COURSE, $this->instance->pageid);
require_once($CFG->dirroot.'/mod/forum/lib.php'); require_once($CFG->dirroot.'/mod/forum/lib.php');
@ -102,7 +111,8 @@ class block_admin extends block_list {
$isteacheredit = isteacheredit($this->instance->pageid); $isteacheredit = isteacheredit($this->instance->pageid);
if ($isteacheredit) { if (has_capability('moodle/course:update', $context->id)) {
//if (isteacheredit($this->instance->pageid)) {
$this->content->icons[]='<img src="'.$CFG->pixpath.'/i/edit.gif" alt="" />'; $this->content->icons[]='<img src="'.$CFG->pixpath.'/i/edit.gif" alt="" />';
if (isediting($this->instance->pageid)) { if (isediting($this->instance->pageid)) {
$this->content->items[]='<a href="view.php?id='.$this->instance->pageid.'&amp;edit=off&amp;sesskey='.sesskey().'">'.get_string('turneditingoff').'</a>'; $this->content->items[]='<a href="view.php?id='.$this->instance->pageid.'&amp;edit=off&amp;sesskey='.sesskey().'">'.get_string('turneditingoff').'</a>';
@ -112,66 +122,65 @@ class block_admin extends block_list {
$this->content->items[]='<a href="edit.php?id='.$this->instance->pageid.'">'.get_string('settings').'</a>'; $this->content->items[]='<a href="edit.php?id='.$this->instance->pageid.'">'.get_string('settings').'</a>';
$this->content->icons[]='<img src="'.$CFG->pixpath.'/i/settings.gif" alt="" />'; $this->content->icons[]='<img src="'.$CFG->pixpath.'/i/settings.gif" alt="" />';
}
$fullname = fullname($USER, true);
$editmyprofile = '<a title="'.$fullname.'" href="'.$CFG->wwwroot.'/user/edit.php?id='.$USER->id.'&amp;course='.$this->instance->pageid.'">'.get_string('editmyprofile').'</a>';
if (empty($USER->description)) {
//Accessibility: replace non-standard <blink> with CSS (<a> makes title visible in IE).
$text = get_string('profile').' '.get_string('missingdescription');
$this->content->items[]= $editmyprofile.' <a title="'.$text.'" class="useredit blink">*<span class="accesshide">'.$text.'</span></a>';
} else {
$this->content->items[]= $editmyprofile;
}
$this->content->icons[]='<img src="'.$CFG->pixpath.'/i/user.gif" alt="" />';
$fullname = fullname($USER, true); /// always need a role assignment link
$editmyprofile = '<a title="'.$fullname.'" href="'.$securewwwroot.'/user/edit.php?id='.$USER->id.'&amp;course='.$this->instance->pageid.'">'.get_string('editmyprofile').'</a>'; if (has_capability('moodle/role:assign', $context->id)) {
if (empty($USER->description)) { $this->content->items[]='<a href="'.$CFG->wwwroot.'/admin/roles/roleassignment.php?contextid='.$context->id.'">'.get_string('assignusers', 'roles').'</a>';
//Accessibility: replace non-standard <blink> with CSS (<a> makes title visible in IE). $this->content->icons[]='<img src="'.$CFG->pixpath.'/i/users.gif" alt="" />';
$text = get_string('profile').' '.get_string('missingdescription'); }
$this->content->items[]= $editmyprofile.' <a title="'.$text.'" class="useredit blink">*<span class="accesshide">'.$text.'</span></a>';
} else { if ($course->metacourse) {
$this->content->items[]= $editmyprofile; $strchildcourses = get_string('childcourses');
$this->content->items[]='<a href="importstudents.php?id='.$this->instance->pageid.'">'.$strchildcourses.'</a>';
$this->content->icons[]='<img src="'.$CFG->pixpath.'/i/course.gif" alt="" />';
} }
$this->content->icons[]='<img src="'.$CFG->pixpath.'/i/user.gif" alt="" />'; if ($course->groupmode || !$course->groupmodeforce) {
$strgroups = get_string('groups');
$this->content->items[]='<a title="'.$strgroups.'" href="'.$CFG->wwwroot.'/course/groups.php?id='.$this->instance->pageid.'">'.$strgroups.'</a>';
if (iscreator() || !empty($CFG->teacherassignteachers)) { $this->content->icons[]='<img src="'.$CFG->pixpath.'/i/group.gif" alt="" />';
if (!$course->teachers) {
$course->teachers = get_string('defaultcourseteachers');
}
$this->content->items[]='<a href="teacher.php?id='.$this->instance->pageid.'">'.$course->teachers.'</a>';
$this->content->icons[]='<img src="'.$CFG->pixpath.'/i/users.gif" alt="" />';
}
if (!$course->students) {
$course->students = get_string('defaultcoursestudents');
}
if (!$course->metacourse) {
$this->content->items[]='<a href="student.php?id='.$this->instance->pageid.'">'.$course->students.'</a>';
$this->content->icons[]='<img src="'.$CFG->pixpath.'/i/users.gif" alt="" />';
} else {
$strchildcourses = get_string('childcourses');
$this->content->items[]='<a href="importstudents.php?id='.$this->instance->pageid.'">'.$strchildcourses.'</a>';
$this->content->icons[]='<img src="'.$CFG->pixpath.'/i/course.gif" alt="" />';
}
if ($course->groupmode || !$course->groupmodeforce) {
$strgroups = get_string('groups');
$this->content->items[]='<a title="'.$strgroups.'" href="'.$CFG->wwwroot.'/course/groups.php?id='.$this->instance->pageid.'">'.$strgroups.'</a>';
$this->content->icons[]='<img src="'.$CFG->pixpath.'/i/group.gif" alt="" />';
}
$this->content->items[]='<a href="'.$CFG->wwwroot.'/backup/backup.php?id='.$this->instance->pageid.'">'.get_string('backup').'</a>';
$this->content->icons[]='<img src="'.$CFG->pixpath.'/i/backup.gif" alt="" />';
$this->content->items[]='<a href="'.$CFG->wwwroot.'/files/index.php?id='.$this->instance->pageid.'&amp;wdir=/backupdata">'.get_string('restore').'</a>';
$this->content->icons[]='<img src="'.$CFG->pixpath.'/i/restore.gif" alt="" />';
$this->content->items[]='<a href="'.$CFG->wwwroot.'/course/import.php?id='.$this->instance->pageid.'">'.get_string('import').'</a>';
$this->content->icons[]='<img src="'.$CFG->pixpath.'/i/restore.gif" alt="" />';
$this->content->items[]='<a href="'.$CFG->wwwroot.'/course/reset.php?id='.$this->instance->pageid.'">'.get_string('reset').'</a>';
$this->content->icons[]='<img src="'.$CFG->pixpath.'/i/return.gif" alt="" />';
$this->content->items[]='<a href="'.$CFG->wwwroot.'/course/report.php?id='.$this->instance->pageid.'">'.get_string('reports').'</a>';
$this->content->icons[]='<img src="'.$CFG->pixpath.'/i/stats.gif" alt="" />';
$this->content->items[]='<a href="'.$CFG->wwwroot.'/question/edit.php?courseid='.$this->instance->pageid.'&amp;clean=true">'.get_string('questions', 'quiz').'</a>';
$this->content->icons[]='<img src="'.$CFG->pixpath.'/i/questions.gif" alt="" />';
$this->content->items[]='<a href="scales.php?id='.$this->instance->pageid.'">'.get_string('scales').'</a>';
$this->content->icons[]='<img src="'.$CFG->pixpath.'/i/scales.gif" alt="" />';
} }
if (has_capability('moodle/site:backup', $context->id)) {
$this->content->items[]='<a href="'.$CFG->wwwroot.'/backup/backup.php?id='.$this->instance->pageid.'">'.get_string('backup').'</a>';
$this->content->icons[]='<img src="'.$CFG->pixpath.'/i/backup.gif" alt="" />';
}
if (has_capability('moodle/site:restore', $context->id)) {
$this->content->items[]='<a href="'.$CFG->wwwroot.'/files/index.php?id='.$this->instance->pageid.'&amp;wdir=/backupdata">'.get_string('restore').'</a>';
$this->content->icons[]='<img src="'.$CFG->pixpath.'/i/restore.gif" alt="" />';
}
$this->content->items[]='<a href="'.$CFG->wwwroot.'/course/import.php?id='.$this->instance->pageid.'">'.get_string('import').'</a>';
$this->content->icons[]='<img src="'.$CFG->pixpath.'/i/restore.gif" alt="" />';
if (has_capability('moodle/site:import', $context->id)) {
$this->content->items[]='<a href="'.$CFG->wwwroot.'/course/reset.php?id='.$this->instance->pageid.'">'.get_string('reset').'</a>';
$this->content->icons[]='<img src="'.$CFG->pixpath.'/i/return.gif" alt="" />';
}
$this->content->items[]='<a href="'.$CFG->wwwroot.'/course/report.php?id='.$this->instance->pageid.'">'.get_string('reports').'</a>';
$this->content->icons[]='<img src="'.$CFG->pixpath.'/i/stats.gif" alt="" />';
$this->content->items[]='<a href="'.$CFG->wwwroot.'/question/edit.php?courseid='.$this->instance->pageid.'&amp;clean=true">'.get_string('questions', 'quiz').'</a>';
$this->content->icons[]='<img src="'.$CFG->pixpath.'/i/questions.gif" alt="" />';
if (has_capability('moodle/course:managescales', $context->id)) {
$this->content->items[]='<a href="scales.php?id='.$this->instance->pageid.'">'.get_string('scales').'</a>';
$this->content->icons[]='<img src="'.$CFG->pixpath.'/i/scales.gif" alt="" />';
}
$this->content->items[]='<a href="'.$CFG->wwwroot.'/grade/index.php?id='.$this->instance->pageid.'">'.get_string('grades').'</a>'; $this->content->items[]='<a href="'.$CFG->wwwroot.'/grade/index.php?id='.$this->instance->pageid.'">'.get_string('grades').'</a>';
$this->content->icons[]='<img src="'.$CFG->pixpath.'/i/grades.gif" alt="" />'; $this->content->icons[]='<img src="'.$CFG->pixpath.'/i/grades.gif" alt="" />';

View file

@ -281,8 +281,34 @@ class block_base {
* @todo complete documenting this function. Define $options. * @todo complete documenting this function. Define $options.
*/ */
function _add_edit_controls($options) { function _add_edit_controls($options) {
global $CFG, $USER; global $CFG, $USER;
// this is the context relevant to this particular block instance
$blockcontext = get_context_instance(CONTEXT_BLOCK, $this->instance->id);
// context for site or course, i.e. participant list etc
// check to see if user can edit site or course blocks.
// blocks can appear on other pages such as mod and blog pages...
switch ($this->instance->pagetype) {
case 'course-view':
if ($this->instance->pageid == SITEID) {
$context = get_context_instance(CONTEXT_SYSTEM, $this->instance->pageid);
} else {
$context = get_context_instance(CONTEXT_COURSE, $this->instance->pageid);
}
if (!has_capability('moodle/site:manageblocks', $context->id)) {
return null;
}
break;
default:
break;
}
if (!isset($this->str)) { if (!isset($this->str)) {
$this->str->delete = get_string('delete'); $this->str->delete = get_string('delete');
$this->str->moveup = get_string('moveup'); $this->str->moveup = get_string('moveup');
@ -310,6 +336,10 @@ class block_base {
$page = page_create_object($this->instance->pagetype, $this->instance->pageid); $page = page_create_object($this->instance->pagetype, $this->instance->pageid);
$script = $page->url_get_full(array('instanceid' => $this->instance->id, 'sesskey' => $USER->sesskey)); $script = $page->url_get_full(array('instanceid' => $this->instance->id, 'sesskey' => $USER->sesskey));
// place holder for roles button
$movebuttons .= '<a class="icon roles" title="'. $title .'" href="'.$CFG->wwwroot.'/admin/roles/roleassignment.php?contextid='.$blockcontext->id.'">' .
'<img src="'.$CFG->pixpath.'/i/users.gif" alt="'.get_string('roles').'" /></a>';
$movebuttons .= '<a class="icon hide" title="'. $title .'" href="'.$script.'&amp;blockaction=toggle">' . $movebuttons .= '<a class="icon hide" title="'. $title .'" href="'.$script.'&amp;blockaction=toggle">' .
'<img src="'. $CFG->pixpath.$icon .'" alt="'.$title.'" /></a>'; '<img src="'. $CFG->pixpath.$icon .'" alt="'.$title.'" /></a>';

View file

@ -7,8 +7,26 @@ class block_participants extends block_list {
} }
function get_content() { function get_content() {
global $USER, $CFG; global $USER, $CFG;
// the following 3 lines is need to pass _self_test();
if (!$this->instance->pageid) {
return '';
}
// only 2 possible contexts, site or course
if ($this->instance->pageid == SITEID) { // site context
$context = get_context_instance(CONTEXT_SYSTEM, SITEID);
} else { // course context
$context = get_context_instance(CONTEXT_COURSE, $this->instance->pageid);
}
if (!has_capability('moodle/course:viewparticipants', $context->id)) {
$this->context = '';
return $this->content;
}
if ($this->content !== NULL) { if ($this->content !== NULL) {
return $this->content; return $this->content;
} }
@ -33,7 +51,7 @@ class block_participants extends block_list {
isteacher(SITEID)) { isteacher(SITEID)) {
$this->content->items[] = '<a title="'.get_string('listofallpeople').'" href="'. $this->content->items[] = '<a title="'.get_string('listofallpeople').'" href="'.
$CFG->wwwroot.'/user/index.php?id='.$this->instance->pageid.'">'.get_string('participants').'</a>'; $CFG->wwwroot.'/user/index.php?id='.$this->instance->pageid.'&amp;contextid='.$context->id.'">'.get_string('participants').'</a>';
$this->content->icons[] = '<img src="'.$CFG->pixpath.'/i/users.gif" height="16" width="16" alt="" />'; $this->content->icons[] = '<img src="'.$CFG->pixpath.'/i/users.gif" height="16" width="16" alt="" />';
} }

View file

@ -16,29 +16,31 @@ if (!$referrer = optional_param('referrer','', PARAM_URL)) {
} }
} }
//first verify that user is not a guest
if (isguest()) { $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
error(get_string('noguestpost', 'blog'), $referrer); if (!has_capability('moodle/blog:readentries', $context->id)) {
error(get_string('nopost', 'blog'), $referrer);
} }
// make sure that the person trying to edit have access right
// Make sure that the person trying to edit have access right
if ($editid = optional_param('editid', 0, PARAM_INT)) { if ($editid = optional_param('editid', 0, PARAM_INT)) {
$blogEntry = get_record('post', 'id', $editid); $blogEntry = get_record('post', 'id', $editid);
if (!blog_user_can_edit_post($blogEntry)) { if (!blog_user_can_edit_post($blogEntry, $context->id)) {
error( get_string('notallowedtoedit', 'blog'), $CFG->wwwroot .'/login/index.php'); error( get_string('notallowedtoedit', 'blog'), $CFG->wwwroot .'/login/index.php');
} }
} }
//check to see if there is a requested blog to edit // Check to see if there is a requested blog to edit
if (isloggedin() && !isguest()) { if (isloggedin() && !isguest()) {
$userid = $USER->id; $userid = $USER->id;
} else { } else {
error(get_string('noblogspecified', 'blog') .'<a href="'. $CFG->blog_blogurl .'">' .get_string('viewentries', 'blog') .'</a>'); error(get_string('noblogspecified', 'blog') .'<a href="'. $CFG->blog_blogurl .'">' .get_string('viewentries', 'blog') .'</a>');
} }
// if we are trying to delete an non-existing blog entry // If we are trying to delete an non-existing blog entry
if (isset($act) && ($act == 'del') && (empty($blogEntry))) { if (isset($act) && ($act == 'del') && (empty($blogEntry))) {
error ('the entry you are trying to delete does not exist'); error ('the entry you are trying to delete does not exist');
} }
@ -153,7 +155,7 @@ function do_delete($postid) {
// check ownership // check ownership
$blogEntry = get_record('post','id',$postid); $blogEntry = get_record('post','id',$postid);
if (blog_user_can_edit_post($blogEntry)) { if (blog_user_can_edit_post($blogEntry, $context->id)) {
if (delete_records('post','id',$postid)) { if (delete_records('post','id',$postid)) {
//echo "bloginfo_arg:"; //debug //echo "bloginfo_arg:"; //debug

View file

@ -237,6 +237,3 @@ if (blocks_have_content($pageblocks, BLOCK_POS_LEFT) || $editing) {
print '<!-- Begin page content -->' . "\n"; print '<!-- Begin page content -->' . "\n";
print '<td width="*">'; print '<td width="*">';
?> ?>
<table width="100%">
<tr>
<td height="100%" valign="top">

View file

@ -26,6 +26,8 @@ $postid = optional_param('postid',0,PARAM_INT);
$filtertype = optional_param('filtertype', '', PARAM_ALPHA); $filtertype = optional_param('filtertype', '', PARAM_ALPHA);
$filterselect = optional_param('filterselect', 0, PARAM_INT); $filterselect = optional_param('filterselect', 0, PARAM_INT);
/// overwrite filter code here /// overwrite filter code here
if ($filtertype) { if ($filtertype) {
@ -48,7 +50,6 @@ if ($filtertype) {
} }
$userid =0; $userid =0;
$groupid = 0; $groupid = 0;
break; break;
case 'group': case 'group':
@ -61,7 +62,6 @@ if ($filtertype) {
$groupid = 0; $groupid = 0;
} }
$userid = 0; $userid = 0;
break; break;
case 'user': case 'user':
@ -69,13 +69,12 @@ if ($filtertype) {
$userid = $filterselect; $userid = $filterselect;
} }
$groupid = 0; $groupid = 0;
break; break;
default: default:
break; break;
} }
} else if ($userid) { //default to user } else if ($userid) { // default to user
$filtertype = 'user'; $filtertype = 'user';
$filterselect = $userid; $filterselect = $userid;
} else { } else {
@ -83,43 +82,53 @@ if ($filtertype) {
$filterselect = ''; $filterselect = '';
} }
/// rights checking
/// Rights checking.
switch ($filtertype) { switch ($filtertype) {
case 'site': case 'site':
if ($CFG->bloglevel < BLOG_SITE_LEVEL && (!isadmin())) { $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
error ('site blogs is not enabled'); if ($CFG->bloglevel < BLOG_SITE_LEVEL &&
!has_capability('moodle/site:config', $context->id)) {
error('Site blogs is not enabled');
} else if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL) { } else if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL) {
require_login(); require_login();
} }
break; break;
case 'course': case 'course':
if ($CFG->bloglevel < BLOG_COURSE_LEVEL && (!isadmin())) { $context = get_context_instance(CONTEXT_COURSE, $courseid);
error ('course blogs is not enabled'); if ($CFG->bloglevel < BLOG_COURSE_LEVEL &&
!has_capability('moodle/course:update', $context->id)) {
error('Course blogs is not enabled');
} }
if (!has_capability('moodle/blog:readentry', $context->id)) {
if (!isstudent($filterselect) && !isteacher($filterselect)) { error('You do not have the required permissions to to view course blogs');
error ('you must be a student in this course to view course blogs');
} }
/// check if viewer is student
break; break;
case 'group': case 'group':
if ($CFG->bloglevel < BLOG_GROUP_LEVEL && (!isadmin())) { $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
error ('group blogs is not enabled'); $coursecontext = get_context_instance(CONTEXT_COURSE, $courseid);
if ($CFG->bloglevel < BLOG_GROUP_LEVEL &&
!has_capability('moodle/site:config', $sitecontext->id)) {
error ('Group blogs is not enabled');
} }
if (!isteacheredit($course) and (groupmode($course) == SEPARATEGROUPS)) { if (!has_capability('moodle/course:update', $coursecontext->id) &&
groupmode($course) == SEPARATEGROUPS) {
if (!ismember($filterselect)) { if (!ismember($filterselect)) {
error ('you are not in this group'); error ('You are not a member of this group');
} }
} }
/// check if user is editting teacher, or if spg, is member /// check if user is editting teacher, or if spg, is member
break; break;
case 'user': case 'user':
if ($CFG->bloglevel < BLOG_USER_LEVEL && (!isadmin())) { $context = get_context_instance(CONTEXT_SYSTEM, $context->id);
if ($CFG->bloglevel < BLOG_USER_LEVEL &&
!has_capability('moodle/site:config', SITEID)) {
error ('Blogs is not enabled'); error ('Blogs is not enabled');
} }
if ($CFG->bloglevel == BLOG_USER_LEVEL && $USER->id != $filterselect &&
if ($CFG->bloglevel == BLOG_USER_LEVEL and $USER->id != $filterselect and !isadmin()) { !has_capability('moodle/site:config', $context->id)) {
error ('Under this setting, you can only view your own blogs'); error ('Under this setting, you can only view your own blogs');
} }
@ -134,12 +143,20 @@ switch ($filtertype) {
// first set the start and end day equal to the day argument passed in from the get vars // first set the start and end day equal to the day argument passed in from the get vars
if ($limit == 'none') { if ($limit == 'none') {
$limit = get_user_preferences('blogpagesize',10); $limit = get_user_preferences('blogpagesize', 10);
} }
include($CFG->dirroot .'/blog/header.php'); include($CFG->dirroot .'/blog/header.php');
$blogpage = optional_param('blogpage',0,PARAM_INT); // prints the tabs
$currenttab = 'blogs';
$user = $USER;
if (!$course) {
$course = get_record('course', 'id', optional_param('courseid', SITEID, PARAM_INT));
}
require_once($CFG->dirroot .'/user/tabs.php');
$blogpage = optional_param('blogpage', 0, PARAM_INT);
blog_print_html_formatted_entries($userid, $postid, $limit, ($blogpage * $limit) ,$filtertype, $filterselect, $tagid, $tag, $filtertype, $filterselect); blog_print_html_formatted_entries($userid, $postid, $limit, ($blogpage * $limit) ,$filtertype, $filterselect, $tagid, $tag, $filtertype, $filterselect);

View file

@ -3,19 +3,22 @@
/** /**
* Library of functions and constants for blog * Library of functions and constants for blog
*/ */
require_once($CFG->libdir .'/blocklib.php'); require_once($CFG->libdir .'/blocklib.php');
require_once($CFG->libdir .'/pagelib.php'); require_once($CFG->libdir .'/pagelib.php');
require_once('rsslib.php'); require_once('rsslib.php');
require_once($CFG->dirroot .'/blog/blogpage.php'); require_once($CFG->dirroot .'/blog/blogpage.php');
/* blog access level constant declaration */
/**
* Blog access level constant declaration
*/
define ('BLOG_USER_LEVEL', 1); define ('BLOG_USER_LEVEL', 1);
define ('BLOG_GROUP_LEVEL', 2); define ('BLOG_GROUP_LEVEL', 2);
define ('BLOG_COURSE_LEVEL', 3); define ('BLOG_COURSE_LEVEL', 3);
define ('BLOG_SITE_LEVEL', 4); define ('BLOG_SITE_LEVEL', 4);
define ('BLOG_GLOBAL_LEVEL', 5); define ('BLOG_GLOBAL_LEVEL', 5);
/** /**
* Definition of blogcourse page type (blog page with course id present). * Definition of blogcourse page type (blog page with course id present).
*/ */
@ -25,15 +28,18 @@
$BLOG_YES_NO_MODES = array ( '0' => get_string('no'), $BLOG_YES_NO_MODES = array ( '0' => get_string('no'),
'1' => get_string('yes') ); '1' => get_string('yes') );
//set default setting for $CFG->blog_* vars used by blog's blocks // Set default setting for $CFG->blog_* vars used by blog's blocks.
//if they are not already. Otherwise errors are thrown // If they are not already. Otherwise errors are thrown when an attempt
//when an attempt is made to use an empty var. // is made to use an empty var.
if (empty($SESSION->blog_editing_enabled)) { if (empty($SESSION->blog_editing_enabled)) {
$SESSION->blog_editing_enabled = false; $SESSION->blog_editing_enabled = false;
} }
// checks to see if user has visited blogpages before, if not, install 2 default blocks
// (blog_menu and blog_tags) /**
* Checks to see if user has visited blogpages before, if not, install 2
* default blocks (blog_menu and blog_tags).
*/
function blog_check_and_install_blocks() { function blog_check_and_install_blocks() {
global $USER; global $USER;
if (isloggedin() && !isguest()) { if (isloggedin() && !isguest()) {
@ -78,6 +84,7 @@
return ($SESSION->blog_editing_enabled); return ($SESSION->blog_editing_enabled);
} }
/** /**
* This function is in lib and not in BlogInfo because entries being searched * This function is in lib and not in BlogInfo because entries being searched
* might be found in any number of blogs rather than just one. * might be found in any number of blogs rather than just one.
@ -132,9 +139,10 @@
print $output; print $output;
} }
/** /**
* This function is in lib and not in BlogInfo because entries being searched * This function is in lib and not in BlogInfo because entries being searched
* might be found in any number of blogs rather than just one. * might be found in any number of blogs rather than just one.
* *
* This function builds an array which can be used by the included * This function builds an array which can be used by the included
* template file, making predefined and nicely formatted variables available * template file, making predefined and nicely formatted variables available
@ -184,7 +192,7 @@
echo '</td>'; echo '</td>';
echo '<td class="topic starter"><div class="subject">'.$template['title'].'</div><div class="author">'; echo '<td class="topic starter"><div class="subject">'.$template['title'].'</div><div class="author">';
$fullname = fullname($user, isteacher($template['userid'])); $fullname = fullname($user, $template['userid']);
$by->name = '<a href="'.$CFG->wwwroot.'/user/view.php?id='. $by->name = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.
$user->id.'&amp;course='.$course->id.'">'.$fullname.'</a>'; $user->id.'&amp;course='.$course->id.'">'.$fullname.'</a>';
$by->date = $template['lastmod']; $by->date = $template['lastmod'];
@ -240,11 +248,14 @@
echo '<div class="commands">'; echo '<div class="commands">';
if (isset($USER->id)) { if (isset($USER->id)) {
if (($template['userid'] == $USER->id) or isadmin()) { $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
$canmanage = has_capability('moodle/blog:manageentries', $context->id);
if (($template['userid'] == $USER->id) or $canmanage) {
echo '<a href="'.$CFG->wwwroot.'/blog/edit.php?editid='.$blogEntry->id.'&amp;sesskey='.sesskey().'">'.$stredit.'</a>'; echo '<a href="'.$CFG->wwwroot.'/blog/edit.php?editid='.$blogEntry->id.'&amp;sesskey='.sesskey().'">'.$stredit.'</a>';
} }
if (($template['userid'] == $USER->id) or isadmin()) { if (($template['userid'] == $USER->id) or $canmanage) {
echo '| <a href="'.$CFG->wwwroot.'/blog/edit.php?act=del&amp;editid='.$blogEntry->id.'&amp;sesskey='.sesskey().'">'.$strdelete.'</a>'; echo '| <a href="'.$CFG->wwwroot.'/blog/edit.php?act=del&amp;editid='.$blogEntry->id.'&amp;sesskey='.sesskey().'">'.$strdelete.'</a>';
} }
} }
@ -255,6 +266,7 @@
} }
/** /**
* Use this function to retrieve a list of publish states available for * Use this function to retrieve a list of publish states available for
* the currently logged in user. * the currently logged in user.
@ -274,25 +286,36 @@
return $options; return $options;
} }
// user can edit if he's an admin, or blog owner
function blog_user_can_edit_post($blogEntry) { /**
* User can edit a blog entry if this is their own blog post and they have
* the capability moodle/blog:writeentry, or if they have the capability
* moodle/blog:manageentries.
*/
function blog_user_can_edit_post($blogEntry, $contextid) {
global $CFG, $USER; global $CFG, $USER;
return (isadmin() || ($blogEntry->userid == $USER->id)); return ((has_capability('moodle/blog:writeentries', $contextid) &&
$blogEntry->userid == $USER->id) ||
has_capability('moodle/blog:manageentries', $context->id));
} }
/// Checks to see if a user can view the blogs of another user.
/// He can do so, if he is admin, in any same non-spg course,
/// or spg group, but same group member /**
* Checks to see if a user can view the blogs of another user.
* He can do so, if he has the moodle/blog:readentry capability. In the
* case of spg group course, the user also needs to be in the same group.
*/
function blog_user_can_view_user_post($targetuserid, $blogEntry=null) { function blog_user_can_view_user_post($targetuserid, $blogEntry=null) {
global $CFG, $USER; global $CFG, $USER;
$canview = 0; //bad start $canview = 0; //bad start
if (isadmin()) { $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
return true;
if (!has_capability('moodle/blog:readentry', $context->id)) {
return false;
} }
if ($USER->id && ($USER->id == $targetuserid)) { if ($USER->id && ($USER->id == $targetuserid)) {
@ -305,14 +328,14 @@
$usercourses = get_my_courses($targetuserid); $usercourses = get_my_courses($targetuserid);
foreach ($usercourses as $usercourse) { foreach ($usercourses as $usercourse) {
/// if viewer and user sharing same non-spg course, then grant permission // If the viewer and user are sharing same non-spg course, then
if (groupmode($usercourse)!= SEPARATEGROUPS){ // grant permission.
if (isstudent($usercourse->id) || isteacher($usercourse->id)) { if (groupmode($usercourse) != SEPARATEGROUPS) {
$canview = 1; $canview = 1;
return $canview; return $canview;
}
} else { } else {
/// now we need every group the user is in, and check to see if view is a member // Now we need every group the user is in, and check to see
// if view is a member.
if ($usergroups = user_group($usercourse->id, $targetuserid)) { if ($usergroups = user_group($usercourse->id, $targetuserid)) {
foreach ($usergroups as $usergroup) { foreach ($usergroups as $usergroup) {
if (ismember($usergroup->id)) { if (ismember($usergroup->id)) {
@ -325,14 +348,16 @@
} }
if (!$canview && $CFG->bloglevel < BLOG_SITE_LEVEL) { if (!$canview && $CFG->bloglevel < BLOG_SITE_LEVEL) {
error ('you can not view this user\'s blogs'); error ('You can not view this user\'s blogs');
} }
return $canview; return $canview;
} }
/// moved from BlogEntry class /**
* Moved from BlogEntry class.
*/
function get_formatted_entry_body($body, $format) { function get_formatted_entry_body($body, $format) {
global $CFG; global $CFG;
include_once($CFG->libdir .'/weblib.php'); include_once($CFG->libdir .'/weblib.php');
@ -342,8 +367,10 @@
return stripslashes_safe($body); return stripslashes_safe($body);
} }
/// Main filter function
/**
* Main filter function.
*/
function fetch_entries($userid, $postid='', $fetchlimit=10, $fetchstart='', $filtertype='', $filterselect='', $tagid='', $tag ='', $sort='lastmodified DESC', $limit=true) { function fetch_entries($userid, $postid='', $fetchlimit=10, $fetchstart='', $filtertype='', $filterselect='', $tagid='', $tag ='', $sort='lastmodified DESC', $limit=true) {
global $CFG, $USER; global $CFG, $USER;
@ -522,18 +549,25 @@
return $records; return $records;
} }
/** /**
* get the count of viewable entries, easiest way is to count fetch_entries * get the count of viewable entries, easiest way is to count fetch_entries
* this is used for print_paging_bar * this is used for print_paging_bar
* this is not ideal, but because of the UNION in the sql in fetch_entries, * this is not ideal, but because of the UNION in the sql in fetch_entries,
* it is hard to use count_records_sql * it is hard to use count_records_sql
*/ */
function get_viewable_entry_count($userid, $postid='', $fetchlimit=10, $fetchstart='', $filtertype='', $filterselect='', $tagid='', $tag ='', $sort='lastmodified DESC') { function get_viewable_entry_count($userid, $postid='', $fetchlimit=10,
$fetchstart='', $filtertype='', $filterselect='', $tagid='',
$tag ='', $sort='lastmodified DESC') {
$blogEntries = fetch_entries($userid, $postid, $fetchlimit,
$fetchstart, $filtertype, $filterselect, $tagid, $tag,
$sort='lastmodified DESC', false);
$blogEntries = fetch_entries($userid, $postid, $fetchlimit, $fetchstart,$filtertype, $filterselect, $tagid, $tag, $sort='lastmodified DESC', false);
return count($blogEntries); return count($blogEntries);
} }
/// Find the base url from $_GET variables, for print_paging_bar /// Find the base url from $_GET variables, for print_paging_bar
function get_baseurl($filtertype, $filterselect) { function get_baseurl($filtertype, $filterselect) {
@ -570,7 +604,8 @@
$querystring = '?'; $querystring = '?';
} }
return strip_querystring(qualified_me()) . $querystring. 'filtertype='.$filtertype.'&amp;filterselect='.$filterselect.'&amp;'; return strip_querystring(qualified_me()) . $querystring. 'filtertype='.
$filtertype.'&amp;filterselect='.$filterselect.'&amp;';
} }
?> ?>

View file

@ -17,13 +17,11 @@
} }
} }
//ensure that the logged in user is not using the guest account $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
if (isguest()) {
error(get_string('noguestpost', 'blog'), $referrer);
}
if (!(isloggedin() && !isguest())) { // Ensure that the logged in user has the capability to post blog entries.
error(get_string('noguestpost', 'blog'), $referrer); if (!has_capability('moodle/blog:writepost', $context->id)) {
error(get_string('nopost', 'blog'), $referrer);
} }
$userid = $USER->id; $userid = $USER->id;

View file

@ -12,7 +12,10 @@ print_heading(get_string('tagmanagement'));
<td> <td>
<form action="tags.php" method="POST"> <form action="tags.php" method="POST">
<input type="hidden" name="sesskey" value="<?php echo sesskey(); ?>" /> <input type="hidden" name="sesskey" value="<?php echo sesskey(); ?>" />
<?php if (isadmin()){ ?> <?php
$context = get_context_instance(CONTEXT_SYSTEM, SITEID);
if (has_capability('moodle/blog:manageofficialtags', $context->id)) {
?>
<select name="tags[]" multiple="multiple" size="8"> <select name="tags[]" multiple="multiple" size="8">
<?php <?php
$otags = get_records_sql('SELECT * from '.$CFG->prefix.'tags WHERE type=\'official\' ORDER by text ASC'); $otags = get_records_sql('SELECT * from '.$CFG->prefix.'tags WHERE type=\'official\' ORDER by text ASC');
@ -72,7 +75,7 @@ print_heading(get_string('tagmanagement'));
<tr> <tr>
<td> <td>
<?php if (isadmin()) { ?> <?php if (has_capability('moodle/blog:manageofficialtags', $context->id)) { ?>
<form action="tags.php" method="POST"> <form action="tags.php" method="POST">
<input type="hidden" name="sesskey" value="<?php echo sesskey(); ?>" /> <input type="hidden" name="sesskey" value="<?php echo sesskey(); ?>" />
<?php print_string('addotags','blog');?>:<br/> <?php print_string('addotags','blog');?>:<br/>

View file

@ -2,16 +2,17 @@
require_once('../config.php'); require_once('../config.php');
require_login(); require_login();
if (isguest()) {
error ('Guests can not modify tags!');
}
//form process //form process
$mode = optional_param('mode','',PARAM_ALPHA); $mode = optional_param('mode','',PARAM_ALPHA);
switch ($mode) { $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
case 'addofficial': /// adding official tags
if (!isadmin() || !confirm_sesskey()) {
switch ($mode) {
case 'addofficial':
/// Adding official tags.
if (!has_capability('moodle/blog:manageofficialtags', $context->id) || !confirm_sesskey()) {
die('you can not add official tags'); die('you can not add official tags');
} }
@ -21,21 +22,25 @@ switch ($mode) {
$tag->type = 'official'; $tag->type = 'official';
$tagid = insert_record('tags', $tag); $tagid = insert_record('tags', $tag);
/// write newly added tags back into window opener /// Write newly added tags back into window opener.
echo '<script language="JavaScript" type="text/javascript"> echo '<script language="JavaScript" type="text/javascript">
var o = opener.document.createElement("option"); var o = opener.document.createElement("option");
o.innerHTML = "<option>'.$tag->text.'</option>"; o.innerHTML = "<option>'.$tag->text.'</option>";
o.value = '.$tagid.'; o.value = '.$tagid.';
opener.document.entry[\'otags[]\'].insertBefore(o, null); opener.document.entry[\'otags[]\'].insertBefore(o, null);
</script>'; </script>';
} else { // tag already exist } else {
/// Tag already exists.
notify(get_string('tagalready')); notify(get_string('tagalready'));
} }
break; break;
case 'addpersonal': /// everyone can add personal tags case 'addpersonal':
if (!confirm_sesskey() || isguest() || !isset($USER->id)) { /// Everyone can add personal tags as long as they can write blog entries.
if (!confirm_sesskey() ||
!has_capability('moodle/blog:writeentries', $context->id) ||
!isset($USER->id)) {
error ('you can not add tags'); error ('you can not add tags');
} }
@ -45,20 +50,22 @@ switch ($mode) {
$tag->type = 'personal'; $tag->type = 'personal';
$tagid = insert_record('tags', $tag); $tagid = insert_record('tags', $tag);
/// write newly added tags back into window opener /// Write newly added tags back into window opener.
echo '<script language="JavaScript" type="text/javascript"> echo '<script language="JavaScript" type="text/javascript">
var o = opener.document.createElement("option"); var o = opener.document.createElement("option");
o.innerHTML = "<option>'.$tag->text.'</option>"; o.innerHTML = "<option>'.$tag->text.'</option>";
o.value = '.$tagid.'; o.value = '.$tagid.';
opener.document.entry[\'ptags[]\'].insertBefore(o, null); opener.document.entry[\'ptags[]\'].insertBefore(o, null);
</script>'; </script>';
} else { //tag already exist } else {
/// Tag already exists.
notify(get_string('tagalready')); notify(get_string('tagalready'));
} }
break; break;
case 'delete': /// delete a tag case 'delete':
/// Delete a tag.
if (!confirm_sesskey()) { if (!confirm_sesskey()) {
error('you can not delete tags'); error('you can not delete tags');
} }
@ -69,14 +76,18 @@ switch ($mode) {
$blogtag = get_record('tags','id',$tag); $blogtag = get_record('tags','id',$tag);
// you can only delete your own tags, or you have to be an admin // You can only delete your own tags, or you have to have the
if (!isadmin() and $USER->id != $blogtag->userid) { // moodle/blog:manageofficialtags capability.
if (!has_capability('moodle/blog:manageofficialtags', $context->id)
&& $USER->id != $blogtag->userid) {
notify(get_string('norighttodeletetag','blog', $blogtag->text)); notify(get_string('norighttodeletetag','blog', $blogtag->text));
continue; continue;
} }
/// Only admin can delete tags that are referenced // You can only delete tags that are referenced if you have
if (!isadmin() && get_records('blog_tag_instance','tagid', $tag)) { // the moodle/blog:manageofficialtags capability.
if (!has_capability('moodle/blog:manageofficialtags', $context->id)
&& get_records('blog_tag_instance','tagid', $tag)) {
notify('tag is used by other users, can not delete!'); notify('tag is used by other users, can not delete!');
continue; continue;
} }
@ -84,7 +95,7 @@ switch ($mode) {
delete_records('tags','id',$tag); delete_records('tags','id',$tag);
delete_records('blog_tag_instance', 'tagid', $tag); delete_records('blog_tag_instance', 'tagid', $tag);
/// remove parent window option via javascript /// Remove parent window option via javascript.
echo '<script> echo '<script>
var i=0; var i=0;
while (i < window.opener.document.entry[\'otags[]\'].length) { while (i < window.opener.document.entry[\'otags[]\'].length) {
@ -107,16 +118,15 @@ switch ($mode) {
} }
break; break;
default: // just displaying tags form default:
/// Just display the tags form.
break; break;
} }
//print the table
/// Print the table.
print_header(); print_header();
include_once('tags.html'); include_once('tags.html');
print_footer(); print_footer();

View file

@ -289,6 +289,9 @@
} }
foreach ($courses as $acourse) { foreach ($courses as $acourse) {
$context = get_context_instance(CONTEXT_COURSE, $acourse->id);
$count++; $count++;
$up = ($count > 1 || !$atfirstpage); $up = ($count > 1 || !$atfirstpage);
$down = ($count < $numcourses || !$atlastpage); $down = ($count < $numcourses || !$atlastpage);
@ -305,24 +308,40 @@
echo '<a title="'.$strassignteachers.'" href="'.$CFG->wwwroot.'/course/teacher.php?id='. echo '<a title="'.$strassignteachers.'" href="'.$CFG->wwwroot.'/course/teacher.php?id='.
$acourse->id.'">'. $acourse->id.'">'.
'<img src="'.$CFG->pixpath.'/t/user.gif" height="11" width="11" border="0" alt="'.$strassignteachers.'" /></a> '; '<img src="'.$CFG->pixpath.'/t/user.gif" height="11" width="11" border="0" alt="'.$strassignteachers.'" /></a> ';
echo '<a title="'.$strdelete.'" href="delete.php?id='.$acourse->id.'">'. if (has_capability('moodle/course:delete', $context->id)) {
'<img src="'.$CFG->pixpath.'/t/delete.gif" height="11" width="11" border="0" alt="'.$strdelete.'" /></a> '; echo '<a title="'.$strdelete.'" href="delete.php?id='.$acourse->id.'">'.
if (!empty($acourse->visible)) { '<img src="'.$CFG->pixpath.'/t/delete.gif" height="11" width="11" border="0" alt="'.$strdelete.'" /></a> ';
echo '<a title="'.$strhide.'" href="category.php?id='.$category->id.'&amp;page='.$page. }
'&amp;perpage='.$perpage.'&amp;hide='.$acourse->id.'&amp;sesskey='.$USER->sesskey.'">'.
'<img src="'.$CFG->pixpath.'/t/hide.gif" height="11" width="11" border="0" alt="'.$strhide.'" /></a> '; if (has_capability('moodle/course:visibility', $context->id)) {
} else { if (!empty($acourse->visible)) {
echo '<a title="'.$strshow.'" href="category.php?id='.$category->id.'&amp;page='.$page. echo '<a title="'.$strhide.'" href="category.php?id='.$category->id.'&amp;page='.$page.
'&amp;perpage='.$perpage.'&amp;show='.$acourse->id.'&amp;sesskey='.$USER->sesskey.'">'. '&amp;perpage='.$perpage.'&amp;hide='.$acourse->id.'&amp;sesskey='.$USER->sesskey.'">'.
'<img src="'.$CFG->pixpath.'/t/show.gif" height="11" width="11" border="0" alt="'.$strshow.'" /></a> '; '<img src="'.$CFG->pixpath.'/t/hide.gif" height="11" width="11" border="0" alt="'.$strhide.'" /></a> ';
} else {
echo '<a title="'.$strshow.'" href="category.php?id='.$category->id.'&amp;page='.$page.
'&amp;perpage='.$perpage.'&amp;show='.$acourse->id.'&amp;sesskey='.$USER->sesskey.'">'.
'<img src="'.$CFG->pixpath.'/t/show.gif" height="11" width="11" border="0" alt="'.$strshow.'" /></a> ';
}
}
if (has_capability('moodle/site:backup', $context->id)) {
echo '<a title="'.$strbackup.'" href="../backup/backup.php?id='.$acourse->id.'">'.
'<img src="'.$CFG->pixpath.'/t/backup.gif" height="11" width="11" border="0" alt="" /></a> ';
}
if (has_capability('moodle/site:restore', $context->id)) {
echo '<a title="'.$strrestore.'" href="../files/index.php?id='.$acourse->id.
'&amp;wdir=/backupdata">'.
'<img src="'.$CFG->pixpath.'/t/restore.gif" height="11" width="11" border="0" alt="" /></a> ';
} }
echo '<a title="'.$strbackup.'" href="../backup/backup.php?id='.$acourse->id.'">'. echo '<a title="'.$strbackup.'" href="../backup/backup.php?id='.$acourse->id.'">'.
'<img src="'.$CFG->pixpath.'/t/backup.gif" height="11" width="11" border="0" alt="'.$strbackup.'" /></a> '; '<img src="'.$CFG->pixpath.'/t/backup.gif" height="11" width="11" border="0" alt="'.$strbackup.'" /></a> ';
echo '<a title="'.$strrestore.'" href="../files/index.php?id='.$acourse->id. echo '<a title="'.$strrestore.'" href="../files/index.php?id='.$acourse->id.
'&amp;wdir=/backupdata">'. '&amp;wdir=/backupdata">'.
'<img src="'.$CFG->pixpath.'/t/restore.gif" height="11" width="11" border="0" alt="'.$strrestore.'" /></a> '; '<img src="'.$CFG->pixpath.'/t/restore.gif" height="11" width="11" border="0" alt="'.$strrestore.'" /></a> ';
if ($up) { if ($up) {
echo '<a title="'.$strmoveup.'" href="category.php?id='.$category->id.'&amp;page='.$page. echo '<a title="'.$strmoveup.'" href="category.php?id='.$category->id.'&amp;page='.$page.
@ -399,14 +418,16 @@
print_single_button('category.php', $options, get_string('resortcoursesbyname'), 'get'); print_single_button('category.php', $options, get_string('resortcoursesbyname'), 'get');
} }
if (iscreator()) { /// Print button to create a new course $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
if (has_capability('moodle/course:create', $context->id)) { /// Print button to create a new course
unset($options); unset($options);
$options['category'] = $category->id; $options['category'] = $category->id;
print_single_button('edit.php', $options, get_string('addnewcourse'), 'get'); print_single_button('edit.php', $options, get_string('addnewcourse'), 'get');
echo '<br />'; echo '<br />';
} }
if (isadmin()) { /// Print form to rename the category $context = get_context_instance(CONTEXT_COURSECAT, $id);
if (has_capability('moodle/category:update', $context->id)) { /// Print form to rename the category
$strrename= get_string('rename'); $strrename= get_string('rename');
echo '<form name="renameform" action="category.php" method="post">'; echo '<form name="renameform" action="category.php" method="post">';
echo '<input type="hidden" name="id" value="'.$category->id.'" />'; echo '<input type="hidden" name="id" value="'.$category->id.'" />';
@ -415,10 +436,10 @@
echo '<input type="submit" value="'.$strrename.'" />'; echo '<input type="submit" value="'.$strrename.'" />';
echo "</form>"; echo "</form>";
echo "<br />"; echo "<br />";
}
print_course_search(); print_course_search();
}
echo "</center>"; echo "</center>";
print_footer(); print_footer();

View file

@ -19,7 +19,9 @@
error("Course ID was incorrect"); error("Course ID was incorrect");
} }
if (!isteacheredit($course->id)) { $context = get_context_instance(CONTEXT_COURSE, $id);
if (!has_capability('moodle/course:update', $context->id)) {
error("You do not currently have editing privileges!"); error("You do not currently have editing privileges!");
} }
@ -38,7 +40,8 @@
} }
} else { // Admin is creating a new course } else { // Admin is creating a new course
if (!iscreator()) { $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
if (!has_capability('moodle/course:create',$context->id)) {
error("You do not currently have course creation privileges!"); error("You do not currently have course creation privileges!");
} }

View file

@ -17,15 +17,19 @@
require_login($course->id); require_login($course->id);
if (!isteacheredit($course->id)) { if (! $group = get_record("groups", "id", $group, "courseid", $course->id)) {
close_window();
}
if (! $group = get_record("groups", "id", $group, "courseid", $course->id)) {
notice('Specified group could not be found!', "#"); notice('Specified group could not be found!', "#");
close_window_button(); close_window_button();
} }
// this is fine since group inherits course settings, this allows 1) teacher to edit all groups
// 2 someone with a role with a cap to modify a specific group
$context = get_context_instance(CONTEXT_GROUP, $group->id);
// this is really weird
if (!has_capability('moodle/course:managegroups', $context->id)) {
close_window();
}
/// Print the headers of the page /// Print the headers of the page

View file

@ -36,8 +36,9 @@
} }
require_login($course->id); require_login($course->id);
$context = get_context_instance(CONTEXT_COURSE, $course->id);
if (!isteacheredit($course->id)) { if (!has_capability('moodle/course:managegroups', $context->id)) {
redirect("group.php?id=$course->id"); // Not allowed to see all groups redirect("group.php?id=$course->id"); // Not allowed to see all groups
} }

View file

@ -15,6 +15,8 @@
$moveup = optional_param('moveup',0,PARAM_INT); $moveup = optional_param('moveup',0,PARAM_INT);
$movedown = optional_param('movedown',0,PARAM_INT); $movedown = optional_param('movedown',0,PARAM_INT);
$context = get_context_instance(CONTEXT_SYSTEM, SITEID);
if (!$site = get_site()) { if (!$site = get_site()) {
error("Site isn't defined!"); error("Site isn't defined!");
} }
@ -97,7 +99,7 @@
/// If data for a new category was submitted, then add it /// If data for a new category was submitted, then add it
if ($form = data_submitted() and confirm_sesskey()) { if ($form = data_submitted() and confirm_sesskey() and has_capability('moodle/category:create', $context->id)) {
if (!empty($form->addcategory)) { if (!empty($form->addcategory)) {
unset($newcategory); unset($newcategory);
$newcategory->name = $form->addcategory; $newcategory->name = $form->addcategory;
@ -114,7 +116,10 @@
/// Delete a category if necessary /// Delete a category if necessary
if (!empty($delete) and confirm_sesskey()) { if (!empty($delete) and confirm_sesskey()) {
if ($deletecat = get_record("course_categories", "id", $delete)) {
// context is coursecat, if not present admins should have it set in site level
$context = get_context_instance(CONTEXT_COURSECAT, $delete);
if ($deletecat = get_record("course_categories", "id", $delete) and has_capability('moodle/category:delete', $context->id)) {
if (!empty($sure) && $sure == md5($deletecat->timemodified)) { if (!empty($sure) && $sure == md5($deletecat->timemodified)) {
/// Send the children categories to live with their grandparent /// Send the children categories to live with their grandparent
if ($childcats = get_records("course_categories", "parent", $deletecat->id)) { if ($childcats = get_records("course_categories", "parent", $deletecat->id)) {
@ -269,17 +274,17 @@
fix_course_sortorder(); fix_course_sortorder();
/// Print form for creating new categories /// Print form for creating new categories
if (has_capability('moodle/category:create', $context->id)) {
echo "<center>";
echo "<form name=\"addform\" action=\"index.php\" method=\"post\">";
echo "<input type=\"text\" size=\"30\" alt=\"$straddnewcategory\" name=\"addcategory\" />";
echo "<input type=\"submit\" value=\"$straddnewcategory\" />";
echo "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />";
echo "</form>";
echo "</center>";
echo "<center>"; echo "<br />";
echo "<form name=\"addform\" action=\"index.php\" method=\"post\">"; }
echo "<input type=\"text\" size=\"30\" alt=\"$straddnewcategory\" name=\"addcategory\" />";
echo "<input type=\"submit\" value=\"$straddnewcategory\" />";
echo "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />";
echo "</form>";
echo "</center>";
echo "<br />";
/// Print out the categories with all the knobs /// Print out the categories with all the knobs
@ -310,7 +315,11 @@
echo "<center>"; echo "<center>";
unset($options); unset($options);
$options["category"] = $category->id; $options["category"] = $category->id;
print_single_button("edit.php", $options, get_string("addnewcourse"), "get");
if (has_capability('moodle/course:create', $context->id)) {
print_single_button("edit.php", $options, get_string("addnewcourse"), "get");
}
print_single_button('pending.php',NULL, get_string('coursespending'),"get"); print_single_button('pending.php',NULL, get_string('coursespending'),"get");
echo "<br />"; echo "<br />";
echo "</center>"; echo "</center>";
@ -336,6 +345,8 @@ function print_category_edit($category, $displaylist, $parentslist, $depth=-1, $
} }
if ($category) { if ($category) {
$context = get_context_instance(CONTEXT_COURSECAT, $category->id);
echo "<tr><td align=\"left\" nowrap=\"nowrap\">"; echo "<tr><td align=\"left\" nowrap=\"nowrap\">";
for ($i=0; $i<$depth;$i++) { for ($i=0; $i<$depth;$i++) {
echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
@ -348,16 +359,20 @@ function print_category_edit($category, $displaylist, $parentslist, $depth=-1, $
echo "<td nowrap=\"nowrap\">"; /// Print little icons echo "<td nowrap=\"nowrap\">"; /// Print little icons
echo "<a title=\"$str->delete\" href=\"index.php?delete=$category->id&amp;sesskey=$USER->sesskey\"><img". if (has_capability('moodle/category:delete', $context->id)) {
" src=\"$CFG->pixpath/t/delete.gif\" height=\"11\" width=\"11\" border=\"0\" alt=\"$str->delete\" /></a> "; echo "<a title=\"$str->delete\" href=\"index.php?delete=$category->id&amp;sesskey=$USER->sesskey\"><img".
" src=\"$CFG->pixpath/t/delete.gif\" height=\"11\" width=\"11\" border=\"0\" alt=\"\" /></a> ";
}
if (!empty($category->visible)) { if (has_capability('moodle/category:visibility', $context->id)) {
echo "<a title=\"$str->hide\" href=\"index.php?hide=$category->id&amp;sesskey=$USER->sesskey\"><img". if (!empty($category->visible)) {
" src=\"$CFG->pixpath/t/hide.gif\" height=\"11\" width=\"11\" border=\"0\" alt=\"$str->hide\" /></a> "; echo "<a title=\"$str->hide\" href=\"index.php?hide=$category->id&amp;sesskey=$USER->sesskey\"><img".
} else { " src=\"$CFG->pixpath/t/hide.gif\" height=\"11\" width=\"11\" border=\"0\" alt=\"\" /></a> ";
echo "<a title=\"$str->show\" href=\"index.php?show=$category->id&amp;sesskey=$USER->sesskey\"><img". } else {
" src=\"$CFG->pixpath/t/show.gif\" height=\"11\" width=\"11\" border=\"0\"alt=\"$str->show\" /></a> "; echo "<a title=\"$str->show\" href=\"index.php?show=$category->id&amp;sesskey=$USER->sesskey\"><img".
} " src=\"$CFG->pixpath/t/show.gif\" height=\"11\" width=\"11\" border=\"0\"alt=\"\" /></a> ";
}
}
if ($up) { if ($up) {
echo "<a title=\"$str->moveup\" href=\"index.php?moveup=$category->id&amp;sesskey=$USER->sesskey\"><img". echo "<a title=\"$str->moveup\" href=\"index.php?moveup=$category->id&amp;sesskey=$USER->sesskey\"><img".

View file

@ -62,9 +62,8 @@
$mod->coursemodule = $cm->id; $mod->coursemodule = $cm->id;
} }
if (!isteacheredit($course->id)) { $context = get_context_instance(CONTEXT_COURSE, $course->id);
error("You can't modify this course!"); has_capability('moodle/course:update', $context->id, true);
}
$mod->course = $course->id; $mod->course = $course->id;
$mod->modulename = clean_param($mod->modulename, PARAM_SAFEDIR); // For safety $mod->modulename = clean_param($mod->modulename, PARAM_SAFEDIR); // For safety
@ -242,9 +241,8 @@
} }
} }
if (!isteacheredit($section->course)) { $context = get_context_instance(CONTEXT_COURSE, $section->course);
error("You can't modify this course!"); has_capability('moodle/course:update', $context->id, true);
}
if (!ismoving($section->course)) { if (!ismoving($section->course)) {
error("You need to copy something first!"); error("You need to copy something first!");
@ -272,9 +270,8 @@
error("This course module doesn't exist"); error("This course module doesn't exist");
} }
if (!isteacheredit($cm->course)) { $context = get_context_instance(CONTEXT_COURSE, $cm->course);
error("You can't modify this course!"); has_capability('moodle/course:update', $context->id, true);
}
$cm->indent += $indent; $cm->indent += $indent;
@ -299,9 +296,8 @@
error("This course module doesn't exist"); error("This course module doesn't exist");
} }
if (!isteacheredit($cm->course)) { $context = get_context_instance(CONTEXT_COURSE, $cm->course);
error("You can't modify this course!"); has_capability('moodle/course:update', $context->id, true);
}
set_coursemodule_visible($cm->id, 0); set_coursemodule_visible($cm->id, 0);
@ -320,9 +316,8 @@
error("This course module doesn't exist"); error("This course module doesn't exist");
} }
if (!isteacheredit($cm->course)) { $context = get_context_instance(CONTEXT_COURSE, $cm->course);
error("You can't modify this course!"); has_capability('moodle/course:update', $context->id, true);
}
if (! $section = get_record("course_sections", "id", $cm->section)) { if (! $section = get_record("course_sections", "id", $cm->section)) {
error("This module doesn't exist"); error("This module doesn't exist");
@ -352,9 +347,8 @@
error("This course module doesn't exist"); error("This course module doesn't exist");
} }
if (!isteacheredit($cm->course)) { $context = get_context_instance(CONTEXT_COURSE, $cm->course);
error("You can't modify this course!"); has_capability('moodle/course:update', $context->id, true);
}
set_coursemodule_groupmode($cm->id, $groupmode); set_coursemodule_groupmode($cm->id, $groupmode);
@ -373,9 +367,8 @@
error("This course module doesn't exist"); error("This course module doesn't exist");
} }
if (!isteacheredit($cm->course)) { $context = get_context_instance(CONTEXT_COURSE, $cm->course);
error("You can't modify this course!"); has_capability('moodle/course:update', $context->id, true);
}
if (! $section = get_record("course_sections", "id", $cm->section)) { if (! $section = get_record("course_sections", "id", $cm->section)) {
error("This module doesn't exist"); error("This module doesn't exist");
@ -415,9 +408,8 @@
error("This course doesn't exist"); error("This course doesn't exist");
} }
if (!isteacheredit($course->id)) { $context = get_context_instance(CONTEXT_COURSE, $cm->course);
error("You can't modify this course!"); has_capability('moodle/course:update', $context->id, true);
}
if (! $module = get_record("modules", "id", $cm->module)) { if (! $module = get_record("modules", "id", $cm->module)) {
error("This module doesn't exist"); error("This module doesn't exist");
@ -472,9 +464,8 @@
error("This course doesn't exist"); error("This course doesn't exist");
} }
if (!isteacheredit($course->id)) { $context = get_context_instance(CONTEXT_COURSE, $course->id);
error("You can't modify this course!"); has_capability('moodle/course:update', $context->id, true);
}
if (! $module = get_record("modules", "id", $cm->module)) { if (! $module = get_record("modules", "id", $cm->module)) {
error("This module doesn't exist"); error("This module doesn't exist");
@ -530,9 +521,8 @@
error("This course doesn't exist"); error("This course doesn't exist");
} }
if (!isteacheredit($course->id)) { $context = get_context_instance(CONTEXT_COURSE, $course->id);
error("You can't modify this course!"); has_capability('moodle/course:update', $context->id, true);
}
if (! $module = get_record("modules", "id", $cm->module)) { if (! $module = get_record("modules", "id", $cm->module)) {
error("This module doesn't exist"); error("This module doesn't exist");
@ -629,9 +619,8 @@
error("No action was specfied"); error("No action was specfied");
} }
if (!isteacheredit($course->id)) { $context = get_context_instance(CONTEXT_COURSE, $course->id);
error("You can't modify this course!"); has_capability('moodle/course:update', $context->id, true);
}
$streditinga = get_string("editinga", "moodle", $fullmodulename); $streditinga = get_string("editinga", "moodle", $fullmodulename);
$strmodulenameplural = get_string("modulenameplural", $module->name); $strmodulenameplural = get_string("modulenameplural", $module->name);
@ -646,6 +635,12 @@
"<a href=\"$CFG->wwwroot/mod/$module->name/index.php?id=$course->id\">$strmodulenameplural</a> -> "<a href=\"$CFG->wwwroot/mod/$module->name/index.php?id=$course->id\">$strmodulenameplural</a> ->
$strnav $streditinga", $focuscursor, "", false); $strnav $streditinga", $focuscursor, "", false);
if (!empty($cm->id)) {
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
$currenttab = 'update';
include_once($CFG->dirroot.'/admin/roles/tabs.php');
}
unset($SESSION->modform); // Clear any old ones that may be hanging around. unset($SESSION->modform); // Clear any old ones that may be hanging around.
$modform = "../mod/$module->name/mod.html"; $modform = "../mod/$module->name/mod.html";

View file

@ -16,6 +16,7 @@
} }
require_login($course->id); require_login($course->id);
$context = get_context_instance(CONTEXT_COURSE, $course->id);
$strscale = get_string("scale"); $strscale = get_string("scale");
$strscales = get_string("scales"); $strscales = get_string("scales");
@ -93,9 +94,8 @@
//If action is details, show the popup info //If action is details, show the popup info
if ($action == "details") { if ($action == "details") {
//Check for teacher edit //Check for teacher edit
if (! isteacheredit($course->id)) { has_capability('moodle/course:managescales', $context->id, true);
error("Only editing teachers can view scales !");
}
//Check for scale //Check for scale
if (! $scale = get_record("scale", "id", $scaleid)) { if (! $scale = get_record("scale", "id", $scaleid)) {
error("Scale ID was incorrect"); error("Scale ID was incorrect");
@ -130,10 +130,8 @@
$sesskey = !empty($USER->id) ? $USER->sesskey : ''; $sesskey = !empty($USER->id) ? $USER->sesskey : '';
//Check for teacher edit has_capability('moodle/course:managescales', $context->id, true);
if (! isteacheredit($course->id)) {
error("Only editing teachers can modify scales !");
}
//Check for scale if action = edit //Check for scale if action = edit
if ($action == "edit") { if ($action == "edit") {
if (! $scale = get_record("scale", "id", $scaleid)) { if (! $scale = get_record("scale", "id", $scaleid)) {
@ -237,9 +235,7 @@
//If action is delete, do it //If action is delete, do it
if ($action == "delete" and confirm_sesskey()) { if ($action == "delete" and confirm_sesskey()) {
//Check for teacher edit //Check for teacher edit
if (! isteacheredit($course->id)) { has_capability('moodle/course:managescales', $context->id, true);
error("Only editing teachers can delete scales !");
}
//Check for scale if action = edit //Check for scale if action = edit
if (! $scale = get_record("scale", "id", $scaleid)) { if (! $scale = get_record("scale", "id", $scaleid)) {
error("Scale ID was incorrect"); error("Scale ID was incorrect");
@ -270,9 +266,7 @@
//If action is down or up, do it //If action is down or up, do it
if (($action == "down" || $action == "up") and confirm_sesskey()) { if (($action == "down" || $action == "up") and confirm_sesskey()) {
//Check for teacher edit //Check for teacher edit
if (! isadmin()) { has_capability('moodle/course:managescales', $context->id, true);
error("Only administrators can move scales",$CFG->wwwroot.'/course/scales.php?id='.$course->id);
}
//Check for scale if action = edit //Check for scale if action = edit
if (! $scale = get_record("scale", "id", $scaleid)) { if (! $scale = get_record("scale", "id", $scaleid)) {
error("Scale ID was incorrect"); error("Scale ID was incorrect");
@ -302,7 +296,7 @@
} }
if ($list) { /// Just list the scales (in a helpwindow) if ($list) { /// Just list the scales (in a helpwindow)
has_capability('moodle/course:viewscales', $context->id, true);
print_header($strscales); print_header($strscales);
if (!empty($scaleid)) { if (!empty($scaleid)) {
@ -345,7 +339,7 @@
} }
} else { } else {
if (isteacheredit($course->id)) { if (has_capability('moodle/course:managescales', $context->id)) {
echo "<p align=\"center\">("; echo "<p align=\"center\">(";
print_string("scalestip"); print_string("scalestip");
echo ")</p>"; echo ")</p>";
@ -375,9 +369,7 @@
/// The rest is all about editing the scales /// The rest is all about editing the scales
if (!isteacheredit($course->id)) { has_capability('moodle/course:managescales', $context->id, true);
error("Only editing teachers can modify scales !");
}
/// Print out the main page /// Print out the main page

View file

@ -71,6 +71,7 @@ $string['adminhelpxmldbeditor'] = 'Interface to edit the XMLDB files. Only for d
$string['adminhelpusers'] = 'Define your users and set up authentication'; $string['adminhelpusers'] = 'Define your users and set up authentication';
$string['administration'] = 'Administration'; $string['administration'] = 'Administration';
$string['administrator'] = 'Administrator'; $string['administrator'] = 'Administrator';
$string['administratordescription'] = 'Administrators can usually do anything on the site, in all courses.';
$string['administrators'] = 'Administrators'; $string['administrators'] = 'Administrators';
$string['administratorsall'] = 'All administrators'; $string['administratorsall'] = 'All administrators';
$string['administratorsandteachers'] = 'Administrators and teachers'; $string['administratorsandteachers'] = 'Administrators and teachers';
@ -229,7 +230,8 @@ $string['courseapprovedfailed'] = 'Failed to save the course as approved!';
$string['coursebackup'] = 'Course backup'; $string['coursebackup'] = 'Course backup';
$string['coursecategories'] = 'Course categories'; $string['coursecategories'] = 'Course categories';
$string['coursecategory'] = 'Course category'; $string['coursecategory'] = 'Course category';
$string['coursecreators'] = 'Course creators'; $string['coursecreators'] = 'Course creator';
$string['coursecreatorsdescription'] = 'Course creators can create new courses and teach in them.';
$string['coursefiles'] = 'Course files'; $string['coursefiles'] = 'Course files';
$string['courseformats'] = 'Course formats'; $string['courseformats'] = 'Course formats';
$string['coursegrades'] = 'Course grades'; $string['coursegrades'] = 'Course grades';
@ -305,9 +307,11 @@ $string['default'] = 'Default';
$string['defaultcoursefullname'] = 'Course Fullname 101'; $string['defaultcoursefullname'] = 'Course Fullname 101';
$string['defaultcourseshortname'] = 'CF101'; $string['defaultcourseshortname'] = 'CF101';
$string['defaultcoursestudent'] = 'Student'; $string['defaultcoursestudent'] = 'Student';
$string['defaultcoursestudentdescription'] = 'Students generally have less privileges within a course.';
$string['defaultcoursestudents'] = 'Students'; $string['defaultcoursestudents'] = 'Students';
$string['defaultcoursesummary'] = 'Write a concise and interesting paragraph here that explains what this course is about'; $string['defaultcoursesummary'] = 'Write a concise and interesting paragraph here that explains what this course is about';
$string['defaultcourseteacher'] = 'Teacher'; $string['defaultcourseteacher'] = 'Teacher';
$string['defaultcourseteacherdescription'] = 'Teachers can do anything within a course, including changing the activities and grading students.';
$string['defaultcourseteachers'] = 'Teachers'; $string['defaultcourseteachers'] = 'Teachers';
$string['delete'] = 'Delete'; $string['delete'] = 'Delete';
$string['deleteall'] = 'Delete all'; $string['deleteall'] = 'Delete all';
@ -611,6 +615,8 @@ $string['groups'] = 'Groups';
$string['groupsnone'] = 'No groups'; $string['groupsnone'] = 'No groups';
$string['groupsseparate'] = 'Separate groups'; $string['groupsseparate'] = 'Separate groups';
$string['groupsvisible'] = 'Visible groups'; $string['groupsvisible'] = 'Visible groups';
$string['guest'] = 'Guest';
$string['guestdescription'] = 'Guests have minimal privileges and usually can not enter text anywhere.';
$string['guestskey'] = 'Allow guests who have the key'; $string['guestskey'] = 'Allow guests who have the key';
$string['guestsno'] = 'Do not allow guests in'; $string['guestsno'] = 'Do not allow guests in';
$string['guestsnotallowed'] = 'Sorry, \'$a\' does not allow guests to enter.'; $string['guestsnotallowed'] = 'Sorry, \'$a\' does not allow guests to enter.';
@ -916,6 +922,8 @@ $string['noimagesyet'] = 'No images have been uploaded to your course yet';
$string['nomorecourses'] = 'No more matching courses could be found'; $string['nomorecourses'] = 'No more matching courses could be found';
$string['nomoreidnumber'] = 'Not using an idnumber to avoid collisions'; $string['nomoreidnumber'] = 'Not using an idnumber to avoid collisions';
$string['none'] = 'None'; $string['none'] = 'None';
$string['noneditingteacher'] = 'Non-editing teacher';
$string['noneditingteacherdescription'] = 'Non-editing teachers can teach in courses and grade students, but may not alter activities.';
$string['nopendingcourses'] = 'There are no courses pending approval'; $string['nopendingcourses'] = 'There are no courses pending approval';
$string['nopotentialadmins'] = 'No potential admins'; $string['nopotentialadmins'] = 'No potential admins';
$string['nopotentialcreators'] = 'No potential course creators'; $string['nopotentialcreators'] = 'No potential course creators';

1467
lib/accesslib.php Executable file

File diff suppressed because it is too large Load diff

View file

@ -35,13 +35,13 @@ function upgrade_plugins($type, $dir, $return) {
unset($plugin); unset($plugin);
if ( is_readable($fullplug .'/version.php')) { if (is_readable($fullplug .'/version.php')) {
include_once($fullplug .'/version.php'); // defines $plugin with version etc include_once($fullplug .'/version.php'); // defines $plugin with version etc
} else { } else {
continue; // Nothing to do. continue; // Nothing to do.
} }
if ( is_readable($fullplug .'/db/'. $CFG->dbtype .'.php')) { if (is_readable($fullplug .'/db/'. $CFG->dbtype .'.php')) {
include_once($fullplug .'/db/'. $CFG->dbtype .'.php'); // defines upgrading function include_once($fullplug .'/db/'. $CFG->dbtype .'.php'); // defines upgrading function
} else { } else {
continue; continue;
@ -95,6 +95,9 @@ function upgrade_plugins($type, $dir, $return) {
if (modify_database($fullplug .'/db/'. $CFG->dbtype .'.sql')) { if (modify_database($fullplug .'/db/'. $CFG->dbtype .'.sql')) {
// OK so far, now update the plugins record // OK so far, now update the plugins record
set_config($pluginversion, $plugin->version); set_config($pluginversion, $plugin->version);
if (!update_capabilities($dir)) {
error('Could not set up the capabilities for '.$module->name.'!');
}
notify(get_string('modulesuccess', '', $plugin->name), 'notifysuccess'); notify(get_string('modulesuccess', '', $plugin->name), 'notifysuccess');
} else { } else {
notify('Installing '. $plugin->name .' FAILED!'); notify('Installing '. $plugin->name .' FAILED!');
@ -112,6 +115,9 @@ function upgrade_plugins($type, $dir, $return) {
$db->debug=false; $db->debug=false;
// OK so far, now update the plugins record // OK so far, now update the plugins record
set_config($pluginversion, $plugin->version); set_config($pluginversion, $plugin->version);
if (!update_capabilities($dir)) {
error('Could not update '.$plugin->name.' capabilities!');
}
notify(get_string('modulesuccess', '', $plugin->name), 'notifysuccess'); notify(get_string('modulesuccess', '', $plugin->name), 'notifysuccess');
} else { } else {
$db->debug=false; $db->debug=false;
@ -214,6 +220,8 @@ function upgrade_activity_modules($return) {
} }
upgrade_log_start(); upgrade_log_start();
print_heading($module->name .' module needs upgrading'); print_heading($module->name .' module needs upgrading');
// Run the upgrade function for the module.
$upgrade_function = $module->name.'_upgrade'; $upgrade_function = $module->name.'_upgrade';
if (function_exists($upgrade_function)) { if (function_exists($upgrade_function)) {
$db->debug=true; $db->debug=true;
@ -232,7 +240,14 @@ function upgrade_activity_modules($return) {
notify('Upgrading '. $module->name .' from '. $currmodule->version .' to '. $module->version .' FAILED!'); notify('Upgrading '. $module->name .' from '. $currmodule->version .' to '. $module->version .' FAILED!');
} }
} }
// Update the capabilities table?
if (!update_capabilities('mod/'.$module->name)) {
error('Could not update '.$module->name.' capabilities!');
}
$updated_modules = true; $updated_modules = true;
} else { } else {
upgrade_log_start(); upgrade_log_start();
error('Version mismatch: '. $module->name .' can\'t downgrade '. $currmodule->version .' -> '. $module->version .' !'); error('Version mismatch: '. $module->name .' can\'t downgrade '. $currmodule->version .' -> '. $module->version .' !');
@ -252,6 +267,9 @@ function upgrade_activity_modules($return) {
if (modify_database($fullmod .'/db/'. $CFG->dbtype .'.sql')) { if (modify_database($fullmod .'/db/'. $CFG->dbtype .'.sql')) {
$db->debug = false; $db->debug = false;
if ($module->id = insert_record('modules', $module)) { if ($module->id = insert_record('modules', $module)) {
if (!update_capabilities('mod/'.$module->name)) {
error('Could not set up the capabilities for '.$module->name.'!');
}
notify(get_string('modulesuccess', '', $module->name), 'notifysuccess'); notify(get_string('modulesuccess', '', $module->name), 'notifysuccess');
echo '<hr />'; echo '<hr />';
} else { } else {

View file

@ -1095,6 +1095,9 @@ function upgrade_blocks_plugins($continueto) {
if(!$upgradesuccess) { if(!$upgradesuccess) {
notify('Upgrading block '. $block->name .' from '. $currblock->version .' to '. $block->version .' FAILED!'); notify('Upgrading block '. $block->name .' from '. $currblock->version .' to '. $block->version .' FAILED!');
} }
if (!update_capabilities('block/'.$block->name)) {
notify('Could not update '.$block->name.' capabilities!');
}
else { else {
// OK so far, now update the block record // OK so far, now update the block record
$block->id = $currblock->id; $block->id = $currblock->id;
@ -1146,6 +1149,9 @@ function upgrade_blocks_plugins($continueto) {
} else { } else {
error($block->name .' block could not be added to the block list!'); error($block->name .' block could not be added to the block list!');
} }
if (!update_capabilities('block', $block->name)) {
notify('Could not set up '.$block->name.' capabilities!');
}
} else { } else {
error('Block '. $block->name .' tables could NOT be set up successfully!'); error('Block '. $block->name .' tables could NOT be set up successfully!');
} }

555
lib/db/access.php Normal file
View file

@ -0,0 +1,555 @@
<?php
//
// Capability definitions for Moodle core.
//
// The capabilities are loaded into the database table when the module is
// installed or updated. Whenever the capability definitions are updated,
// the module version number should be bumped up.
//
// The system has four possible values for a capability:
// CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT, and inherit (not set).
//
//
// CAPABILITY NAMING CONVENTION
//
// It is important that capability names are unique. The naming convention
// for capabilities that are specific to modules and blocks is as follows:
// [mod/block]/<component_name>:<capabilityname>
//
// component_name should be the same as the directory name of the mod or block.
//
// Core moodle capabilities are defined thus:
// moodle/<capabilityclass>:<capabilityname>
//
// Examples: mod/forum:viewpost
// block/recent_activity:view
// moodle/site:deleteuser
//
// The variable name for the capability definitions array follows the format
// $<componenttype>_<component_name>_capabilities
//
// For the core capabilities, the variable is $moodle_capabilities.
$moodle_capabilities = array(
'moodle/site:doanything' => array(
'captype' => 'admin',
'contextlevel' => CONTEXT_SYSTEM
),
'moodle/legacy:guest' => array(
'captype' => 'legacy',
'contextlevel' => CONTEXT_SYSTEM
),
'moodle/legacy:student' => array(
'captype' => 'legacy',
'contextlevel' => CONTEXT_SYSTEM
),
'moodle/legacy:teacher' => array(
'captype' => 'legacy',
'contextlevel' => CONTEXT_SYSTEM
),
'moodle/legacy:editingteacher' => array(
'captype' => 'legacy',
'contextlevel' => CONTEXT_SYSTEM
),
'moodle/legacy:coursecreator' => array(
'captype' => 'legacy',
'contextlevel' => CONTEXT_SYSTEM
),
'moodle/legacy:admin' => array(
'captype' => 'legacy',
'contextlevel' => CONTEXT_SYSTEM
),
'moodle/site:config' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_PREVENT,
'editingteacher' => CAP_PREVENT,
'coursecreator' => CAP_PREVENT,
'admin' => CAP_ALLOW
)
),
'moodle/site:import' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_PREVENT,
'editingteacher' => CAP_PREVENT,
'coursecreator' => CAP_PREVENT,
'admin' => CAP_ALLOW
)
),
'moodle/site:backup' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_PREVENT,
'editingteacher' => CAP_PREVENT,
'coursecreator' => CAP_PREVENT,
'admin' => CAP_ALLOW
)
),
'moodle/site:restore' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_PREVENT,
'editingteacher' => CAP_PREVENT,
'coursecreator' => CAP_PREVENT,
'admin' => CAP_ALLOW
)
),
'moodle/site:manageblocks' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_PREVENT,
'editingteacher' => CAP_PREVENT,
'coursecreator' => CAP_PREVENT,
'admin' => CAP_ALLOW
)
),
'moodle/user:create' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_PREVENT,
'editingteacher' => CAP_PREVENT,
'coursecreator' => CAP_PREVENT,
'admin' => CAP_ALLOW
)
),
'moodle/user:delete' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_PREVENT,
'editingteacher' => CAP_PREVENT,
'coursecreator' => CAP_PREVENT,
'admin' => CAP_ALLOW
)
),
'moodle/user:update' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_PREVENT,
'editingteacher' => CAP_PREVENT,
'coursecreator' => CAP_PREVENT,
'admin' => CAP_ALLOW
)
),
'moodle/user:viewdetails' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'moodle/role:assign' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_PREVENT,
'editingteacher' => CAP_PREVENT,
'coursecreator' => CAP_PREVENT,
'admin' => CAP_ALLOW
)
),
'moodle/role:manage' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_PREVENT,
'editingteacher' => CAP_PREVENT,
'coursecreator' => CAP_PREVENT,
'admin' => CAP_ALLOW
)
),
'moodle/category:create' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSECAT,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_PREVENT,
'editingteacher' => CAP_PREVENT,
'coursecreator' => CAP_PREVENT,
'admin' => CAP_ALLOW
)
),
'moodle/category:delete' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSECAT,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_PREVENT,
'editingteacher' => CAP_PREVENT,
'coursecreator' => CAP_PREVENT,
'admin' => CAP_ALLOW
)
),
'moodle/category:update' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSECAT,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_PREVENT,
'editingteacher' => CAP_PREVENT,
'coursecreator' => CAP_PREVENT,
'admin' => CAP_ALLOW
)
),
'moodle/category:visibility' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSECAT,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_PREVENT,
'editingteacher' => CAP_PREVENT,
'coursecreator' => CAP_PREVENT,
'admin' => CAP_ALLOW
)
),
'moodle/course:create' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_PREVENT,
'editingteacher' => CAP_PREVENT,
'coursecreator' => CAP_PREVENT,
'admin' => CAP_ALLOW
)
),
'moodle/course:delete' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_PREVENT,
'editingteacher' => CAP_PREVENT,
'coursecreator' => CAP_PREVENT,
'admin' => CAP_ALLOW
)
),
'moodle/course:update' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_PREVENT,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'moodle/course:view' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'moodle/course:visibility' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_PREVENT,
'editingteacher' => CAP_PREVENT,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'moodle/course:manageactivities' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'moodle/course:activityvisibility' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_PREVENT,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'moodle/course:viewhiddenactivities' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'moodle/course:viewparticipants' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'moodle/course:viewscales' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'moodle/course:managescales' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_PREVENT,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'moodle/course:managegroups' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_PREVENT,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'moodle/blog:view' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'moodle/blog:create' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'moodle/blog:manageofficialtags' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_PREVENT,
'editingteacher' => CAP_PREVENT,
'coursecreator' => CAP_PREVENT,
'admin' => CAP_ALLOW
)
),
'moodle/blog:managepersonaltags' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'moodle/blog:manageentries' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'moodle/calendar:manageownentries' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'moodle/calendar:manageentries' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
)
);
?>

View file

@ -2001,6 +2001,75 @@ function main_upgrade($oldversion=0) {
table_column('grade_letter', 'grade_low', 'grade_low', 'decimal(5,2)', '', '', '0.00', 'not null', ''); table_column('grade_letter', 'grade_low', 'grade_low', 'decimal(5,2)', '', '', '0.00', 'not null', '');
} }
if ($oldversion < 2006080400) {
execute_sql("CREATE TABLE {$CFG->prefix}role (
`id` int(10) NOT NULL auto_increment,
`name` varchar(255) NOT NULL default '',
`description` text NOT NULL default '',
`sortorder` int(10) NOT NULL default '0',
PRIMARY KEY (`id`)
)", true);
execute_sql("CREATE TABLE {$CFG->prefix}context (
`id` int(10) NOT NULL auto_increment,
`level` int(10) NOT NULL default '0',
`instanceid` int(10) NOT NULL default '0',
PRIMARY KEY (`id`)
)", true);
execute_sql("CREATE TABLE {$CFG->prefix}role_assignments (
`id` int(10) NOT NULL auto_increment,
`roleid` int(10) NOT NULL default '0',
`contextid` int(10) NOT NULL default '0',
`userid` int(10) NOT NULL default '0',
`hidden` int(1) NOT NULL default '0',
`timestart` int(10) NOT NULL default '0',
`timeend` int(10) NOT NULL default '0',
`timemodified` int(10) NOT NULL default '0',
`modifierid` int(10) NOT NULL default '0',
`enrol` varchar(20) NOT NULL default '',
`sortorder` int(10) NOT NULL default '0',
PRIMARY KEY (`id`)
)", true);
execute_sql("CREATE TABLE {$CFG->prefix}role_capabilities (
`id` int(10) NOT NULL auto_increment,
`contextid` int(10) NOT NULL default '0',
`roleid` int(10) NOT NULL default '0',
`capability` varchar(255) NOT NULL default '',
`permission` int(10) NOT NULL default '0',
`timemodified` int(10) NOT NULL default '0',
`modifierid` int(10) NOT NULL default '0',
PRIMARY KEY (`id`)
)", true);
execute_sql("CREATE TABLE {$CFG->prefix}role_deny_grant (
`id` int(10) NOT NULL auto_increment,
`roleid` int(10) NOT NULL default '0',
`unviewableroleid` int(10) NOT NULL default '0',
PRIMARY KEY (`id`)
)", true);
execute_sql("CREATE TABLE {$CFG->prefix}capabilities (
`id` int(10) NOT NULL auto_increment,
`name` varchar(150) NOT NULL default '',
`captype` varchar(50) NOT NULL default '',
`contextlevel` int(10) NOT NULL default '0',
`component` varchar(100) NOT NULL default '',
PRIMARY KEY (`id`)
)", true);
execute_sql("CREATE TABLE {$CFG->prefix}role_names (
`id` int(10) NOT NULL auto_increment,
`roleid` int(10) NOT NULL default '0',
`contextid` int(10) NOT NULL default '0',
`text` text NOT NULL default '',
PRIMARY KEY (`id`)
)", true);
}
return $result; return $result;
} }

View file

@ -899,6 +899,74 @@ CREATE TABLE prefix_blog_tag_instance (
PRIMARY KEY (`id`) PRIMARY KEY (`id`)
) TYPE=MyISAM COMMENT ='tag instance for blogs.'; ) TYPE=MyISAM COMMENT ='tag instance for blogs.';
###################################
# Roles tables
###################################
CREATE TABLE prefix_role (
`id` int(10) NOT NULL auto_increment,
`name` varchar(255) NOT NULL default '',
`description` text NOT NULL default '',
`sortorder` int(10) NOT NULL default '0',
PRIMARY KEY (`id`)
) TYPE=MyISAM COMMENT ='moodle roles';
CREATE TABLE prefix_context (
`id` int(10) NOT NULL auto_increment,
`level` int(10) NOT NULL default '0',
`instanceid` int(10) NOT NULL default '0',
PRIMARY KEY (`id`)
) TYPE=MyISAM COMMENT ='one of these must be set';
CREATE TABLE prefix_role_assignments (
`id` int(10) NOT NULL auto_increment,
`roleid` int(10) NOT NULL default '0',
`contextid` int(10) NOT NULL default '0',
`userid` int(10) NOT NULL default '0',
`hidden` int(1) NOT NULL default '0',
`timestart` int(10) NOT NULL default '0',
`timeend` int(10) NOT NULL default '0',
`timemodified` int(10) NOT NULL default '0',
`modifierid` int(10) NOT NULL default '0',
`enrol` varchar(20) NOT NULL default '',
`sortorder` int(10) NOT NULL default '0',
PRIMARY KEY (`id`)
) TYPE=MyISAM COMMENT ='assigning roles to different context';
CREATE TABLE prefix_role_capabilities (
`id` int(10) NOT NULL auto_increment,
`contextid` int(10) NOT NULL default '0',
`roleid` int(10) NOT NULL default '0',
`capability` varchar(255) NOT NULL default '',
`permission` int(10) NOT NULL default '0',
`timemodified` int(10) NOT NULL default '0',
`modifierid` int(10) NOT NULL default '0',
PRIMARY KEY (`id`)
) TYPE=MYISAM COMMENT ='overriding a capability for a particular role in a particular context';
CREATE TABLE prefix_role_deny_grant (
`id` int(10) NOT NULL auto_increment,
`roleid` int(10) NOT NULL default '0',
`unviewableroleid` int(10) NOT NULL default '0',
PRIMARY KEY (`id`)
) TYPE=MYISAM COMMENT ='this defines what role can touch (assign, override) what role';
CREATE TABLE prefix_capabilities (
`id` int(10) NOT NULL auto_increment,
`name` varchar(150) NOT NULL default '',
`captype` varchar(50) NOT NULL default '',
`contextlevel` int(10) NOT NULL default '0',
`component` varchar(100) NOT NULL default '',
PRIMARY KEY (`id`)
) TYPE=MYISAM COMMENT ='this defines all capabilities';
CREATE TABLE prefix_role_names (
`id` int(10) NOT NULL auto_increment,
`roleid` int(10) NOT NULL default '0',
`contextid` int(10) NOT NULL default '0',
`text` text NOT NULL default '',
PRIMARY KEY (`id`)
) TYPE=MYISAM COMMENT ='role names in native strings';
INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('user', 'view', 'user', 'CONCAT(firstname," ",lastname)'); INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('user', 'view', 'user', 'CONCAT(firstname," ",lastname)');
INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('course', 'user report', 'user', 'CONCAT(firstname," ",lastname)'); INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('course', 'user report', 'user', 'CONCAT(firstname," ",lastname)');

View file

@ -1617,6 +1617,68 @@ function main_upgrade($oldversion=0) {
//} //}
} }
if ($oldversion < 2006080400) {
modify_database('', "CREATE TABLE prefix_role (
id SERIAL PRIMARY KEY,
name varchar(255) NOT NULL default '',
description text NOT NULL default '',
sortorder integer NOT NULL default '0'
);");
modify_database('', "CREATE TABLE prefix_context (
id SERIAL PRIMARY KEY,
level integer NOT NULL default 0,
instanceid integer NOT NULL default 0
);");
modify_database('', "CREATE TABLE prefix_role_assignments (
id SERIAL PRIMARY KEY,
roleid interger NOT NULL default 0,
contextid interger NOT NULL default 0,
userid interger NOT NULL default 0,
hidden interger NOT NULL default 0,
timestart interger NOT NULL default 0,
timeend interger NOT NULL default 0,
timemodified interger NOT NULL default 0,
modifierid interger NOT NULL default 0,
enrol varchar(20) NOT NULL default '',
sortorder integer NOT NULL default '0'
);");
modify_database('', "CREATE TABLE prefix_role_capabilities (
id SERIAL PRIMARY KEY,
contextid interger NOT NULL default 0,
roleid interger NOT NULL default 0,
capability varchar(255) NOT NULL default '',
permission integer NOT NULL default 0,
timemodified interger NOT NULL default 0,
modifierid interger NOT NULL default 0
);");
modify_database('', "CREATE TABLE prefix_role_deny_grant (
id SERIAL PRIMARY KEY,
roleid integer NOT NULL default '0',
unviewableroleid integer NOT NULL default '0'
);");
modify_database('', "CREATE TABLE prefix_capabilities (
id SERIAL PRIMARY KEY,
name varchar(150) NOT NULL default '',
captype varchar(50) NOT NULL default '',
contextlevel integer NOT NULL default 0,
component varchar(100) NOT NULL default ''
);");
modify_database('', "CREATE TABLE prefix_role_names (
id SERIAL PRIMARY KEY,
roleid integer NOT NULL default 0,
contextid integer NOT NULL default 0,
text text NOT NULL default ''
);");
}
return $result; return $result;
} }

View file

@ -670,6 +670,68 @@ CREATE TABLE prefix_blog_tag_instance (
CREATE INDEX prefix_bti_entryid_idx ON prefix_blog_tag_instance (entryid); CREATE INDEX prefix_bti_entryid_idx ON prefix_blog_tag_instance (entryid);
CREATE INDEX prefix_bti_tagid_idx ON prefix_blog_tag_instance (tagid); CREATE INDEX prefix_bti_tagid_idx ON prefix_blog_tag_instance (tagid);
# Roles tables
CREATE TABLE prefix_role (
id SERIAL PRIMARY KEY,
name varchar(255) NOT NULL default '',
description text NOT NULL default '',
sortorder integer NOT NULL default '0'
);
CREATE TABLE prefix_context (
id SERIAL PRIMARY KEY,
level integer NOT NULL default 0,
instanceid integer NOT NULL default 0
);
CREATE TABLE prefix_role_assignments (
id SERIAL PRIMARY KEY,
roleid interger NOT NULL default 0,
contextid interger NOT NULL default 0,
userid interger NOT NULL default 0,
hidden interger NOT NULL default 0,
timestart interger NOT NULL default 0,
timeend interger NOT NULL default 0,
timemodified interger NOT NULL default 0,
modifierid interger NOT NULL default 0,
enrol varchar(20) NOT NULL default '',
sortorder integer NOT NULL default '0'
);
CREATE TABLE prefix_role_capabilities (
id SERIAL PRIMARY KEY,
contextid interger NOT NULL default 0,
roleid interger NOT NULL default 0,
capability varchar(255) NOT NULL default '',
permission integer NOT NULL default 0,
timemodified interger NOT NULL default 0,
modifierid interger NOT NULL default 0
);
CREATE TABLE prefix_role_deny_grant (
id SERIAL PRIMARY KEY,
roleid integer NOT NULL default '0',
unviewableroleid integer NOT NULL default '0'
);
CREATE TABLE prefix_capabilities (
id SERIAL PRIMARY KEY,
name varchar(150) NOT NULL default '',
captype varchar(50) NOT NULL default '',
contextlevel integer NOT NULL default 0,
component varchar(100) NOT NULL default ''
);
CREATE TABLE prefix_role_names (
id SERIAL PRIMARY KEY,
roleid integer NOT NULL default 0,
contextid integer NOT NULL default 0,
text text NOT NULL default ''
);
INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('user', 'view', 'user', 'firstname||\' \'||lastname'); INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('user', 'view', 'user', 'firstname||\' \'||lastname');
INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('course', 'user report', 'user', 'firstname||\' \'||lastname'); INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('course', 'user report', 'user', 'firstname||\' \'||lastname');
INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('course', 'view', 'course', 'fullname'); INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('course', 'view', 'course', 'fullname');

View file

@ -1,5 +1,8 @@
<?php // $Id$ <?php // $Id$
// this needs to be changed back
require_once('accesslib.php');
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
// // // //
// NOTICE OF COPYRIGHT // // NOTICE OF COPYRIGHT //
@ -1600,7 +1603,10 @@ function require_login($courseid=0, $autologinguest=true, $cm=null) {
print_header(); print_header();
notice(get_string('coursehidden'), $CFG->wwwroot .'/'); notice(get_string('coursehidden'), $CFG->wwwroot .'/');
} }
if (!empty($USER->student[$courseid]) or !empty($USER->teacher[$courseid]) or !empty($USER->admin)) {
$context = get_context_instance(CONTEXT_COURSE, $courseid);
if (has_capability('moodle/course:view', $context->id)) {
if (isset($USER->realuser)) { // Make sure the REAL person can also access this course if (isset($USER->realuser)) { // Make sure the REAL person can also access this course
if (!isteacher($courseid, $USER->realuser)) { if (!isteacher($courseid, $USER->realuser)) {
print_header(); print_header();
@ -2002,6 +2008,22 @@ function isadmin($userid=0) {
global $USER; global $USER;
static $admins, $nonadmins; static $admins, $nonadmins;
if (isset($CFG->rolesactive) && $CFG->rolesactive ===1) {
if ($courseid == 0) {
$context = get_context_instance(CONTEXT_SYSTEM, SITEID);
} else {
$context = get_context_instance(CONTEXT_COURSE, $courseid);
}
if (!$userid) {
return has_capability('moodle/legacy:admin', $context->id);
} else {
return has_capability('moodle/legacy:admin', $context->id, false, $userid);
}
}
if (!isset($admins)) { if (!isset($admins)) {
$admins = array(); $admins = array();
$nonadmins = array(); $nonadmins = array();
@ -2045,6 +2067,23 @@ function isteacher($courseid=0, $userid=0, $includeadmin=true) {
/// Is the user able to access this course as a teacher? /// Is the user able to access this course as a teacher?
global $USER, $CFG; global $USER, $CFG;
if (isset($CFG->rolesactive) && $CFG->rolesactive ===1) { // should be always
if ($courseid == 0) {
$context = get_context_instance(CONTEXT_SYSTEM, SITEID);
} else {
$context = get_context_instance(CONTEXT_COURSE, $courseid);
}
if (!$userid) {
return has_capability('moodle/legacy:teacher', $context->id);
} else {
return has_capability('moodle/legacy:teacher', $context->id, false, $userid);
}
}
// Old code follows, will be removed before 1.7 because it shouldn't run
if (empty($userid)) { // we are relying on $USER if (empty($userid)) { // we are relying on $USER
if (empty($USER) or empty($USER->id)) { // not logged in so can't be a teacher if (empty($USER) or empty($USER->id)) { // not logged in so can't be a teacher
return false; return false;
@ -2117,6 +2156,21 @@ function isteacherinanycourse($userid=0, $includeadmin=true) {
function isteacheredit($courseid, $userid=0, $ignorestudentview=false) { function isteacheredit($courseid, $userid=0, $ignorestudentview=false) {
global $USER; global $USER;
if (isset($CFG->rolesactive) && $CFG->rolesactive ===1) {
if ($courseid == 0) {
$context = get_context_instance(CONTEXT_SYSTEM, SITEID);
} else {
$context = get_context_instance(CONTEXT_COURSE, $courseid);
}
if (!$userid) {
return has_capability('moodle/legacy:edittingteacher', $context->id);
} else {
return has_capability('moodle/legacy:edittingteacher', $context->id, false, $userid);
}
}
// we can't edit in studentview // we can't edit in studentview
if (!empty($USER->studentview) and !$ignorestudentview) { if (!empty($USER->studentview) and !$ignorestudentview) {
return false; return false;
@ -2148,6 +2202,22 @@ function isteacheredit($courseid, $userid=0, $ignorestudentview=false) {
*/ */
function iscreator ($userid=0) { function iscreator ($userid=0) {
global $USER; global $USER;
if (isset($CFG->rolesactive) && $CFG->rolesactive ===1) {
if ($courseid == 0) {
$context = get_context_instance(CONTEXT_SYSTEM, SITEID);
} else {
$context = get_context_instance(CONTEXT_COURSE, $courseid);
}
if (!$userid) {
return has_capability('moodle/legacy:coursecreator', $context->id);
} else {
return has_capability('moodle/legacy:coursecreator', $context->id, false, $userid);
}
}
if (empty($USER->id)) { if (empty($USER->id)) {
return false; return false;
} }
@ -2177,6 +2247,22 @@ function iscreator ($userid=0) {
function isstudent($courseid, $userid=0) { function isstudent($courseid, $userid=0) {
global $USER, $CFG; global $USER, $CFG;
if (isset($CFG->rolesactive) && $CFG->rolesactive ===1) {
if ($courseid == 0) {
$context = get_context_instance(CONTEXT_SYSTEM, SITEID);
} else {
$context = get_context_instance(CONTEXT_COURSE, $courseid);
}
if (!$userid) {
return has_capability('moodle/legacy:student', $context->id);
} else {
return has_capability('moodle/legacy:student', $context->id, false, $userid);
}
}
if (empty($USER->id) and !$userid) { if (empty($USER->id) and !$userid) {
return false; return false;
} }

View file

@ -207,7 +207,11 @@
} }
reset_login_count(); reset_login_count();
$rolesconfig = get_config('', 'rolesactive');
if ($rolesconfig->value == 1) {
load_user_capability(); // load user's capabilities
}
redirect($urltogo); redirect($urltogo);
exit; exit;

View file

@ -0,0 +1,79 @@
<?php
//
// Capability definitions for the assignment module.
//
// The capabilities are loaded into the database table when the module is
// installed or updated. Whenever the capability definitions are updated,
// the module version number should be bumped up.
//
// The system has four possible values for a capability:
// CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT, and inherit (not set).
//
//
// CAPABILITY NAMING CONVENTION
//
// It is important that capability names are unique. The naming convention
// for capabilities that are specific to modules and blocks is as follows:
// [mod/block]/<component_name>:<capabilityname>
//
// component_name should be the same as the directory name of the mod or block.
//
// Core moodle capabilities are defined thus:
// moodle/<capabilityclass>:<capabilityname>
//
// Examples: mod/forum:viewpost
// block/recent_activity:view
// moodle/site:deleteuser
//
// The variable name for the capability definitions array follows the format
// $<componenttype>_<component_name>_capabilities
//
// For the core capabilities, the variable is $moodle_capabilities.
$mod_assignment_capabilities = array(
'mod/assignment:view' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/assignment:submit' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/assignment:grade' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
)
);
?>

View file

@ -107,7 +107,10 @@ class assignment_base {
*/ */
function view() { function view() {
add_to_log($this->course->id, "assignment", "view", "view.php?id={$this->cm->id}", $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
has_capability('mod/assignment:view', $context->id, true);
add_to_log($this->course->id, "assignment", "view", "view.php?id={$this->cm->id}",
$this->assignment->id, $this->cm->id); $this->assignment->id, $this->cm->id);
$this->view_header(); $this->view_header();
@ -273,9 +276,13 @@ class assignment_base {
$submitted = ''; $submitted = '';
if (isteacher($this->course->id)) { $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
if (!isteacheredit($this->course->id) and (groupmode($this->course, $this->cm) == SEPARATEGROUPS)) { if (has_capability('mod/assignment:grade', $context->id) && (groupmode($this->course, $this->cm) == SEPARATEGROUPS)) {
$count = $this->count_real_submissions($this->currentgroup); // Only their group
// if this user can mark and is put in a group
// then he can only see/mark submission in his own groups
if (user_group($this->course->id, $USER->id)) {
$count = $this->count_real_submissions($this->currentgroup); // Only their groups
} else { } else {
$count = $this->count_real_submissions(); // Everyone $count = $this->count_real_submissions(); // Everyone
} }
@ -2349,7 +2356,9 @@ function assignment_print_overview($courses, &$htmlarray) {
$str .= '<div class="info">'.$strduedateno.'</div>'; $str .= '<div class="info">'.$strduedateno.'</div>';
} }
if (isteacher($assignment->course)) { // if (isteacher($assignment->course)) {
$context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
if (has_capability('mod/assignment:grade', $context->id)) {
$submissions = count_records_sql("SELECT COUNT(*) $submissions = count_records_sql("SELECT COUNT(*)
FROM {$CFG->prefix}assignment_submissions a, FROM {$CFG->prefix}assignment_submissions a,
{$CFG->prefix}user_students s, {$CFG->prefix}user_students s,

View file

@ -14,7 +14,10 @@ class assignment_online extends assignment_base {
global $USER; global $USER;
$submission = $this->get_submission(); $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
has_capability('mod/assignment:view', $context->id, true);
$submission = $this->get_submission();
//Guest can not submit nor edit an assignment (bug: 4604) //Guest can not submit nor edit an assignment (bug: 4604)
if (isguest($USER->id)) { if (isguest($USER->id)) {
@ -56,27 +59,29 @@ class assignment_online extends assignment_base {
notify(get_string('submissionsaved', 'assignment')); notify(get_string('submissionsaved', 'assignment'));
} }
print_simple_box_start('center', '70%', '', '', 'generalbox', 'online'); if (has_capability('mod/assignment:submit', $context->id)) {
if ($editmode) { print_simple_box_start('center', '70%', '', '', 'generalbox', 'online');
$this->view_edit_form($submission); if ($editmode) {
} else { $this->view_edit_form($submission);
if ($submission) { } else {
echo format_text($submission->data1, $submission->data2); if ($submission) {
} else if (isguest($USER->id)) { //fix for #4604 echo format_text($submission->data1, $submission->data2);
echo '<center>'. get_string('guestnosubmit', 'assignment').'</center>'; } else if (isguest($USER->id)) { //fix for #4604
} else if ($this->isopen()){ //fix for #4206 echo '<center>'. get_string('guestnosubmit', 'assignment').'</center>';
echo '<center>'.get_string('emptysubmission', 'assignment').'</center>'; } else if ($this->isopen()){ //fix for #4206
} echo '<center>'.get_string('emptysubmission', 'assignment').'</center>';
if ($editable) { }
print_single_button('view.php', array('id'=>$this->cm->id,'edit'=>'1'), if ($editable) {
get_string('editmysubmission', 'assignment')); print_single_button('view.php', array('id'=>$this->cm->id,'edit'=>'1'),
} get_string('editmysubmission', 'assignment'));
} }
print_simple_box_end(); }
print_simple_box_end();
if ($editmode and $this->usehtmleditor) { if ($editmode and $this->usehtmleditor) {
use_html_editor(); // MUst be at the end of the page use_html_editor(); // MUst be at the end of the page
} }
}
$this->view_feedback(); $this->view_feedback();

View file

@ -48,6 +48,9 @@ class assignment_uploadsingle extends assignment_base {
global $USER; global $USER;
$context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
has_capability('mod/assignment:view', $context->id, true);
add_to_log($this->course->id, "assignment", "view", "view.php?id={$this->cm->id}", $this->assignment->id, $this->cm->id); add_to_log($this->course->id, "assignment", "view", "view.php?id={$this->cm->id}", $this->assignment->id, $this->cm->id);
$this->view_header(); $this->view_header();
@ -66,7 +69,7 @@ class assignment_uploadsingle extends assignment_base {
} }
} }
if (!isguest($USER->id) && $this->isopen() && (!$filecount || $this->assignment->resubmit || !$submission->timemarked)) { if (has_capability('mod/assignment:submit', $context->id) && $this->isopen() && (!$filecount || $this->assignment->resubmit || !$submission->timemarked)) {
$this->view_upload_form(); $this->view_upload_form();
} }

View file

@ -5,7 +5,7 @@
// This fragment is called by /admin/index.php // This fragment is called by /admin/index.php
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
$module->version = 2005060100; $module->version = 2006080800;
$module->requires = 2005031000; // Requires this Moodle version $module->requires = 2005031000; // Requires this Moodle version
$module->cron = 60; $module->cron = 60;

80
mod/chat/db/access.php Normal file
View file

@ -0,0 +1,80 @@
<?php
//
// Capability definitions for the chat module.
//
// The capabilities are loaded into the database table when the module is
// installed or updated. Whenever the capability definitions are updated,
// the module version number should be bumped up.
//
// The system has four possible values for a capability:
// CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT, and inherit (not set).
//
//
// CAPABILITY NAMING CONVENTION
//
// It is important that capability names are unique. The naming convention
// for capabilities that are specific to modules and blocks is as follows:
// [mod/block]/<component_name>:<capabilityname>
//
// component_name should be the same as the directory name of the mod or block.
//
// Core moodle capabilities are defined thus:
// moodle/<capabilityclass>:<capabilityname>
//
// Examples: mod/forum:viewpost
// block/recent_activity:view
// moodle/site:deleteuser
//
// The variable name for the capability definitions array follows the format
// $<componenttype>_<component_name>_capabilities
//
// For the core capabilities, the variable is $moodle_capabilities.
$mod_chat_capabilities = array(
'mod/chat:chat' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/chat:readlog' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/chat:deletelog' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
)
);
?>

View file

@ -18,12 +18,16 @@
error('Course Module ID was incorrect'); error('Course Module ID was incorrect');
} }
require_login($course->id, false, $cm); $context = get_context_instance(CONTEXT_MODULE, $cm->id);
require_login($course->id, false, $cm);
has_capability('mod/chat:chat',$context->id, true);
/*
if (isguest()) { if (isguest()) {
error('Guest does not have access to chat rooms'); error('Guest does not have access to chat rooms');
} }
*/
if (!$cm->visible and !isteacher($course->id)) { if (!$cm->visible and !isteacher($course->id)) {
print_header(); print_header();
notice(get_string("activityiscurrentlyhidden")); notice(get_string("activityiscurrentlyhidden"));

View file

@ -199,7 +199,19 @@ function chat_print_recent_activity($course, $isteacher, $timestart) {
$current = 0; $current = 0;
} }
if ($chat = get_record('chat', 'id', $chatuser->chatid)) { if ($chat = get_record('chat', 'id', $chatuser->chatid)) {
if (!($isteacher or instance_is_visible('chat', $chat))) { // Chat hidden to students
// we find the course module id
$chatmod = get_record('modules', 'name', 'chat');
$SQL = "select * from {$CFG->prefix}course_modules where
course = $course->id
and module = $chatmod->id
and instance = $chat->id";
$cm = get_records_sql($SQL);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
// needs to be fixed
if (!(has_capability('mod/chat:readlog', $context->id) or instance_is_visible('chat', $chat))) { // Chat hidden to students
//if (!($isteacher or instance_is_visible('chat', $chat))) { // Chat hidden to students
continue; continue;
} }
if (!$outputstarted) { if (!$outputstarted) {

View file

@ -21,14 +21,16 @@
error('Course is misconfigured'); error('Course is misconfigured');
} }
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
require_login($course->id, false, $cm); require_login($course->id, false, $cm);
$isteacher = isteacher($course->id); $isteacher = isteacher($course->id);
$isteacheredit = isteacheredit($course->id); $isteacheredit = isteacheredit($course->id);
if (isguest() or (!$isteacher and !$chat->studentlogs)) { //if (isguest() or (!$isteacher and !$chat->studentlogs)) {
error('You can not view these chat reports'); //error('You can not view these chat reports');
} //}
has_capability('mod/chat:readlog', $context->id, true); // if can't even read, kill
add_to_log($course->id, 'chat', 'report', "report.php?id=$cm->id", $chat->id, $cm->id); add_to_log($course->id, 'chat', 'report', "report.php?id=$cm->id", $chat->id, $cm->id);
@ -62,7 +64,8 @@
$groupselect = ""; $groupselect = "";
} }
if ($deletesession and $isteacheredit) { //if ($deletesession and $isteacheredit) {
if ($deletesession and has_capability('mod/chat:deletelog', $context->id)) {
notice_yesno(get_string('deletesessionsure', 'chat'), notice_yesno(get_string('deletesessionsure', 'chat'),
"report.php?id=$cm->id&amp;deletesession=1&amp;confirmdelete=1&amp;start=$start&amp;end=$end&amp;sesskey=$USER->sesskey", "report.php?id=$cm->id&amp;deletesession=1&amp;confirmdelete=1&amp;start=$start&amp;end=$end&amp;sesskey=$USER->sesskey",
"report.php?id=$cm->id"); "report.php?id=$cm->id");
@ -86,7 +89,8 @@
print_simple_box_end('center'); print_simple_box_end('center');
} }
if (!$deletesession or !$isteacheredit) { if (!$deletesession or !has_capability('mod/chat:deletelog', $context->id)) {
//if (!$deletesession or !$isteacheredit) {
print_continue("report.php?id=$cm->id"); print_continue("report.php?id=$cm->id");
} }
@ -120,7 +124,8 @@
/// Delete a session if one has been specified /// Delete a session if one has been specified
if ($deletesession and $isteacheredit and $confirmdelete and $start and $end and confirm_sesskey()) { if ($deletesession and has_capability('mod/chat:deletelog', $context->id) and $confirmdelete and $start and $end and confirm_sesskey()) {
//if ($deletesession and $isteacheredit and $confirmdelete and $start and $end and confirm_sesskey()) {
delete_records_select('chat_messages', "chatid = $chat->id AND delete_records_select('chat_messages', "chatid = $chat->id AND
timestamp >= '$start' AND timestamp >= '$start' AND
timestamp <= '$end' $groupselect"); timestamp <= '$end' $groupselect");
@ -181,14 +186,15 @@
foreach ($sessionusers as $sessionuser => $usermessagecount) { foreach ($sessionusers as $sessionuser => $usermessagecount) {
if ($user = get_record('user', 'id', $sessionuser)) { if ($user = get_record('user', 'id', $sessionuser)) {
print_user_picture($user->id, $course->id, $user->picture); print_user_picture($user->id, $course->id, $user->picture);
echo '&nbsp;'.fullname($user, $isteacher); echo '&nbsp;'.fullname($user, $isteacher); // need to fix this
echo "&nbsp;($usermessagecount)<br />"; echo "&nbsp;($usermessagecount)<br />";
} }
} }
echo '<p align="right">'; echo '<p align="right">';
echo "<a href=\"report.php?id=$cm->id&amp;start=$sessionstart&amp;end=$sessionend\">$strseesession</a>"; echo "<a href=\"report.php?id=$cm->id&amp;start=$sessionstart&amp;end=$sessionend\">$strseesession</a>";
if ($isteacheredit) { //if ($isteacheredit)
if (has_capability('mod/chat:deletelog', $context->id)) {
echo "<br /><a href=\"report.php?id=$cm->id&amp;start=$sessionstart&amp;end=$sessionend&amp;deletesession=1\">$strdeletesession</a>"; echo "<br /><a href=\"report.php?id=$cm->id&amp;start=$sessionstart&amp;end=$sessionend&amp;deletesession=1\">$strdeletesession</a>";
} }
echo '</p>'; echo '</p>';

View file

@ -5,7 +5,7 @@
/// This fragment is called by moodle_needs_upgrading() and /admin/index.php /// This fragment is called by moodle_needs_upgrading() and /admin/index.php
///////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////
$module->version = 2005031000; // The (date) version of this module $module->version = 2006080800; // The (date) version of this module
$module->requires = 2005031000; // Requires this Moodle version $module->requires = 2005031000; // Requires this Moodle version
$module->cron = 300; // How often should cron check this module (seconds)? $module->cron = 300; // How often should cron check this module (seconds)?

View file

@ -40,9 +40,12 @@
} }
} }
require_course_login($course, true, $cm); require_course_login($course, true, $cm);
add_to_log($course->id, 'chat', 'view', "view.php?id=$cm->id", $chat->id, $cm->id); $context = get_context_instance(CONTEXT_MODULE, $cm->id);
add_to_log($course->id, 'chat', 'view', "view.php?id=$cm->id", $chat->id, $cm->id);
// Initialize $PAGE, compute blocks // Initialize $PAGE, compute blocks
@ -73,7 +76,8 @@
echo '<td id="middle-column">'; echo '<td id="middle-column">';
if (($chat->studentlogs or isteacher($course->id)) and !isguest()) { if ($chat->studentlogs or has_capability('mod/chat:readlog',$context->id)) {
//if (($chat->studentlogs or isteacher($course->id)) and !isguest()) {
echo '<div class="reportlink">'; echo '<div class="reportlink">';
echo "<a href=\"report.php?id=$cm->id\">". echo "<a href=\"report.php?id=$cm->id\">".
get_string('viewreport', 'chat').'</a>'; get_string('viewreport', 'chat').'</a>';
@ -99,13 +103,14 @@
/// Print the main part of the page /// Print the main part of the page
if (!isguest()) { //if (!isguest()) {
if (has_capability('mod/chat:chat',$context->id, true)) {
print_simple_box_start('center'); print_simple_box_start('center');
link_to_popup_window ("/mod/chat/gui_$CFG->chat_method/index.php?id=$chat->id$groupparam", link_to_popup_window ("/mod/chat/gui_$CFG->chat_method/index.php?id=$chat->id$groupparam",
"chat$course->id$chat->id$groupparam", "$strenterchat", 500, 700, get_string('modulename', 'chat')); "chat$course->id$chat->id$groupparam", "$strenterchat", 500, 700, get_string('modulename', 'chat'));
print_simple_box_end(); print_simple_box_end();
} else { } else {
/*
$wwwroot = $CFG->wwwroot.'/login/index.php'; $wwwroot = $CFG->wwwroot.'/login/index.php';
if (!empty($CFG->loginhttps)) { if (!empty($CFG->loginhttps)) {
$wwwroot = str_replace('http:','https:', $wwwroot); $wwwroot = str_replace('http:','https:', $wwwroot);
@ -116,6 +121,7 @@
print_footer($course); print_footer($course);
exit; exit;
*/
} }

93
mod/choice/db/access.php Normal file
View file

@ -0,0 +1,93 @@
<?php
//
// Capability definitions for the choice module.
//
// The capabilities are loaded into the database table when the module is
// installed or updated. Whenever the capability definitions are updated,
// the module version number should be bumped up.
//
// The system has four possible values for a capability:
// CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT, and inherit (not set).
//
//
// CAPABILITY NAMING CONVENTION
//
// It is important that capability names are unique. The naming convention
// for capabilities that are specific to modules and blocks is as follows:
// [mod/block]/<component_name>:<capabilityname>
//
// component_name should be the same as the directory name of the mod or block.
//
// Core moodle capabilities are defined thus:
// moodle/<capabilityclass>:<capabilityname>
//
// Examples: mod/forum:viewpost
// block/recent_activity:view
// moodle/site:deleteuser
//
// The variable name for the capability definitions array follows the format
// $<componenttype>_<component_name>_capabilities
//
// For the core capabilities, the variable is $moodle_capabilities.
$mod_choice_capabilities = array(
'mod/choice:choose' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/choice:readresponses' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/choice:deleteresponses' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/choice:downloadresponses' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
)
);
?>

View file

@ -155,9 +155,11 @@ $cdisplay = array();
if (isset($text)) { //make sure there are no dud entries in the db with blank text values. if (isset($text)) { //make sure there are no dud entries in the db with blank text values.
$countanswers = (get_records("choice_answers", "optionid", $optionid)); $countanswers = (get_records("choice_answers", "optionid", $optionid));
$countans = 0; $countans = 0;
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
if (!empty($countanswers)) { if (!empty($countanswers)) {
foreach ($countanswers as $ca) { //only return enrolled users. foreach ($countanswers as $ca) { //only return enrolled users.
if (isstudent($cm->course, $ca->userid) or isteacher($cm->course, $ca->userid)) { if (has_capability('mod/choice:choose', $context->id)) {
//if (isstudent($cm->course, $ca->userid) or isteacher($cm->course, $ca->userid)) {
$countans = $countans+1; $countans = $countans+1;
} }
} }
@ -254,12 +256,13 @@ $cdisplay = array();
function choice_user_submit_response($formanswer, $choice, $userid, $courseid, $cm) { function choice_user_submit_response($formanswer, $choice, $userid, $courseid, $cm) {
$current = get_record('choice_answers', 'choiceid', $choice->id, 'userid', $userid); $current = get_record('choice_answers', 'choiceid', $choice->id, 'userid', $userid);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
$countanswers = get_records("choice_answers", "optionid", $formanswer); $countanswers = get_records("choice_answers", "optionid", $formanswer);
if ($countanswers) { if ($countanswers) {
$countans = 0; $countans = 0;
foreach ($countanswers as $ca) { //only return enrolled users. foreach ($countanswers as $ca) { //only return enrolled users.
if (isstudent($courseid, $ca->userid) or isteacher($courseid, $ca->userid)) { if (has_capability('mod/choice:choose', $context->id)) {
//if (isstudent($courseid, $ca->userid) or isteacher($courseid, $ca->userid)) {
$countans = $countans+1; $countans = $countans+1;
} }
} }
@ -300,10 +303,12 @@ $current = get_record('choice_answers', 'choiceid', $choice->id, 'userid', $user
function choice_show_reportlink($choice, $courseid, $cmid) { function choice_show_reportlink($choice, $courseid, $cmid) {
$context = get_context_instance(CONTEXT_MODULE, $cmid);
if ( $allanswers = get_records("choice_answers", "choiceid", $choice->id)) { if ( $allanswers = get_records("choice_answers", "choiceid", $choice->id)) {
$responsecount = 0; $responsecount = 0;
foreach ($allanswers as $aa) { foreach ($allanswers as $aa) {
if (isstudent($courseid, $aa->userid) or isteacher($courseid, $aa->userid)) { //check to make sure user is enrolled in course. if (has_capability('mod/choice:readresponses', $context->id)) {
//if (isstudent($courseid, $aa->userid) or isteacher($courseid, $aa->userid)) { //check to make sure user is enrolled in course.
$responsecount++; $responsecount++;
} }
} }
@ -318,6 +323,7 @@ function choice_show_reportlink($choice, $courseid, $cmid) {
function choice_show_results($choice, $course, $cm, $forcepublish='') { function choice_show_results($choice, $course, $cm, $forcepublish='') {
global $CFG, $COLUMN_HEIGHT, $USER; global $CFG, $COLUMN_HEIGHT, $USER;
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
print_heading(get_string("responses", "choice")); print_heading(get_string("responses", "choice"));
if (empty($forcepublish)) { //alow the publish setting to be overridden if (empty($forcepublish)) { //alow the publish setting to be overridden
$forcepublish = $choice->publish; $forcepublish = $choice->publish;
@ -374,11 +380,11 @@ function choice_show_results($choice, $course, $cm, $forcepublish='') {
switch ($forcepublish) { switch ($forcepublish) {
case CHOICE_PUBLISH_NAMES: case CHOICE_PUBLISH_NAMES:
$isteacher = isteacher($course->id); //$isteacher = isteacher($course->id);
$tablewidth = (int) (100.0 / count($useranswer)); $tablewidth = (int) (100.0 / count($useranswer));
if (has_capability('mod/choice:readresponses', $context->id)) {
if (isteacher($course->id, $USER->id)) { //if (isteacher($course->id, $USER->id)) {
echo '<div id="tablecontainer">'; echo '<div id="tablecontainer">';
echo '<form id="attemptsform" method="post" action="'.$_SERVER['PHP_SELF'].'" onsubmit="var menu = document.getElementById(\'menuaction\'); return (menu.options[menu.selectedIndex].value == \'delete\' ? \''.addslashes(get_string('deleteattemptcheck','quiz')).'\' : true);">'; echo '<form id="attemptsform" method="post" action="'.$_SERVER['PHP_SELF'].'" onsubmit="var menu = document.getElementById(\'menuaction\'); return (menu.options[menu.selectedIndex].value == \'delete\' ? \''.addslashes(get_string('deleteattemptcheck','quiz')).'\' : true);">';
echo '<input type="hidden" name="id" value="'.$cm->id.'" />'; echo '<input type="hidden" name="id" value="'.$cm->id.'" />';
@ -414,6 +420,7 @@ function choice_show_results($choice, $course, $cm, $forcepublish='') {
echo "<table width=\"100%\">"; echo "<table width=\"100%\">";
foreach ($userlist as $user) { foreach ($userlist as $user) {
// this needs to be fixed
if (!($optionid==0 && isadmin($user->id)) && !($optionid==0 && isteacher($course->id, $user->id) && !(isteacheredit($course->id, $user->id)) ) ) { //make sure admins and hidden teachers are not shown in not answered yet column. if (!($optionid==0 && isadmin($user->id)) && !($optionid==0 && isteacher($course->id, $user->id) && !(isteacheredit($course->id, $user->id)) ) ) { //make sure admins and hidden teachers are not shown in not answered yet column.
echo "<tr>"; echo "<tr>";
if (isteacher($course->id, $USER->id) && !($optionid==0)) { if (isteacher($course->id, $USER->id) && !($optionid==0)) {
@ -444,6 +451,7 @@ function choice_show_results($choice, $course, $cm, $forcepublish='') {
$countans = 0; $countans = 0;
if (!empty($countanswers)) { if (!empty($countanswers)) {
foreach ($countanswers as $ca) { //only return enrolled users. foreach ($countanswers as $ca) { //only return enrolled users.
// needs fixing too
if (isstudent($course->id, $ca->userid) or isteacher($course->id, $ca->userid)) { if (isstudent($course->id, $ca->userid) or isteacher($course->id, $ca->userid)) {
$countans = $countans+1; $countans = $countans+1;
} }
@ -462,7 +470,8 @@ function choice_show_results($choice, $course, $cm, $forcepublish='') {
} }
/// Print "Select all" etc. /// Print "Select all" etc.
if (isteacher($course->id, $USER->id)) { if (has_capability('mod/choice:readresponses', $context->id)) {
//if (isteacher($course->id, $USER->id)) {
echo '<tr><td><p>'; echo '<tr><td><p>';
echo '<tr><td>'; echo '<tr><td>';
echo '<a href="javascript:select_all_in(\'DIV\',null,\'tablecontainer\');">'.get_string('selectall', 'quiz').'</a> / '; echo '<a href="javascript:select_all_in(\'DIV\',null,\'tablecontainer\');">'.get_string('selectall', 'quiz').'</a> / ';
@ -479,7 +488,8 @@ function choice_show_results($choice, $course, $cm, $forcepublish='') {
echo "</tr></table>"; echo "</tr></table>";
if (isteacher($course->id, $USER->id)) { //if (isteacher($course->id, $USER->id)) {
if (has_capability('mod/choice:readresponses', $context->id)) {
echo "</form></div>"; echo "</form></div>";
} }
break; break;

View file

@ -18,9 +18,13 @@
require_login($course->id, false, $cm); require_login($course->id, false, $cm);
if (!isteacher($course->id)) { $context = get_context_instance(CONTEXT_MODULE, $cm->id);
error("Only teachers can look at this page");
} has_capability('mod/choice:readresponses', $context->id, true);
//if (!isteacher($course->id)) {
// error("Only teachers can look at this page");
//}
if (!$choice = choice_get_choice($cm->instance)) { if (!$choice = choice_get_choice($cm->instance)) {
error("Course module is incorrect"); error("Course module is incorrect");
@ -32,7 +36,8 @@
add_to_log($course->id, "choice", "report", "report.php?id=$cm->id", "$choice->id",$cm->id); add_to_log($course->id, "choice", "report", "report.php?id=$cm->id", "$choice->id",$cm->id);
if ($action == 'delete') { //some responses need to be deleted if ($action == 'delete' && has_capability('mod/choice:deleteresponses',$context->id, true)) {
//if ($action == 'delete') { //some responses need to be deleted
$attemptids = isset($_POST['attemptid']) ? $_POST['attemptid'] : array(); //get array of repsonses to delete. $attemptids = isset($_POST['attemptid']) ? $_POST['attemptid'] : array(); //get array of repsonses to delete.
choice_delete_responses($attemptids); //delete responses. choice_delete_responses($attemptids); //delete responses.
redirect("report.php?id=$cm->id"); redirect("report.php?id=$cm->id");
@ -81,7 +86,8 @@
ksort($useranswer); ksort($useranswer);
//print spreadsheet if one is asked for: //print spreadsheet if one is asked for:
if ($download == "xls") { //if ($download == "xls") {
if ($download == "xls" && has_capability('mod/choice:downloadresponses', $context->id, true)) {
require_once("$CFG->libdir/excellib.class.php"); require_once("$CFG->libdir/excellib.class.php");
/// Calculate file name /// Calculate file name
@ -138,7 +144,8 @@
exit; exit;
} }
// print text file // print text file
if ($download == "txt") { //if ($download == "txt") {
if ($download == "txt" && has_capability('mod/choice:downloadresponses', $context->id, true)) {
$filename = clean_filename("$course->shortname ".strip_tags(format_string($choice->name,true))).'.txt'; $filename = clean_filename("$course->shortname ".strip_tags(format_string($choice->name,true))).'.txt';
header("Content-Type: application/download\n"); header("Content-Type: application/download\n");

View file

@ -5,7 +5,7 @@
// This fragment is called by /admin/index.php // This fragment is called by /admin/index.php
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
$module->version = 2006020900; $module->version = 2006080800;
$module->requires = 2005021600; // Requires this Moodle version $module->requires = 2005021600; // Requires this Moodle version
$module->cron = 0; $module->cron = 0;

View file

@ -16,6 +16,9 @@
} }
require_course_login($course, false, $cm); require_course_login($course, false, $cm);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
has_capability('mod/choice:choose', $context->id, true);
if (!$choice = choice_get_choice($cm->instance)) { if (!$choice = choice_get_choice($cm->instance)) {
error("Course module is incorrect"); error("Course module is incorrect");
@ -30,8 +33,8 @@
if ($form = data_submitted()) { if ($form = data_submitted()) {
$timenow = time(); $timenow = time();
if (has_capability('mod/choice:deleteresponses', $context->id)) {
if (isteacher($course->id, $USER->id)) { //if (isteacher($course->id, $USER->id)) {
if ($action == 'delete') { //some responses need to be deleted if ($action == 'delete') { //some responses need to be deleted
choice_delete_responses($attemptids); //delete responses. choice_delete_responses($attemptids); //delete responses.
redirect("view.php?id=$cm->id"); redirect("view.php?id=$cm->id");
@ -56,8 +59,8 @@
"<a href=\"index.php?id=$course->id\">$strchoices</a> -> ".format_string($choice->name), "", "", true, "<a href=\"index.php?id=$course->id\">$strchoices</a> -> ".format_string($choice->name), "", "", true,
update_module_button($cm->id, $course->id, $strchoice), navmenu($course, $cm)); update_module_button($cm->id, $course->id, $strchoice), navmenu($course, $cm));
if (has_capability('mod/choice:readresponses', $context->id)) {
if (isteacher($course->id)) { //if (isteacher($course->id)) {
choice_show_reportlink($choice, $course->id, $cm->id); choice_show_reportlink($choice, $course->id, $cm->id);
} else if (!$cm->visible) { } else if (!$cm->visible) {
notice(get_string("activityiscurrentlyhidden")); notice(get_string("activityiscurrentlyhidden"));

View file

@ -27,14 +27,17 @@
require_login($course->id); require_login($course->id);
if ($commentid) { $cm = data_get_cm($data);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
if ($commentid) {
if (! $comment = get_record('data_comments', 'id', $commentid)) { if (! $comment = get_record('data_comments', 'id', $commentid)) {
error('Comment ID is misconfigured'); error('Comment ID is misconfigured');
} }
if ($comment->recordid != $record->id) { if ($comment->recordid != $record->id) {
error('Comment ID is misconfigured'); error('Comment ID is misconfigured');
} }
if (!isteacher($course->id) && $comment->userid != $USER->id) { if (!has_capability('mod/data:managecomments', $context->id) && $comment->userid != $USER->id) {
error('Comment is not yours to edit!'); error('Comment is not yours to edit!');
} }
} }

150
mod/data/db/access.php Normal file
View file

@ -0,0 +1,150 @@
<?php
//
// Capability definitions for the data module.
//
// The capabilities are loaded into the database table when the module is
// installed or updated. Whenever the capability definitions are updated,
// the module version number should be bumped up.
//
// The system has four possible values for a capability:
// CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT, and inherit (not set).
//
//
// CAPABILITY NAMING CONVENTION
//
// It is important that capability names are unique. The naming convention
// for capabilities that are specific to modules and blocks is as follows:
// [mod/block]/<component_name>:<capabilityname>
//
// component_name should be the same as the directory name of the mod or block.
//
// Core moodle capabilities are defined thus:
// moodle/<capabilityclass>:<capabilityname>
//
// Examples: mod/forum:viewpost
// block/recent_activity:view
// moodle/site:deleteuser
//
// The variable name for the capability definitions array follows the format
// $<componenttype>_<component_name>_capabilities
//
// For the core capabilities, the variable is $moodle_capabilities.
$mod_data_capabilities = array(
'mod/data:readentry' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/data:writeentry' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/data:comment' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/data:rate' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/data:approve' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/data:manageentries' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/data:managecomments' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/data:managetemplates' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
)
);
?>

View file

@ -92,6 +92,56 @@ CREATE TABLE prefix_data_ratings (
rating integer NOT NULL default '0' rating integer NOT NULL default '0'
); );
# Roles tables
CREATE TABLE prefix_roles (
`id` SERIAL PRIMARY KEY,
`name` varchar(255) NOT NULL default '',
`description` text NOT NULL default '',
`priority` decimal(2,2) NOT NULL default '0',
);
CREATE TABLE prefix_contexts (
`id` SERIAL PRIMARY KEY,
`system` int(1) NOT NULL default '0',
`metacourseid` int(10) NOT NULL default '0',
`coursecatid` int(10) NOT NULL default '0',
`courseid` int(10) NOT NULL default '0',
`moduleinstance` int(10) NOT NULL default '0',
`userid` int(10) NOT NULL default '0',
);
CREATE TABLE prefix_role_assignments (
`id` SERIAL PRIMARY KEY,
`roldid` int(10) NOT NULL default '0',
`contextid` int(10) NOT NULL default '0',
`userid` int(10) NOT NULL default '0',
`groupid` int(10) NOT NULL default '0',
`timestart` int(10) NOT NULL default '0',
`timeend` int(10) NOT NULL default '0',
`timemodified` int(10) NOT NULL default '0',
`modifierid` int(10) NOT NULL default '0',
);
CREATE TABLE prefix_capability_overrides (
`id` SERIAL PRIMARY KEY,
`contextid` int(10) NOT NULL default '0',
`roleid` int(10) NOT NULL default '0',
`module` varchar(255) NOT NULL default '',
`capability` varchar(255) NOT NULL default '',
`allow` int(1) NOT NULL default '0',
`priority` double(2,2) NOT NULL default '0',
`timemodified` int(10) NOT NULL default '0',
`modifierid` int(10) NOT NULL default '0',
);
CREATE TABLE prefix_role_capabilities (
`id` SERIAL PRIMARY KEY,
`module` varchar(255) NOT NULL default '',
`capability` varchar(255) NOT NULL default '',
`allow` int(1) NOT NULL default '0',
);
INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('data', 'view', 'data', 'name'); INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('data', 'view', 'data', 'name');
INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('data', 'add', 'data', 'name'); INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('data', 'add', 'data', 'name');
INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('data', 'update', 'data', 'name'); INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('data', 'update', 'data', 'name');

View file

@ -65,6 +65,10 @@
require_course_login($course, true, $cm); require_course_login($course, true, $cm);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
has_capability('mod/data:managetemplates', $context->id, true);
if (!isteacheredit($course->id)){ if (!isteacheredit($course->id)){
error(get_string('noaccess','data')); error(get_string('noaccess','data'));
} }

View file

@ -57,13 +57,18 @@
} }
} }
if (isteacher($course->id)) { $context = get_context_instance(CONTEXT_MODULE, $cm->id);
has_capability('mod/data:uploadentries', $context->id, true);
if (has_capability('mod/data:managetemplates', $context->id)) {
if (!count_records('data_fields','dataid',$data->id)) { // Brand new database! if (!count_records('data_fields','dataid',$data->id)) { // Brand new database!
redirect($CFG->wwwroot.'/mod/data/field.php?d='.$data->id); // Redirect to field entry redirect($CFG->wwwroot.'/mod/data/field.php?d='.$data->id); // Redirect to field entry
} }
} }
///checking for participants ///checking for participants
// needs fixing?
/*
if ((!isteacher($course->id)) && $data->participants == DATA_TEACHERS_ONLY) { if ((!isteacher($course->id)) && $data->participants == DATA_TEACHERS_ONLY) {
error ('students are not allowed to participate in this activity'); error ('students are not allowed to participate in this activity');
} }
@ -72,7 +77,7 @@
if (!isteacher($course->id) or !data_isowner($rid) or !confirm_sesskey()){ if (!isteacher($course->id) or !data_isowner($rid) or !confirm_sesskey()){
error (get_string('noaccess','data')); error (get_string('noaccess','data'));
} }
} }*/
/// Print the page header /// Print the page header

View file

@ -549,11 +549,15 @@ function data_numentries($data){
function data_add_record($data, $groupid=0){ function data_add_record($data, $groupid=0){
global $USER; global $USER;
$cm = data_get_cm($data);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
$record->userid = $USER->id; $record->userid = $USER->id;
$record->dataid = $data->id; $record->dataid = $data->id;
$record->groupid = $groupid; $record->groupid = $groupid;
$record->timecreated = $record->timemodified = time(); $record->timecreated = $record->timemodified = time();
if (isteacher($data->course)) { if (has_capability('mod/data:approve', $context->id)) {
//if (isteacher($data->course)) {
$record->approved = 1; $record->approved = 1;
} else { } else {
$record->approved = 0; $record->approved = 0;
@ -835,6 +839,9 @@ function data_get_coursemodule_info($coursemodule) {
function data_print_template($template, $records, $data, $search='',$page=0, $return=false) { function data_print_template($template, $records, $data, $search='',$page=0, $return=false) {
global $CFG; global $CFG;
$cm = data_get_cm($data);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
static $fields = NULL; static $fields = NULL;
static $isteacher; static $isteacher;
static $dataid = NULL; static $dataid = NULL;
@ -872,7 +879,7 @@ function data_print_template($template, $records, $data, $search='',$page=0, $re
/// Replacing special tags (##Edit##, ##Delete##, ##More##) /// Replacing special tags (##Edit##, ##Delete##, ##More##)
$patterns[]='/\#\#Edit\#\#/i'; $patterns[]='/\#\#Edit\#\#/i';
$patterns[]='/\#\#Delete\#\#/i'; $patterns[]='/\#\#Delete\#\#/i';
if ($isteacher or data_isowner($record->id)) { if (has_capability('mod/data:manageentries', $context->id) or data_isowner($record->id)) {
$replacement[] = '<a href="'.$CFG->wwwroot.'/mod/data/edit.php?d=' $replacement[] = '<a href="'.$CFG->wwwroot.'/mod/data/edit.php?d='
.$data->id.'&amp;rid='.$record->id.'&amp;sesskey='.sesskey().'"><img src="'.$CFG->pixpath.'/t/edit.gif" height="11" width="11" border="0" alt="'.get_string('edit').'" /></a>'; .$data->id.'&amp;rid='.$record->id.'&amp;sesskey='.sesskey().'"><img src="'.$CFG->pixpath.'/t/edit.gif" height="11" width="11" border="0" alt="'.get_string('edit').'" /></a>';
$replacement[] = '<a href="'.$CFG->wwwroot.'/mod/data/view.php?d=' $replacement[] = '<a href="'.$CFG->wwwroot.'/mod/data/view.php?d='
@ -892,7 +899,7 @@ function data_print_template($template, $records, $data, $search='',$page=0, $re
'&amp;course='.$data->course.'">'.fullname($record).'</a>'; '&amp;course='.$data->course.'">'.fullname($record).'</a>';
$patterns[]='/\#\#Approve\#\#/i'; $patterns[]='/\#\#Approve\#\#/i';
if ($isteacher && ($data->approval) && (!$record->approved)){ if (has_capability('mod/data:approve', $context->id) && ($data->approval) && (!$record->approved)){
$replacement[] = '<a href="'.$CFG->wwwroot.'/mod/data/view.php?d='.$data->id.'&amp;approve='.$record->id.'&amp;sesskey='.sesskey().'"><img src="'.$CFG->pixpath.'/i/approve.gif" height="11" width="11" border="0" alt="'.get_string('approve').'" /></a>'; $replacement[] = '<a href="'.$CFG->wwwroot.'/mod/data/view.php?d='.$data->id.'&amp;approve='.$record->id.'&amp;sesskey='.sesskey().'"><img src="'.$CFG->pixpath.'/i/approve.gif" height="11" width="11" border="0" alt="'.get_string('approve').'" /></a>';
} else { } else {
$replacement[] = ''; $replacement[] = '';
@ -984,19 +991,22 @@ function data_print_preference_form($data, $perpage, $search, $sort='', $order='
function data_print_ratings($data, $record) { function data_print_ratings($data, $record) {
global $USER; global $USER;
$cm = data_get_cm($data);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
$ratingsmenuused = false; $ratingsmenuused = false;
if ($data->ratings and !empty($USER->id)) { if ($data->ratings and !empty($USER->id)) {
if ($ratings->scale = make_grades_menu($data->scale)) { if ($ratings->scale = make_grades_menu($data->scale)) {
$ratings->assesspublic = $data->assesspublic; $ratings->assesspublic = $data->assesspublic;
$ratings->allow = (($data->assessed != 2 or isteacher($data->course)) && !isguest()); $ratings->allow = ($data->assessed != 2 or has_capability('mod/data:rate', $context->id));
if ($ratings->allow) { if ($ratings->allow) {
echo '<div class="ratings" align="center">'; echo '<div class="ratings" align="center">';
echo '<form name="form" method="post" action="rate.php">'; echo '<form name="form" method="post" action="rate.php">';
$useratings = true; $useratings = true;
if ($useratings) { if ($useratings) {
if ((isteacher($data->course) or $ratings->assesspublic) and !data_isowner($record->id)) { if ((has_capability('mod/data:rate', $context->id) or $ratings->assesspublic) and !data_isowner($record->id)) {
data_print_ratings_mean($record->id, $ratings->scale, isteacher($data->course)); data_print_ratings_mean($record->id, $ratings->scale, has_capability('mod/data:rate', $context->id));
if (!empty($ratings->allow)) { if (!empty($ratings->allow)) {
echo '&nbsp;'; echo '&nbsp;';
data_print_rating_menu($record->id, $USER->id, $ratings->scale); data_print_rating_menu($record->id, $USER->id, $ratings->scale);
@ -1155,7 +1165,10 @@ function data_print_comment($data, $comment, $page=0) {
global $USER, $CFG; global $USER, $CFG;
$stredit = get_string('edit'); $cm = data_get_cm($data);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
$stredit = get_string('edit');
$strdelete = get_string('delete'); $strdelete = get_string('delete');
$user = get_record('user','id',$comment->userid); $user = get_record('user','id',$comment->userid);
@ -1192,7 +1205,7 @@ function data_print_comment($data, $comment, $page=0) {
/// Commands /// Commands
echo '<div class="commands">'; echo '<div class="commands">';
if (data_isowner($comment->recordid) or isteacher($data->course)) { if (data_isowner($comment->recordid) or has_capability('mod/data:managecomments', $context->id)) {
echo '<a href="'.$CFG->wwwroot.'/mod/data/comment.php?rid='.$comment->recordid.'&amp;mode=edit&amp;commentid='.$comment->id.'&amp;page='.$page.'">'.$stredit.'</a>'; echo '<a href="'.$CFG->wwwroot.'/mod/data/comment.php?rid='.$comment->recordid.'&amp;mode=edit&amp;commentid='.$comment->id.'&amp;page='.$page.'">'.$stredit.'</a>';
echo '| <a href="'.$CFG->wwwroot.'/mod/data/comment.php?rid='.$comment->recordid.'&amp;mode=delete&amp;commentid='.$comment->id.'&amp;page='.$page.'">'.$strdelete.'</a>'; echo '| <a href="'.$CFG->wwwroot.'/mod/data/comment.php?rid='.$comment->recordid.'&amp;mode=delete&amp;commentid='.$comment->id.'&amp;page='.$page.'">'.$strdelete.'</a>';
} }
@ -1239,13 +1252,15 @@ function data_convert_arrays_to_strings(&$fieldinput) {
} }
} }
function data_clean_field_name($fn) { // returns the $cm given $data
$fn = trim($fn); function data_get_cm($data) {
//hack from clean_filename - to be replaced by something nicer later global $CFG, $course;
$fn = preg_replace("/[\\000-\\x2c\\x2f\\x3a-\\x40\\x5b-\\x5e\\x60\\x7b-\\177]/s", '_', $fn); $datamod = get_record('modules', 'name', 'data');
$fn = preg_replace("/_+/", '_', $fn); $SQL = "select * from {$CFG->prefix}course_modules
$fn = preg_replace("/\.\.+/", '.', $fn); where course = $course->id and
return $fn; module = $datamod->id and
instance = $data->id";
return get_record_sql($SQL);
} }
?> ?>

View file

@ -29,6 +29,9 @@
error('You cannot call this script in that way'); error('You cannot call this script in that way');
} }
$cm = data_get_cm($data);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
$inactive = NULL; $inactive = NULL;
$row = array(); $row = array();
@ -40,13 +43,13 @@
$row[] = new tabobject('single', $CFG->wwwroot.'/mod/data/view.php?d='.$data->id.'&amp;mode=single', get_string('single','data'), '', true); $row[] = new tabobject('single', $CFG->wwwroot.'/mod/data/view.php?d='.$data->id.'&amp;mode=single', get_string('single','data'), '', true);
} }
if (isloggedin() and !isguest()) { //if (isloggedin() and !isguest()) {
if (isteacher($course->id) or ($data->participants == DATA_STUDENTS_ONLY) or if (isloggedin()) {
($data->participants == DATA_TEACHERS_AND_STUDENTS)){ if (has_capability('mod/data:writeentry', $context->id)) { // took out participation list here!
$addstring = empty($editentry) ? get_string('add', 'data') : get_string('editentry', 'data'); $addstring = empty($editentry) ? get_string('add', 'data') : get_string('editentry', 'data');
$row[] = new tabobject('add', $CFG->wwwroot.'/mod/data/edit.php?d='.$data->id, $addstring, '', true); $row[] = new tabobject('add', $CFG->wwwroot.'/mod/data/edit.php?d='.$data->id, $addstring, '', true);
} }
if (isteacher($course->id)) { if (has_capability('mod/data:managetemplates', $context->id)) {
if ($currenttab == 'list') { if ($currenttab == 'list') {
$defaultemplate = 'listtemplate'; $defaultemplate = 'listtemplate';
} else if ($currenttab == 'add') { } else if ($currenttab == 'add') {

View file

@ -56,7 +56,9 @@
} }
require_course_login($course, true, $cm); require_course_login($course, true, $cm);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
has_capability('mod/data:managetemplates', $context->id, true);
/*
if (!isteacheredit($course->id)){ if (!isteacheredit($course->id)){
error(get_string('noaccess','data')); error(get_string('noaccess','data'));
} }
@ -66,7 +68,7 @@
redirect($CFG->wwwroot.'/mod/data/field.php?d='.$data->id); // Redirect to field entry redirect($CFG->wwwroot.'/mod/data/field.php?d='.$data->id); // Redirect to field entry
} }
} }
*/
//add_to_log($course->id, 'data', 'templates view', "templates.php?id=$cm->id&amp;d=$data->id", $data->id, $cm->id); //add_to_log($course->id, 'data', 'templates view', "templates.php?id=$cm->id&amp;d=$data->id", $data->id, $cm->id);

View file

@ -5,7 +5,7 @@
// This fragment is called by /admin/index.php // This fragment is called by /admin/index.php
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
$module->version = 2006052400; $module->version = 2006080800;
$module->requires = 2005060230; // Requires this Moodle version $module->requires = 2005060230; // Requires this Moodle version
$module->cron = 60; $module->cron = 60;

View file

@ -43,7 +43,6 @@
$approve = optional_param('approve', 0, PARAM_INT); //approval recordid $approve = optional_param('approve', 0, PARAM_INT); //approval recordid
$delete = optional_param('delete', 0, PARAM_INT); //delete recordid $delete = optional_param('delete', 0, PARAM_INT); //delete recordid
if ($id) { if ($id) {
if (! $cm = get_record('course_modules', 'id', $id)) { if (! $cm = get_record('course_modules', 'id', $id)) {
error('Course Module ID was incorrect'); error('Course Module ID was incorrect');
@ -82,12 +81,13 @@
$record = NULL; $record = NULL;
} }
require_course_login($course, true, $cm); require_course_login($course, true, $cm);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
has_capability('mod/data:readentry', $context->id, true);
/// If it's hidden then it's don't show anything. :) /// If it's hidden then it's don't show anything. :)
if (empty($cm->visible) and !isteacher($course->id)) { if (empty($cm->visible) and !has_capability('mod/data:managetemplates', $context->id)) {
$strdatabases = get_string("modulenameplural", "data"); $strdatabases = get_string("modulenameplural", "data");
$navigation = "<a href=\"index.php?id=$course->id\">$strdatabases</a> ->"; $navigation = "<a href=\"index.php?id=$course->id\">$strdatabases</a> ->";
print_header_simple(format_string($data->name), "", print_header_simple(format_string($data->name), "",
@ -96,7 +96,7 @@
} }
/// If we have an empty Database then redirect because this page is useless without data /// If we have an empty Database then redirect because this page is useless without data
if (isteacher($course->id)) { if (has_capability('mod/data:managetemplates', $context->id)) {
if (!record_exists('data_fields','dataid',$data->id)) { // Brand new database! if (!record_exists('data_fields','dataid',$data->id)) { // Brand new database!
redirect($CFG->wwwroot.'/mod/data/field.php?d='.$data->id); // Redirect to field entry redirect($CFG->wwwroot.'/mod/data/field.php?d='.$data->id); // Redirect to field entry
} }
@ -198,7 +198,7 @@
/// Delete any requested records /// Delete any requested records
if ($delete && confirm_sesskey() && (isteacher($course->id) or data_isowner($delete))) { if ($delete && confirm_sesskey() && (has_capability('mod/data:manageentries', $context->id) or data_isowner($delete))) {
if ($confirm = optional_param('confirm',0,PARAM_INT)) { if ($confirm = optional_param('confirm',0,PARAM_INT)) {
if ($deleterecord = get_record('data_records', 'id', $delete)) { // Need to check this is valid if ($deleterecord = get_record('data_records', 'id', $delete)) { // Need to check this is valid
if ($deleterecord->dataid == $data->id) { // Must be from this database if ($deleterecord->dataid == $data->id) { // Must be from this database
@ -249,7 +249,7 @@
/// Approve any requested records /// Approve any requested records
if ($approve && confirm_sesskey() && isteacher($course->id)) { if ($approve && confirm_sesskey() && has_capability('mod/data:approve', $context->id)) {
if ($approverecord = get_record('data_records', 'id', $approve)) { // Need to check this is valid if ($approverecord = get_record('data_records', 'id', $approve)) { // Need to check this is valid
if ($approverecord->dataid == $data->id) { // Must be from this database if ($approverecord->dataid == $data->id) { // Must be from this database
$newrecord->id = $approverecord->id; $newrecord->id = $approverecord->id;
@ -262,7 +262,7 @@
} }
// If not teacher, check whether user has sufficient records to view // If not teacher, check whether user has sufficient records to view
if (!isteacher($course->id) and data_numentries($data) < $data->requiredentriestoview){ if (!has_capability('mod/data:managetemplates', $context->id) and data_numentries($data) < $data->requiredentriestoview){
notify (($data->requiredentriestoview - data_numentries($data)).'&nbsp;'.get_string('insufficiententries','data')); notify (($data->requiredentriestoview - data_numentries($data)).'&nbsp;'.get_string('insufficiententries','data'));
echo '</td></tr></table>'; echo '</td></tr></table>';
print_footer($course); print_footer($course);
@ -272,7 +272,7 @@
/// We need to examine the whole dataset to produce the correct paging /// We need to examine the whole dataset to produce the correct paging
if ((!isteacher($course->id)) && ($data->approval)) { if ((!has_capability('mod/data:managetemplates', $context->id)) && ($data->approval)) {
if (isloggedin()) { if (isloggedin()) {
$approveselect = ' AND (r.approved=1 OR r.userid='.$USER->id.') '; $approveselect = ' AND (r.approved=1 OR r.userid='.$USER->id.') ';
} else { } else {
@ -390,7 +390,7 @@
if (empty($records)) { // Nothing to show! if (empty($records)) { // Nothing to show!
if ($record) { // Something was requested so try to show that at least (bug 5132) if ($record) { // Something was requested so try to show that at least (bug 5132)
if (isteacher($course->id) || empty($data->approval) || if (has_capability('mod/data:manageentries', $context->id) || empty($data->approval) ||
$record->approved || (isloggedin() && $record->userid == $USER->id)) { $record->approved || (isloggedin() && $record->userid == $USER->id)) {
if (!$currentgroup || $record->groupid == $currentgroup || $record->groupid == 0) { if (!$currentgroup || $record->groupid == $currentgroup || $record->groupid == 0) {
$records[] = $record; $records[] = $record;

View file

@ -55,6 +55,8 @@
require_login($course->id, false, $cm); require_login($course->id, false, $cm);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
$strexercises = get_string("modulenameplural", "exercise"); $strexercises = get_string("modulenameplural", "exercise");
$strexercise = get_string("modulename", "exercise"); $strexercise = get_string("modulename", "exercise");
$strassessments = get_string("assessments", "exercise"); $strassessments = get_string("assessments", "exercise");
@ -71,7 +73,7 @@
/******************* admin amend Grading Grade ************************************/ /******************* admin amend Grading Grade ************************************/
if ($action == 'adminamendgradinggrade' ) { if ($action == 'adminamendgradinggrade' ) {
if (!isteacher($course->id)) { if (!has_capability('mod/exercise:assess', $context->id)) {
error("Only teachers can look at this page"); error("Only teachers can look at this page");
} }
if (empty($aid)) { if (empty($aid)) {
@ -109,7 +111,7 @@
/******************* admin confirm delete ************************************/ /******************* admin confirm delete ************************************/
elseif ($action == 'adminconfirmdelete' ) { elseif ($action == 'adminconfirmdelete' ) {
if (!isteacher($course->id)) { if (!has_capability('mod/exercise:assess', $context->id)) {
error("Only teachers can look at this page"); error("Only teachers can look at this page");
} }
if (empty($aid)) { if (empty($aid)) {
@ -125,7 +127,7 @@
/******************* admin delete ************************************/ /******************* admin delete ************************************/
elseif ($action == 'admindelete' ) { elseif ($action == 'admindelete' ) {
if (!isteacher($course->id)) { if (!has_capability('mod/exercise:assess', $context->id)) {
error("Only teachers can look at this page"); error("Only teachers can look at this page");
} }
if (empty($aid)) { if (empty($aid)) {
@ -145,7 +147,7 @@
/*********************** admin list of asssessments (of a submission) (by teachers)**************/ /*********************** admin list of asssessments (of a submission) (by teachers)**************/
elseif ($action == 'adminlist') { elseif ($action == 'adminlist') {
if (!isteacher($course->id)) { if (!has_capability('mod/exercise:assess', $context->id)) {
error("Only teachers can look at this page"); error("Only teachers can look at this page");
} }
@ -161,7 +163,7 @@
/****************** admin list of asssessments by a student (used by teachers only )******************/ /****************** admin list of asssessments by a student (used by teachers only )******************/
elseif ($action == 'adminlistbystudent') { elseif ($action == 'adminlistbystudent') {
if (!isteacher($course->id)) { if (!has_capability('mod/exercise:assess', $context->id)) {
error("Only teachers can look at this page"); error("Only teachers can look at this page");
} }
@ -258,7 +260,7 @@
/****************** edit assessment elements (for teachers) ***********************/ /****************** edit assessment elements (for teachers) ***********************/
elseif ($action == 'editelements') { elseif ($action == 'editelements') {
if (!isteacher($course->id)) { if (!has_capability('mod/exercise:assess', $context->id)) {
error("Only teachers can look at this page"); error("Only teachers can look at this page");
} }
@ -455,7 +457,7 @@
/****************** insert/update assignment elements (for teachers)***********************/ /****************** insert/update assignment elements (for teachers)***********************/
elseif ($action == 'insertelements') { elseif ($action == 'insertelements') {
if (!isteacher($course->id)) { if (!has_capability('mod/exercise:assess', $context->id)) {
error("Only teachers can look at this page"); error("Only teachers can look at this page");
} }
@ -572,7 +574,7 @@
/****************** list assessments for grading (Student submissions)(by teachers)*********************/ /****************** list assessments for grading (Student submissions)(by teachers)*********************/
elseif ($action == 'listungradedstudentsubmissions') { elseif ($action == 'listungradedstudentsubmissions') {
if (!isteacher($course->id)) { if (!has_capability('mod/exercise:assess', $context->id)) {
error("Only teachers can look at this page"); error("Only teachers can look at this page");
} }
exercise_list_ungraded_assessments($exercise, "student"); exercise_list_ungraded_assessments($exercise, "student");
@ -584,7 +586,7 @@
******************Teacher's submissions) (by teachers)****/ ******************Teacher's submissions) (by teachers)****/
elseif ($action == 'listungradedstudentassessments') { elseif ($action == 'listungradedstudentassessments') {
if (!isteacher($course->id)) { if (!has_capability('mod/exercise:assess', $context->id)) {
error("Only teachers can look at this page"); error("Only teachers can look at this page");
} }
exercise_list_ungraded_assessments($exercise, "teacher"); exercise_list_ungraded_assessments($exercise, "teacher");
@ -603,7 +605,7 @@
/******************* regrade student assessments ************************************/ /******************* regrade student assessments ************************************/
elseif ($action == 'regradestudentassessments' ) { elseif ($action == 'regradestudentassessments' ) {
if (!isteacher($course->id)) { if (!has_capability('mod/exercise:assess', $context->id)) {
error("Only teachers can look at this page"); error("Only teachers can look at this page");
} }
// get all the student assessments // get all the student assessments
@ -636,7 +638,7 @@
/****************** teacher assessment : grading of assessment and submission (from student) ************/ /****************** teacher assessment : grading of assessment and submission (from student) ************/
elseif ($action == 'teacherassessment') { elseif ($action == 'teacherassessment') {
if (!isteacher($course->id)) { if (!has_capability('mod/exercise:assess', $context->id)) {
error("Only teachers can look at this page"); error("Only teachers can look at this page");
} }
@ -659,7 +661,7 @@
/****************** teacher table : show assessments by exercise and teacher ************/ /****************** teacher table : show assessments by exercise and teacher ************/
elseif ($action == 'teachertable') { elseif ($action == 'teachertable') {
if (!isteacher($course->id)) { if (!has_capability('mod/exercise:assess', $context->id)) {
error("Only teachers can look at this page"); error("Only teachers can look at this page");
} }
@ -850,7 +852,7 @@
} }
// is user allowed to resubmit? // is user allowed to resubmit?
if (isteacher($course->id)) { if (has_capability('mod/exercise:assess', $context->id)) {
if (!$submission = get_record("exercise_submissions", "id", $assessment->submissionid)) { if (!$submission = get_record("exercise_submissions", "id", $assessment->submissionid)) {
error ("Updateassessment: submission record not found"); error ("Updateassessment: submission record not found");
} }
@ -885,7 +887,7 @@
/****************** update teacher assessment (by teacher only) ***************************/ /****************** update teacher assessment (by teacher only) ***************************/
elseif ($action == 'updateteacherassessment') { elseif ($action == 'updateteacherassessment') {
if (!isteacher($course->id)) { if (!has_capability('mod/exercise:assess', $context->id)) {
error("Only teachers can look at this page"); error("Only teachers can look at this page");
} }
@ -1098,7 +1100,7 @@
/****************** update grading grade(by teacher) ***************************/ /****************** update grading grade(by teacher) ***************************/
elseif ($action == 'updategradinggrade') { elseif ($action == 'updategradinggrade') {
if (!isteacher($course->id)) { if (!has_capability('mod/exercise:assess', $context->id)) {
error("Only teachers can look at this page"); error("Only teachers can look at this page");
} }

View file

@ -0,0 +1,52 @@
<?php
//
// Capability definitions for the exercise module.
//
// The capabilities are loaded into the database table when the module is
// installed or updated. Whenever the capability definitions are updated,
// the module version number should be bumped up.
//
// The system has four possible values for a capability:
// CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT, and inherit (not set).
//
//
// CAPABILITY NAMING CONVENTION
//
// It is important that capability names are unique. The naming convention
// for capabilities that are specific to modules and blocks is as follows:
// [mod/block]/<component_name>:<capabilityname>
//
// component_name should be the same as the directory name of the mod or block.
//
// Core moodle capabilities are defined thus:
// moodle/<capabilityclass>:<capabilityname>
//
// Examples: mod/forum:viewpost
// block/recent_activity:view
// moodle/site:deleteuser
//
// The variable name for the capability definitions array follows the format
// $<componenttype>_<component_name>_capabilities
//
// For the core capabilities, the variable is $moodle_capabilities.
$mod_exercise_capabilities = array(
'mod/exercise:assess' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
)
);
?>

View file

@ -5,7 +5,7 @@
// This fragment is called by /admin/index.php // This fragment is called by /admin/index.php
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
$module->version = 2005031000; $module->version = 2006080800;
$module->requires = 2005031000; // Requires this Moodle version $module->requires = 2005031000; // Requires this Moodle version
$module->cron = 60; $module->cron = 60;

View file

@ -38,6 +38,8 @@
require_login($course->id, false, $cm); require_login($course->id, false, $cm);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
// ...log activity... // ...log activity...
add_to_log($course->id, "exercise", "view", "view.php?id=$cm->id", $exercise->id, $cm->id); add_to_log($course->id, "exercise", "view", "view.php?id=$cm->id", $exercise->id, $cm->id);
@ -308,8 +310,8 @@
/****************** submission of assignment by teacher only***********************/ /****************** submission of assignment by teacher only***********************/
elseif ($action == 'submitassignment') { elseif ($action == 'submitassignment') {
if (!isteacheredit($course->id)) { if (!has_capability('mod/exercise:assess', $context->id)) {
error("Only teachers with editing permissions can do this."); //error("Only teachers with editing permissions can do this.");
} }
exercise_print_assignment_info($exercise); exercise_print_assignment_info($exercise);

276
mod/forum/db/access.php Normal file
View file

@ -0,0 +1,276 @@
<?php
//
// Capability definitions for the forum module.
//
// The capabilities are loaded into the database table when the module is
// installed or updated. Whenever the capability definitions are updated,
// the module version number should be bumped up.
//
// The system has four possible values for a capability:
// CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT, and inherit (not set).
//
//
// CAPABILITY NAMING CONVENTION
//
// It is important that capability names are unique. The naming convention
// for capabilities that are specific to modules and blocks is as follows:
// [mod/block]/<component_name>:<capabilityname>
//
// component_name should be the same as the directory name of the mod or block.
//
// Core moodle capabilities are defined thus:
// moodle/<capabilityclass>:<capabilityname>
//
// Examples: mod/forum:viewpost
// block/recent_activity:view
// moodle/site:deleteuser
//
// The variable name for the capability definitions array follows the format
// $<componenttype>_<component_name>_capabilities
//
// For the core capabilities, the variable is $moodle_capabilities.
$mod_forum_capabilities = array(
'mod/forum:viewforum' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/forum:viewdiscussion' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/forum:viewdiscussionsfromallgroups' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_PREVENT,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/forum:startdiscussion' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/forum:replypost' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/forum:viewrating' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/forum:viewanyrating' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/forum:rate' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/forum:createattachment' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/forum:deleteownpost' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/forum:deleteanypost' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/forum:splitdiscussions' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/forum:movediscussions' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/forum:editanypost' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/forum:viewqandawithoutposting' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/forum:viewsubscribers' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
),
'mod/forum:managesubscriptions' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'admin' => CAP_ALLOW
)
)
);
?>

View file

@ -224,10 +224,37 @@ function forum_upgrade($oldversion) {
table_column('forum_posts','','mailnow','integer'); table_column('forum_posts','','mailnow','integer');
} }
if ($oldversion < 2006011702) {
execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('forum', 'user report', 'user', 'CONCAT(firstname,\' \',lastname)')"); // Upgrades for new roles and capabilities support.
if ($oldversion < 2006011701) {
// forum.open defines what students can do:
// 0 = No discussions, no replies
// 1 = No discussions, but replies are allowed
// 2 = Discussions and replies are allowed
// Delete column forum.open
// forum.assessed defines who can rate posts:
// 1 = Everyone can rate posts
// 2 = Only teachers can rate posts
// Delete column forum.assessed
// forum.assesspublic defines whether students can see everybody's
// ratings:
// 0 = Students can only see their own ratings
// 1 = Students can see everyone's ratings
// Delete column forum.assesspublic
} }
return true; return true;
} }

View file

@ -163,7 +163,6 @@ INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('forum',
INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('forum', 'add discussion', 'forum_discussions', 'name'); INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('forum', 'add discussion', 'forum_discussions', 'name');
INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('forum', 'add post', 'forum_posts', 'subject'); INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('forum', 'add post', 'forum_posts', 'subject');
INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('forum', 'update post', 'forum_posts', 'subject'); INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('forum', 'update post', 'forum_posts', 'subject');
INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('forum', 'user report', 'user', 'CONCAT(firstname,\' \',lastname)');
INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('forum', 'move discussion', 'forum_discussions', 'name'); INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('forum', 'move discussion', 'forum_discussions', 'name');
INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('forum', 'view subscribers', 'forum', 'name'); INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('forum', 'view subscribers', 'forum', 'name');
INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('forum', 'view discussion', 'forum_discussions', 'name'); INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('forum', 'view discussion', 'forum_discussions', 'name');

View file

@ -156,7 +156,6 @@ function forum_upgrade($oldversion) {
} }
if ($oldversion < 2006011600) { if ($oldversion < 2006011600) {
notify('forum_type does not exists, you can ignore and this will properly removed');
execute_sql("ALTER TABLE {$CFG->prefix}forum DROP CONSTRAINT {$CFG->prefix}forum_type"); execute_sql("ALTER TABLE {$CFG->prefix}forum DROP CONSTRAINT {$CFG->prefix}forum_type");
execute_sql("ALTER TABLE {$CFG->prefix}forum ADD CONSTRAINT {$CFG->prefix}forum_type CHECK (type IN ('single','news','general','social','eachuser','teacher','qanda')) "); execute_sql("ALTER TABLE {$CFG->prefix}forum ADD CONSTRAINT {$CFG->prefix}forum_type CHECK (type IN ('single','news','general','social','eachuser','teacher','qanda')) ");
} }
@ -171,15 +170,6 @@ function forum_upgrade($oldversion) {
table_column('forum_posts','','mailnow','integer'); table_column('forum_posts','','mailnow','integer');
} }
if ($oldversion < 2006011701) {
execute_sql("ALTER TABLE {$CFG->prefix}forum DROP CONSTRAINT {$CFG->prefix}forum_type_check");
}
if ($oldversion < 2006011702) {
execute_sql("INSERT INTO {$CFG->prefix}log_display (module, action, mtable, field) VALUES ('forum', 'user report', 'user', 'firstname||\' \'||lastname')");
}
return true; return true;
} }

View file

@ -175,7 +175,6 @@ INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('forum',
INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('forum', 'add discussion', 'forum_discussions', 'name'); INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('forum', 'add discussion', 'forum_discussions', 'name');
INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('forum', 'add post', 'forum_posts', 'subject'); INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('forum', 'add post', 'forum_posts', 'subject');
INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('forum', 'update post', 'forum_posts', 'subject'); INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('forum', 'update post', 'forum_posts', 'subject');
INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('forum', 'user report', 'user', 'firstname||\' \'||lastname');
INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('forum', 'move discussion', 'forum_discussions', 'name'); INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('forum', 'move discussion', 'forum_discussions', 'name');
INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('forum', 'view subscribers', 'forum', 'name'); INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('forum', 'view subscribers', 'forum', 'name');
INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('forum', 'view discussion', 'forum_discussions', 'name'); INSERT INTO prefix_log_display (module, action, mtable, field) VALUES ('forum', 'view discussion', 'forum_discussions', 'name');

View file

@ -25,17 +25,20 @@
notify("Bad forum ID stored in this discussion"); notify("Bad forum ID stored in this discussion");
} }
if ($forum->type == "teacher") { if (! $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) {
require_login($course->id); error('Course Module ID was incorrect');
}
if (!isteacher($course->id)) { $canviewdiscussion = false;
error("You must be a $course->teacher to view this forum");
}
} elseif ($forum->type == "news") { $context = get_context_instance(CONTEXT_MODULE, $cm->id);
if (!((isadmin() and !empty($CFG->admineditalways)) if (has_capability('mod/forum:viewdiscussion', $context->id)) {
|| isteacher($course->id) $canviewdiscussion = true;
|| (!empty($USER->id) && $USER->id == $discussion->userid) }
if ($forum->type == "news") {
if (!($canviewdiscussion || $USER->id == $discussion->userid
|| (($discussion->timestart == 0 || $discussion->timestart <= time()) || (($discussion->timestart == 0 || $discussion->timestart <= time())
&& ($discussion->timeend == 0 || $discussion->timeend > time())))) { && ($discussion->timeend == 0 || $discussion->timeend > time())))) {
error('Discussion ID was incorrect or no longer exists', "$CFG->wwwroot/mod/forum/view.php?f=$forum->id"); error('Discussion ID was incorrect or no longer exists', "$CFG->wwwroot/mod/forum/view.php?f=$forum->id");
@ -50,58 +53,15 @@
if (!empty($move)) { if (!empty($move)) {
if (!isteacher($course->id)) { if (has_capability('mod/forum:movediscussions', $context->id)) {
error("Only teachers can do that!"); error("You do not have the permission to move this discussion!");
} }
if ($forum = get_record("forum", "id", $move)) { if ($forum = get_record("forum", "id", $move)) {
if (!forum_move_attachments($discussion, $move)) { if (!forum_move_attachments($discussion, $move)) {
notify("Errors occurred while moving attachment directories - check your file permissions"); notify("Errors occurred while moving attachment directories - check your file permissions");
} }
set_field("forum_discussions", "forum", $forum->id, "id", $discussion->id);
if (!$fromforum = get_record("forum", "id", $discussion->forum)) {
notify('Bad forum ID stored in this discussion');
}
$discussion->forum = $forum->id; $discussion->forum = $forum->id;
$discussion->timemodified = time();
// Leave behind a skeleton discussion containing only a post which
// notifies that the discussion has been moved.
$skeleton = clone($discussion);
$skeleton->forum = $fromforum->id;
$skeleton->name = addslashes( $skeleton->name . ' ' . get_string('movedmarker', 'forum') );
// Prepare replacement parameters for message content string
// - these create the link to the new discussion location
$link = new stdClass;
$me = strip_querystring(me());
$link->discusshref = $me . '?d=' . $discussion->id;
$link->forumhref = dirname($me) . '/view.php?f=' . $forum->id;
$link->forumname = $forum->name;
// retrieve translateable message content
$skeleton->intro = addslashes( get_string('discussionmovedpost', 'forum', $link) );
$skeleton->format = 1;
$skeleton->mailnow = 0;
// add the skeleton discussion to the database
if (!($skeleton->id = forum_add_discussion($skeleton, $msg))) {
notify('Failed to add discussion-moved notification : '. $msg);
}
if (update_record('forum_discussions', $discussion)) {
// Update RSS feeds for both from and to forums.
require_once('rsslib.php');
require_once($CFG->libdir.'/rsslib.php');
// Delete the RSS files for the 2 forums because we want to force
// the regeneration of the feeds since the discussions have been
// moved.
if (!forum_rss_delete_file($forum) || !forum_rss_delete_file($fromforum)) {
notify('Could not purge the cached RSS feeds for the source and/or'.
'destination forum(s) - check your file permissionsforums');
}
}
if ($cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) { if ($cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
add_to_log($course->id, "forum", "move discussion", "discuss.php?d=$discussion->id", "$discussion->id", add_to_log($course->id, "forum", "move discussion", "discuss.php?d=$discussion->id", "$discussion->id",
$cm->id); $cm->id);
@ -195,9 +155,9 @@
if ($groupmode and !isteacheredit($course->id)) { // Groups must be kept separate if ($groupmode and !has_capability('mod/forum:viewdiscussionsfromallgroups', $context->id)) { // Groups must be kept separate
//change this to ismember //change this to ismember
$mygroupid = mygroupid($course->id);//only useful if 0, otherwise it's an array now $mygroupid = mygroupid($course->id); //only useful if 0, otherwise it's an array now
if ($groupmode == SEPARATEGROUPS) { if ($groupmode == SEPARATEGROUPS) {
require_login(); require_login();
@ -212,7 +172,9 @@
} }
} else if ($groupmode == VISIBLEGROUPS) { } else if ($groupmode == VISIBLEGROUPS) {
$canreply = ((empty($mygroupid) and $discussion->groupid == -1) || (ismember($discussion->groupid) || $mygroupid == $discussion->groupid)); $canreply = ( (empty($mygroupid) && $discussion->groupid == -1) ||
(ismember($discussion->groupid) || $mygroupid == $discussion->groupid) &&
has_capability('mod/forum:replypost', $context->id) );
} }
} }
@ -222,7 +184,7 @@
echo '<table width="100%"><tr><td width="33%">'; echo '<table width="100%"><tr><td width="33%">';
if ($groupmode == VISIBLEGROUPS or ($groupmode and isteacheredit($course->id))) { if ($groupmode == VISIBLEGROUPS or ($groupmode and has_capability('mod/forum:viewdiscussionsfromallgroups', $context->id))) {
if ($groups = get_records_menu('groups', 'courseid', $course->id, 'name ASC', 'id,name')) { if ($groups = get_records_menu('groups', 'courseid', $course->id, 'name ASC', 'id,name')) {
print_group_menu($groups, $groupmode, $discussion->groupid, "view.php?id=$cm->id&amp;group="); print_group_menu($groups, $groupmode, $discussion->groupid, "view.php?id=$cm->id&amp;group=");
} }
@ -232,7 +194,7 @@
forum_print_mode_form($discussion->id, $displaymode); forum_print_mode_form($discussion->id, $displaymode);
echo "</td><td width=\"33%\">"; echo "</td><td width=\"33%\">";
if (isteacher($course->id) && $forum->type != "teacher") { // Popup menu to move discussions to other forums if (has_capability('mod/forum:movediscussions', $context->id)) { // Popup menu to move discussions to other forums
if ($forums = get_all_instances_in_course("forum", $course)) { if ($forums = get_all_instances_in_course("forum", $course)) {
if ($course->format == 'weeks') { if ($course->format == 'weeks') {
$strsection = get_string("week"); $strsection = get_string("week");
@ -266,7 +228,8 @@
notify(get_string('thisforumisthrottled','forum',$a)); notify(get_string('thisforumisthrottled','forum',$a));
} }
if ($forum->type == 'qanda' && !isteacher($forum->course) && !forum_user_has_posted($forum->id,$discussion->id,$USER->id)) { if ($forum->type == 'qanda' && !has_capability('mod/forum:viewqandawithoutposting', $context->id) &&
!forum_user_has_posted($forum->id,$discussion->id,$USER->id)) {
notify(get_string('qandanotify','forum')); notify(get_string('qandanotify','forum'));
} }
@ -275,8 +238,8 @@
} }
/// Print the actual discussion /// Print the actual discussion
$canrate = has_capability('mod/forum:rate', $context->id);
forum_print_discussion($course, $forum, $discussion, $post, $displaymode, $canreply); forum_print_discussion($course, $forum, $discussion, $post, $displaymode, $canreply, $canrate);
print_footer($course); print_footer($course);

View file

@ -91,7 +91,9 @@
foreach ($forums as $forum) { foreach ($forums as $forum) {
if (!isset($forum->visible)) { if (!isset($forum->visible)) {
$forum->visible = instance_is_visible("forum", $forum); $forum->visible = instance_is_visible("forum", $forum);
if (!$forum->visible and !isteacher($course->id)) { $cm = get_coursemodule_from_instance("forum", $forum->id, $course->id);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
if (!$forum->visible and !has_capability('moodle/course:viewhiddenactivities', $context->id)) {
if (isset($forum->keyreference)) { if (isset($forum->keyreference)) {
unset($learningforums[$forum->keyreference]); unset($learningforums[$forum->keyreference]);
} }
@ -106,12 +108,14 @@
unset($learningforums[$forum->keyreference]); unset($learningforums[$forum->keyreference]);
} }
break; break;
/*
case "teacher": case "teacher":
if (isteacher($course->id)) { if (isteacher($course->id)) {
$forum->visible = true; $forum->visible = true;
$generalforums[] = $forum; $generalforums[] = $forum;
} }
break; break;
*/
default: default:
if (!$course->category or empty($forum->section)) { // Site level or section 0 if (!$course->category or empty($forum->section)) { // Site level or section 0
$generalforums[] = $forum; $generalforums[] = $forum;
@ -153,13 +157,19 @@
if ($generalforums) { if ($generalforums) {
foreach ($generalforums as $forum) { foreach ($generalforums as $forum) {
if (isset($forum->groupmode)) {
$cm = get_coursemodule_from_instance("forum", $forum->id, $course->id);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
if (isset($forum->groupmode)) {
$groupmode = groupmode($course, $forum); /// Can do this because forum->groupmode is defined $groupmode = groupmode($course, $forum); /// Can do this because forum->groupmode is defined
} else { } else {
$groupmode = NOGROUPS; $groupmode = NOGROUPS;
} }
if ($groupmode == SEPARATEGROUPS and !isteacheredit($course->id)) {
// this is potentially wrong logic. could possibly check for if user has the right to hmmm
if ($groupmode == SEPARATEGROUPS and !has_capability('mod/forum:viewdiscussionsfromallgroups', $context->id)) {
$count = count_records_select("forum_discussions", "forum = '$forum->id' AND (groupid = '$currentgroup' OR groupid = '-1')"); $count = count_records_select("forum_discussions", "forum = '$forum->id' AND (groupid = '$currentgroup' OR groupid = '-1')");
} else { } else {
$count = count_records("forum_discussions", "forum", "$forum->id"); $count = count_records("forum_discussions", "forum", "$forum->id");
@ -167,7 +177,7 @@
if ($usetracking) { if ($usetracking) {
if (($forum->trackingtype == FORUM_TRACKING_ON) || !isset($untracked[$forum->id])) { if (($forum->trackingtype == FORUM_TRACKING_ON) || !isset($untracked[$forum->id])) {
$groupid = ($groupmode==SEPARATEGROUPS && !isteacheredit($course->id)) ? $currentgroup : false; $groupid = ($groupmode==SEPARATEGROUPS && !has_capability('mod/forum:viewdiscussionsfromallgroups', $context->id)) ? $currentgroup : false;
$unread = forum_tp_count_forum_unread_posts($USER->id, $forum->id, $groupid); $unread = forum_tp_count_forum_unread_posts($USER->id, $forum->id, $groupid);
if ($unread > 0) { if ($unread > 0) {
$unreadlink = '<span class="unread"><a href="view.php?f='.$forum->id.'">'.$unread.'</a>'; $unreadlink = '<span class="unread"><a href="view.php?f='.$forum->id.'">'.$unread.'</a>';
@ -177,6 +187,7 @@
$unreadlink = '<span class="read"><a href="view.php?f='.$forum->id.'">'.$unread.'</a>'; $unreadlink = '<span class="read"><a href="view.php?f='.$forum->id.'">'.$unread.'</a>';
} }
if ($forum->trackingtype == FORUM_TRACKING_OPTIONAL) { if ($forum->trackingtype == FORUM_TRACKING_OPTIONAL) {
$trackedlink = '<a title="'.$strnotrackforum.'" href="settracking.php?id='. $trackedlink = '<a title="'.$strnotrackforum.'" href="settracking.php?id='.
$forum->id.'">'.$stryes.'</a>'; $forum->id.'">'.$stryes.'</a>';
@ -226,7 +237,7 @@
if (forum_is_forcesubscribed($forum->id)) { if (forum_is_forcesubscribed($forum->id)) {
$sublink = $stryes; $sublink = $stryes;
} else { } else {
if ($groupmode and !isteacheredit($course->id) and !mygroupid($course->id)) { if ($groupmode and !has_capability('mod/forum:viewdiscussionsfromallgroups', $context->id) and !mygroupid($course->id)) {
$sublink = $strno; // Can't subscribe to a group forum (not in a group) $sublink = $strno; // Can't subscribe to a group forum (not in a group)
$forumlink = format_string($forum->name,true); $forumlink = format_string($forum->name,true);
} else { } else {
@ -303,11 +314,12 @@
if ($learningforums) { if ($learningforums) {
$currentsection = ""; $currentsection = "";
foreach ($learningforums as $key => $forum) { foreach ($learningforums as $key => $forum) {
$groupmode = groupmode($course, $forum); /// Can do this because forum->groupmode is defined $groupmode = groupmode($course, $forum); /// Can do this because forum->groupmode is defined
$forum->visible = instance_is_visible("forum", $forum);
$cm = get_coursemodule_from_instance("forum", $forum->id, $course->id);
if ($groupmode == SEPARATEGROUPS and !isteacheredit($course->id)) { if ($groupmode == SEPARATEGROUPS and !has_capability('mod/forum:viewdiscussionsfromallgroups', $context->id)) {
$count = count_records("forum_discussions", "forum", "$forum->id", "groupid", $currentgroup); $count = count_records("forum_discussions", "forum", "$forum->id", "groupid", $currentgroup);
} else { } else {
$count = count_records("forum_discussions", "forum", "$forum->id"); $count = count_records("forum_discussions", "forum", "$forum->id");

View file

@ -81,9 +81,6 @@ if (!isset($CFG->forum_enabletimedposts)) { // Newish feature that is not quit
$CFG->forum_enabletimedposts = false; $CFG->forum_enabletimedposts = false;
} }
if (!isset($CFG->forum_enablerssfeeds)) { // Disable forum RSS feeds by default
$CFG->forum_enablerssfeeds = false;
}
/// STANDARD FUNCTIONS /////////////////////////////////////////////////////////// /// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
@ -111,10 +108,6 @@ function forum_add_instance($forum) {
$forum->assesstimefinish = 0; $forum->assesstimefinish = 0;
} }
//sanitize given values a bit
$forum->warnafter = clean_param($forum->warnafter, PARAM_INT);
$forum->blockafter = clean_param($forum->blockafter, PARAM_INT);
if (! $forum->id = insert_record('forum', $forum)) { if (! $forum->id = insert_record('forum', $forum)) {
return false; return false;
} }
@ -244,9 +237,7 @@ function forum_cron () {
} }
if (!empty($USER->id)) { // Remember real USER account if necessary if (!empty($USER->id)) { // Remember real USER account if necessary
$realuser = clone($USER); //PHP5 compatibility $realuser = $USER;
} else {
$realuser = false;
} }
/// Posts older than 2 days will not be mailed. This is to avoid the problem where /// Posts older than 2 days will not be mailed. This is to avoid the problem where
@ -1105,48 +1096,95 @@ function forum_get_child_posts($parent, $forumid) {
ORDER BY p.created ASC"); ORDER BY p.created ASC");
} }
/**
* Returns a list of posts found using an array of search terms.
* e.g. word +word -word
* @param $searchterms
* @param $courseid
* @param $page
* @param $recordsperpage=50
* @param &$totalcount
* @param $groupid - either a single groupid or an array of groupids.
* this specifies the groups the search is to be carried
* for. However, please note that, unless the user has
* the capability 'mod/forum:viewdiscussionsfromallgroups',
* we will restrict the search to a subset of groups from
* $groupid. The subset consists of the groups the user
* really is in.
* @param $extrasql
*/
function forum_search_posts($searchterms, $courseid, $page=0, $recordsperpage=50,
&$totalcount, $groupid=0, $extrasql='') {
function forum_search_posts($searchterms, $courseid, $page=0, $recordsperpage=50, &$totalcount, $sepgroups=0, $extrasql='') {
/// Returns a list of posts found using an array of search terms
/// eg word +word -word
///
global $CFG, $USER; global $CFG, $USER;
require_once($CFG->libdir.'/searchlib.php'); require_once($CFG->libdir.'/searchlib.php');
if (!isteacher($courseid)) { $forummodule = get_record("modules", "name", "forum");
$notteacherforum = "AND f.type <> 'teacher'"; $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
$forummodule = get_record("modules", "name", "forum"); $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id); // Will need to fix this.
$onlyvisible = "AND d.forum = f.id AND f.id = cm.instance AND cm.visible = 1 AND cm.module = $forummodule->id";
$onlyvisibletable = ", {$CFG->prefix}course_modules cm, {$CFG->prefix}forum f";
if (!empty($sepgroups)) {
$separategroups = SEPARATEGROUPS;
$selectgroup = " AND ( NOT (cm.groupmode='$separategroups'".
" OR (c.groupmode='$separategroups' AND c.groupmodeforce='1') )";//.
$selectgroup .= " OR d.groupid = '-1'"; //search inside discussions for all groups too
foreach ($sepgroups as $sepgroup){
$selectgroup .= " OR d.groupid = '$sepgroup->id'";
}
$selectgroup .= ")";
// " OR d.groupid = '$groupid')"; // Take into account forum visibility.
$selectcourse = " AND d.course = '$courseid' AND c.id='$courseid'"; if (has_capability('moodle/course:viewhiddenactivities', $coursecontext->id)) {
$coursetable = ", {$CFG->prefix}course c"; $onlyvisible = '';
} else { $onlyvisibletable = '';
$selectgroup = '';
$selectcourse = " AND d.course = '$courseid'";
$coursetable = '';
}
} else { } else {
$notteacherforum = ""; $onlyvisible = "AND d.forum = f.id
AND f.id = cm.instance
AND cm.visible = 1
AND cm.module = $forummodule->id";
$onlyvisibletable = ", {$CFG->prefix}course_modules cm, {$CFG->prefix}forum f";
}
// Take into account user groups.
if (has_capability('mod/forum:viewdiscussionsfromallgroups', $modcontext->id)) {
$selectgroup = ''; $selectgroup = '';
$onlyvisible = "";
$onlyvisibletable = "";
$coursetable = ''; $coursetable = '';
if ($courseid == SITEID && isadmin()) { if ($courseid == SITEID && isadmin()) {
$selectcourse = ''; $selectcourse = '';
} else { } else {
$selectcourse = " AND d.course = '$courseid'"; $selectcourse = " AND d.course = '$courseid'";
} }
} else {
$searchgroupid = mygroupid($courseid);
if ($groupid) {
// Okay we don't necessarily trust the groups specified. We'll
// force the search to occur for a subset of the groups the user
// is really in.
$novalidgroups = false;
if (is_array($groupid)) {
foreach ($searchgroupid as $index => $validgroupid) {
if (array_search($validgroupid, $groupid) === false) {
unset($searchgroupid[$index]);
}
}
if (count($searchgroupid) == 0) {
$novalidgroups = true;
}
} else {
if (array_search($groupid, $searchgroupid) === false) {
$novalidgroups = true;
}
}
if ($novalidgroups) {
error('The user does not belong in the group(s) specified '.
'by $groupid and the user does not have the '.
'required permission to view posts from all '.
'groups.');
}
}
$separategroups = SEPARATEGROUPS;
$selectgroup = " AND ( NOT (cm.groupmode='$separategroups'".
" OR (c.groupmode='$separategroups' AND c.groupmodeforce='1') )";//.
foreach ($searchgroupid as $index => $value){
$selectgroup .= " OR d.groupid = '$value'";
}
$selectgroup .= ")";
// " OR d.groupid = '$groupid')";
$selectcourse = " AND d.course = '$courseid' AND c.id='$courseid'";
$coursetable = ", {$CFG->prefix}course c";
} }
$timelimit = ''; $timelimit = '';
@ -1191,12 +1229,21 @@ function forum_search_posts($searchterms, $courseid, $page=0, $recordsperpage=50
$messagesearch = search_generate_SQL($parsearray,'p.message','p.subject','p.userid','u.id','u.firstname','u.lastname','p.modified', 'd.forum'); $messagesearch = search_generate_SQL($parsearray,'p.message','p.subject','p.userid','u.id','u.firstname','u.lastname','p.modified', 'd.forum');
} }
/*
$selectsql = "{$CFG->prefix}forum_posts p, $selectsql = "{$CFG->prefix}forum_posts p,
{$CFG->prefix}forum_discussions d, {$CFG->prefix}forum_discussions d,
{$CFG->prefix}user u $onlyvisibletable $coursetable {$CFG->prefix}user u $onlyvisibletable $coursetable
WHERE ($messagesearch) WHERE ($messagesearch)
AND p.userid = u.id AND p.userid = u.id
AND p.discussion = d.id $selectcourse $notteacherforum $onlyvisible $selectgroup $timelimit $extrasql"; AND p.discussion = d.id $selectcourse $notteacherforum $onlyvisible $selectgroup $timelimit $extrasql";
*/
$selectsql = "{$CFG->prefix}forum_posts p,
{$CFG->prefix}forum_discussions d,
{$CFG->prefix}user u $onlyvisibletable $coursetable
WHERE ($messagesearch)
AND p.userid = u.id
AND p.discussion = d.id $selectcourse $onlyvisible $selectgroup $timelimit $extrasql";
$totalcount = count_records_sql("SELECT COUNT(*) FROM $selectsql"); $totalcount = count_records_sql("SELECT COUNT(*) FROM $selectsql");
@ -2264,14 +2311,14 @@ function forum_print_mode_form($discussion, $mode) {
function forum_search_form($course, $search='') { function forum_search_form($course, $search='') {
global $CFG; global $CFG;
$output = '<div class="forumsearchform">'; $output = '<table border="0" cellpadding="0" cellspacing="0"><tr><td nowrap="nowrap">';
$output .= '<form name="search" action="'.$CFG->wwwroot.'/mod/forum/search.php" style="display:inline">'; $output .= helpbutton('search', get_string('search'), 'moodle', true, false, '', true);
$output .= '&nbsp;<form name="search" action="'.$CFG->wwwroot.'/mod/forum/search.php" style="display:inline">';
$output .= '<input name="search" type="text" size="18" value="'.$search.'" alt="search" />'; $output .= '<input name="search" type="text" size="18" value="'.$search.'" alt="search" />';
$output .= '<input value="'.get_string('searchforums', 'forum').'" type="submit" />'; $output .= '<input value="'.get_string('searchforums', 'forum').'" type="submit" />';
$output .= '<input name="id" type="hidden" value="'.$course->id.'" />'; $output .= '<input name="id" type="hidden" value="'.$course->id.'" />';
$output .= '</form>'; $output .= '</form>';
$output .= helpbutton('search', get_string('search'), 'moodle', true, false, '', true); $output .= '</td></tr></table>';
$output .= '</div>';
return $output; return $output;
} }
@ -2712,32 +2759,32 @@ function forum_user_has_posted_discussion($forumid, $userid) {
} }
} }
function forum_user_has_posted($forumid,$did,$userid) { function forum_user_has_posted($forumid, $did, $userid) {
return record_exists('forum_posts','discussion',$did,'userid',$userid); return record_exists('forum_posts','discussion',$did,'userid',$userid);
} }
function forum_user_can_post_discussion($forum, $currentgroup=false, $groupmode='', $edit=0) { function forum_user_can_post_discussion($forum, $currentgroup=false, $groupmode='') {
// $forum is an object // $forum is an object
global $USER, $SESSION; global $USER, $SESSION;
if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
error('Course Module ID was incorrect');
}
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
if (!has_capability('mod/forum:startdiscussion', $context->id)) {
return false;
}
if ($forum->type == "eachuser") { if ($forum->type == "eachuser") {
if ($edit) { // fix for 5551, if 1 post per user, should allow edit, if poster is owner return (!forum_user_has_posted_discussion($forum->id, $USER->id));
$post = get_record('forum_posts','id',$edit);
return ($post->userid == $USER->id); // editting your own post?
} else {
return (! forum_user_has_posted_discussion($forum->id, $USER->id));
}
} else if ($forum->type == 'qanda') {
return isteacher($forum->course);
} else if ($forum->type == "teacher") {
return isteacher($forum->course);
} else if ($currentgroup) { } else if ($currentgroup) {
return (isteacheredit($forum->course) or (ismember($currentgroup) and $forum->open == 2)); return (has_capability('mod/forum:viewdiscussionsfromallgroups', $context->id)
} else if (isteacher($forum->course)) { or (ismember($currentgroup) and $forum->open == 2));
return true;
} else { } else {
//else it might be group 0 in visible mode //else it might be group 0 in visible mode
if ($groupmode == VISIBLEGROUPS){ if ($groupmode == VISIBLEGROUPS){
return ($forum->open == 2 AND ismember($currentgroup)); return ($forum->open == 2 and ismember($currentgroup));
} }
else { else {
return ($forum->open == 2); return ($forum->open == 2);
@ -2745,24 +2792,35 @@ function forum_user_can_post_discussion($forum, $currentgroup=false, $groupmode=
} }
} }
/**
* This function checks whether the user can reply to posts in a forum
* discussion. Use forum_user_can_post_discussion() to check whether the user
* can start dicussions.
* @param $forum - forum object
* @param $user - user object
*/
function forum_user_can_post($forum, $user=NULL) { function forum_user_can_post($forum, $user=NULL) {
// $forum, $user are objects
if ($user) { if (!$forum->open) {
$isteacher = isteacher($forum->course, $user->id); // No point doing the more expensive has_capability checks.
} else { return false;
$isteacher = isteacher($forum->course);
} }
if ($forum->type == "teacher") { if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
return $isteacher; error('Course Module ID was incorrect');
} else if ($isteacher) {
return true;
} else {
return $forum->open;
} }
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
if (isset($user)) {
$canreply = has_capability('mod/forum:replypost', $context->id, false, $user->id);
} else {
$canreply = has_capability('mod/forum:replypost', $context->id, false);
}
return $canreply;
} }
//checks to see if a user can view a particular post //checks to see if a user can view a particular post
function forum_user_can_view_post($post, $course, $cm, $forum, $discussion, $user=NULL){ function forum_user_can_view_post($post, $course, $cm, $forum, $discussion, $user=NULL){
@ -2772,32 +2830,28 @@ function forum_user_can_view_post($post, $course, $cm, $forum, $discussion, $use
$user = $USER; $user = $USER;
} }
if (isteacheredit($course->id)) { $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
return true; if (!has_capability('mod/forum:viewdiscussion', $modcontext->id)) {
return false;
} }
if ($forum->type == 'teacher'){ //teacher type forum $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
return isteacher($course->id); if (!has_capability('moodle/course:view', $coursecontext->id)) {
}
/// Make sure the user is allowed in the course
if (!(isstudent($course->id) or
isteacher($course->id) or
($course->id == SITEID && !$CFG->forcelogin) or
(isguest() && $course->guest) )){
return false; return false;
} }
/// If it's a grouped discussion, make sure the user is a member /// If it's a grouped discussion, make sure the user is a member
if ($discussion->groupid > 0) { if ($discussion->groupid > 0) {
if ($cm->groupmode == SEPARATEGROUPS) { if ($cm->groupmode == SEPARATEGROUPS) {
return ismember($discussion->groupid); return ismember($discussion->groupid) ||
has_capability('mod/forum:viewdiscussionsfromallgroups', $modcontext->id);
} }
} }
return true; return true;
} }
function forum_user_can_see_discussion($forum,$discussion,$user=NULL) {
function forum_user_can_see_discussion($forum, $discussion, $contextid, $user=NULL) {
global $USER; global $USER;
if (empty($user) || empty($user->id)) { if (empty($user) || empty($user->id)) {
@ -2815,29 +2869,30 @@ function forum_user_can_see_discussion($forum,$discussion,$user=NULL) {
return false; return false;
} }
} }
if ($forum->type == 'qanda') {
return (forum_user_has_posted($forum->id,$discussion->id,$user->id) || isteacher($forum->course)); if (!has_capability('mod/forum:viewdiscussion', $contextid)) {
return false;
}
if ($forum->type == 'qanda' &&
!forum_user_has_posted($forum->id, $discussion->id, $user->id) &&
!has_capability('mod/forum:viewqandawithoutposting', $contextid)) {
return false;
} }
return true; return true;
} }
function forum_user_can_see_post($forum,$discussion,$post,$user=NULL) { function forum_user_can_see_post($forum, $discussion, $post, $user=NULL) {
global $USER; global $USER;
if (empty($user) || empty($user->id)) {
$user = $USER;
}
// retrive objects (yuk) // retrive objects (yuk)
if (is_numeric($forum)) { if (is_numeric($forum)) {
if (!$forum = get_record('forum','id',$forum)) { if (!$forum = get_record('forum','id',$forum)) {
return false; return false;
} }
} }
if (isteacher($forum->course)) {
return true;
}
if (is_numeric($discussion)) { if (is_numeric($discussion)) {
if (!$discussion = get_record('forum_discussions','id',$discussion)) { if (!$discussion = get_record('forum_discussions','id',$discussion)) {
return false; return false;
@ -2848,14 +2903,29 @@ function forum_user_can_see_post($forum,$discussion,$post,$user=NULL) {
return false; return false;
} }
} }
if (!isset($post->id) && isset($post->parent)) { if (!isset($post->id) && isset($post->parent)) {
$post->id = $post->parent; $post->id = $post->parent;
} }
if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
error('Course Module ID was incorrect');
}
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
if (empty($user) || empty($user->id)) {
$user = $USER;
}
if (!has_capability('mod/forum:viewdiscussion', $context->id, false, $user->id)) {
return false;
}
if ($forum->type == 'qanda') { if ($forum->type == 'qanda') {
$firstpost = forum_get_firstpost_from_discussion($discussion->id); $firstpost = forum_get_firstpost_from_discussion($discussion->id);
return (forum_user_has_posted($forum->id,$discussion->id,$user->id) || $firstpost->id == $post->id || isteacher($forum->course));
return (forum_user_has_posted($forum->id,$discussion->id,$user->id) ||
$firstpost->id == $post->id ||
has_capability('mod/forum:viewqandawithoutposting', $context->id, false, $user->id));
} }
return true; return true;
} }
@ -2878,6 +2948,12 @@ function forum_print_latest_discussions($course, $forum, $maxdiscussions=5, $dis
$currentgroup=-1, $groupmode=-1, $page=-1) { $currentgroup=-1, $groupmode=-1, $page=-1) {
global $CFG, $USER; global $CFG, $USER;
if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
error('Course Module ID was incorrect');
}
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
/// Sort out some defaults /// Sort out some defaults
if ((!$maxdiscussions) && ($displayformat == 'plain')) { if ((!$maxdiscussions) && ($displayformat == 'plain')) {
@ -2906,7 +2982,8 @@ function forum_print_latest_discussions($course, $forum, $maxdiscussions=5, $dis
$currentgroup = get_current_group($course->id); $currentgroup = get_current_group($course->id);
} }
if (!$currentgroup and ($groupmode != SEPARATEGROUPS or isteacheredit($course->id)) ) { if (!$currentgroup and ($groupmode != SEPARATEGROUPS or
has_capability('mod/forum:viewdiscussionsfromallgroups', $context->id)) ) {
$visiblegroups = -1; $visiblegroups = -1;
} else { } else {
$visiblegroups = $currentgroup; $visiblegroups = $currentgroup;
@ -3098,7 +3175,7 @@ function forum_print_latest_discussions($course, $forum, $maxdiscussions=5, $dis
} }
function forum_print_discussion($course, $forum, $discussion, $post, $mode, $canreply=NULL) { function forum_print_discussion($course, $forum, $discussion, $post, $mode, $canreply=NULL, $canrate=false) {
global $USER, $CFG; global $USER, $CFG;
@ -3120,11 +3197,12 @@ function forum_print_discussion($course, $forum, $discussion, $post, $mode, $can
$ratings->assesspublic = $forum->assesspublic; $ratings->assesspublic = $forum->assesspublic;
$ratings->assesstimestart = $forum->assesstimestart; $ratings->assesstimestart = $forum->assesstimestart;
$ratings->assesstimefinish = $forum->assesstimefinish; $ratings->assesstimefinish = $forum->assesstimefinish;
$ratings->allow = (($forum->assessed != 2 or isteacher($course->id)) && !isguest()); $ratings->allow = $canrate;
if ($ratings->allow) { if ($ratings->allow) {
echo '<form name="form" method="post" action="rate.php">'; echo '<form name="form" method="post" action="rate.php">';
echo '<input type="hidden" name="id" value="'.$course->id.'" />'; echo '<input type="hidden" name="id" value="'.$course->id.'" />';
echo '<input type="hidden" name="forumid" value="'.$forum->id.'" />';
} }
} }
} }
@ -3241,7 +3319,7 @@ function forum_print_posts_threaded($parent, $courseid, $depth, $ratings, $reply
if (!forum_user_can_see_post($post->forum,$post->discussion,$post)) { if (!forum_user_can_see_post($post->forum,$post->discussion,$post)) {
continue; continue;
} }
$by->name = fullname($post, isteacher($courseid)); $by->name = fullname($post);
$by->date = userdate($post->modified); $by->date = userdate($post->modified);
if ($istracking) { if ($istracking) {
@ -3426,19 +3504,17 @@ function forum_update_subscriptions_button($courseid, $forumid) {
// Prints the editing button on subscribers page // Prints the editing button on subscribers page
global $CFG, $USER; global $CFG, $USER;
if (isteacher($courseid)) { if (!empty($USER->subscriptionsediting)) {
if (!empty($USER->subscriptionsediting)) { $string = get_string("turneditingoff");
$string = get_string("turneditingoff"); $edit = "off";
$edit = "off"; } else {
} else { $string = get_string("turneditingon");
$string = get_string("turneditingon"); $edit = "on";
$edit = "on";
}
return "<form target=\"$CFG->framename\" method=\"get\" action=\"$CFG->wwwroot/mod/forum/subscribers.php\">".
"<input type=\"hidden\" name=\"id\" value=\"$forumid\" />".
"<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
"<input type=\"submit\" value=\"$string\" /></form>";
} }
return "<form target=\"$CFG->framename\" method=\"get\" action=\"$CFG->wwwroot/mod/forum/subscribers.php\">".
"<input type=\"hidden\" name=\"id\" value=\"$forumid\" />".
"<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
"<input type=\"submit\" value=\"$string\" /></form>";
} }
function forum_add_user($userid, $courseid) { function forum_add_user($userid, $courseid) {

View file

@ -29,7 +29,7 @@
if (isguest()) { // Guests can't change forum if (isguest()) { // Guests can't change forum
$wwwroot = $CFG->wwwroot.'/login/index.php'; $wwwroot = $CFG->wwwroot.'/login/index.php';
if (!empty($CFG->loginhttps)) { if (!empty($CFG->loginhttps)) {
$wwwroot = str_replace('http:','https:', $wwwroot); $wwwroot = str_replace('http','https', $wwwroot);
} }
$strforums = get_string('modulenameplural', 'forum'); $strforums = get_string('modulenameplural', 'forum');

View file

@ -105,17 +105,6 @@
<?php print_textarea($usehtmleditor, 20, 50, 680, 400, 'intro', $form->intro); ?> <?php print_textarea($usehtmleditor, 20, 50, 680, 400, 'intro', $form->intro); ?>
</td> </td>
</tr> </tr>
<tr valign="top">
<td align="right"><b><?php print_string('allowdiscussions', 'forum', strtolower("$course->student")) ?>:</b></td>
<td>
<?php
choose_from_menu($FORUM_OPEN_MODES, 'open', $form->open, '');
helpbutton('allowdiscussions', get_string('allowdiscussions',
'forum', moodle_strtolower("$course->student")), 'forum');
?>
</td>
</tr>
<tr> <tr>
<td align="right"><b><?php print_string('forcesubscribeq', 'forum') ?>:</b></td> <td align="right"><b><?php print_string('forcesubscribeq', 'forum') ?>:</b></td>
<td> <td>
@ -219,25 +208,6 @@
echo '&nbsp;'.get_string('ratingsuse', 'forum').':'; echo '&nbsp;'.get_string('ratingsuse', 'forum').':';
echo '</td></tr>'; echo '</td></tr>';
echo '<tr><td>';
// The odd order below was to maintain backward compatibility
unset($options);
$options[2] = get_string('ratingonlyteachers', 'forum', moodle_strtolower($course->teachers));
$options[1] = get_string('ratingeveryone', 'forum');
echo get_string('users').': ';
echo '</td><td>';
choose_from_menu($options, 'assessed', $form->assessed, '');
echo '</td></tr>';
echo '<tr><td>';
unset($options);
$options[0] = get_string('ratingpublicnot', 'forum', $course->students);
$options[1] = get_string('ratingpublic', 'forum', $course->students);
echo get_string('view').': ';
echo '</td><td>';
choose_from_menu($options, 'assesspublic', $form->assesspublic, '');
echo '</td></tr>';
echo '<tr><td>'; echo '<tr><td>';
echo get_string('grade').': '; echo get_string('grade').': ';
echo '</td><td>'; echo '</td><td>';

View file

@ -1,4 +1,9 @@
<?php <?php
/**
* This file is required by post.php. Therefore, the context objects
* $modcontext and $coursecontext are available to the script.
*/
if (!isset($discussion->timestart)) { if (!isset($discussion->timestart)) {
$discussion->timestart = 0; $discussion->timestart = 0;
} }
@ -59,7 +64,8 @@ if (!isset($discussion->timeend)) {
<?php <?php
if (forum_is_forcesubscribed($forum->id)) { if (forum_is_forcesubscribed($forum->id)) {
print_string("everyoneissubscribed", "forum"); print_string("everyoneissubscribed", "forum");
} else if ($forum->forcesubscribe != FORUM_DISALLOWSUBSCRIBE || isteacher($forum->course)){ } else if ($forum->forcesubscribe != FORUM_DISALLOWSUBSCRIBE ||
has_capability('moodle/course:manageactivities', $coursecontext->id)){
unset($options); unset($options);
if (forum_is_subscribed($USER->id, $post->forum)) { if (forum_is_subscribed($USER->id, $post->forum)) {
$options[0] = get_string("subscribestart", "forum"); $options[0] = get_string("subscribestart", "forum");
@ -102,7 +108,10 @@ if (!isset($discussion->timeend)) {
<?php } ?> <?php } ?>
<?php if (isadmin() && empty($post->id)) { ?> <?php
if (has_capability('moodle/course:manageactivities', $coursecontext->id)
&& empty($post->id)) {
?>
<tr valign="top"> <tr valign="top">
<td align="right"><b><?php print_string("mailnow", "forum") ?>:</b></td> <td align="right"><b><?php print_string("mailnow", "forum") ?>:</b></td>
@ -113,9 +122,8 @@ if (!isset($discussion->timeend)) {
<?php } ?> <?php } ?>
<?php if (!empty($CFG->forum_enabletimedposts) && <?php if (!empty($CFG->forum_enabletimedposts) && !$post->parent) {
isteacher($course->id) && $forum->type == 'news' && !$post->parent) { // This is the first post of a discussion, and timed posts are enabled.
// This is the first post of a discussion in news forum
?> ?>
<tr valign="top"> <tr valign="top">
<td align="right"><b><?php print_string("displayperiod", "forum") ?>:<br />(<?php print_string("optional") ?>)&nbsp;</b></td> <td align="right"><b><?php print_string("displayperiod", "forum") ?>:<br />(<?php print_string("optional") ?>)&nbsp;</b></td>
@ -150,7 +158,7 @@ if (!isset($discussion->timeend)) {
<?php } else { ?> <?php } else { ?>
<input type="hidden" name="timestartdisabled" value="1" /> <input type="hidden" name="timestartdisabled" value="1" />
<input type="hidden" name="timeenddisabled" value="1" /> <input type="hidden" name="timeenddisabled" value="1" />
<?php } ?> <? } ?>
<tr> <tr>
<td align="center" colspan="2"> <td align="center" colspan="2">
<input type="hidden" name="course" value="<?php p($post->course) ?>" /> <input type="hidden" name="course" value="<?php p($post->course) ?>" />
@ -158,6 +166,7 @@ if (!isset($discussion->timeend)) {
<input type="hidden" name="discussion" value="<?php p($post->discussion) ?>" /> <input type="hidden" name="discussion" value="<?php p($post->discussion) ?>" />
<input type="hidden" name="parent" value="<?php p($post->parent) ?>" /> <input type="hidden" name="parent" value="<?php p($post->parent) ?>" />
<input type="hidden" name="userid" value="<?php p($post->userid) ?>" /> <input type="hidden" name="userid" value="<?php p($post->userid) ?>" />
<input type="hidden" name="groupid" value="<?php p($post->groupid) ?>" />
<input type="hidden" name="edit" value="<?php p($post->edit) ?>" /> <input type="hidden" name="edit" value="<?php p($post->edit) ?>" />
<input type="submit" value="<?php p(($post->edit) ? get_string('savechanges') : get_string('posttoforum', 'forum')); ?>" /> <input type="submit" value="<?php p(($post->edit) ? get_string('savechanges') : get_string('posttoforum', 'forum')); ?>" />
</td> </td>

View file

@ -13,13 +13,17 @@
$name = optional_param('name','',PARAM_CLEAN); $name = optional_param('name','',PARAM_CLEAN);
$confirm = optional_param('confirm',0,PARAM_INT); $confirm = optional_param('confirm',0,PARAM_INT);
$coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
if (isguest()) { if (isguest()) {
$wwwroot = $CFG->wwwroot.'/login/index.php'; $wwwroot = $CFG->wwwroot.'/login/index.php';
if (!empty($CFG->loginhttps)) { if (!empty($CFG->loginhttps)) {
$wwwroot = str_replace('http:','https:', $wwwroot); $wwwroot = str_replace('http','https', $wwwroot);
} }
if (!empty($forum)) { // User is starting a new discussion in a forum if (isset($forum)) { // User is starting a new discussion in a forum
if (! $forum = get_record('forum', 'id', $forum)) { if (! $forum = get_record('forum', 'id', $forum)) {
error('The forum number was incorrect'); error('The forum number was incorrect');
} }
@ -38,7 +42,10 @@
error('The course number was incorrect'); error('The course number was incorrect');
} }
if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) { // For the logs if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) { // For the logs
// Teacher forum?
$cm->id = 0; $cm->id = 0;
} else {
$modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
} }
$strforums = get_string('modulenameplural', 'forum'); $strforums = get_string('modulenameplural', 'forum');
@ -61,84 +68,54 @@
require_login(0, false); // Script is useless unless they're logged in require_login(0, false); // Script is useless unless they're logged in
if ($post = data_submitted()) { if ($post = data_submitted()) {
if (! $forum = get_record('forum', 'id', $forum)) { if (empty($post->course)) {
error('The forum number was incorrect'); error('No course was defined!');
} }
if (!$course = get_record('course', 'id', $forum->course)) { if (!$course = get_record('course', 'id', $post->course)) {
error('Could not find specified course!'); error('Could not find specified course!');
} }
require_login($course->id, false);
$adminedit = (isadmin() and !empty($CFG->admineditalways));
if (!empty($course->lang)) { // Override current language if (!empty($course->lang)) { // Override current language
$CFG->courselang = $course->lang; $CFG->courselang = $course->lang;
} }
if (empty($SESSION->fromurl)) { if (empty($SESSION->fromurl)) {
$errordestination = "$CFG->wwwroot/mod/forum/view.php?f=$forum->id"; $errordestination = "$CFG->wwwroot/mod/forum/view.php?f=$post->forum";
} else { } else {
$errordestination = $SESSION->fromurl; $errordestination = $SESSION->fromurl;
} }
$post->subject = clean_param(strip_tags($post->subject, '<lang><span>'), PARAM_CLEAN); // Strip all tags except multilang $post->subject = strip_tags($post->subject, '<lang><span>'); // Strip all tags except lang
//$post->message will be cleaned later before display //$post->message = clean_text($post->message, $post->format); // Clean up any bad tags
$post->attachment = isset($_FILES['attachment']) ? $_FILES['attachment'] : NULL; $post->attachment = isset($_FILES['attachment']) ? $_FILES['attachment'] : NULL;
if (!$cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) { // For the logs if (!$cm = get_coursemodule_from_instance("forum", $post->forum, $course->id)) { // For the logs
$cm->id = 0; $cm->id = 0;
} }
if (($post->subject == '') or ($post->message == '')) { if (!$post->subject or !$post->message) {
$post->error = get_string("emptymessage", "forum"); $post->error = get_string("emptymessage", "forum");
} else if ($post->edit) { } else if ($post->edit) { // Updating a post
/// Updating a post $post->id = $post->edit;
if (! $oldpost = forum_get_post_full($post->edit)) {
error("Post ID was incorrect");
}
if (($oldpost->userid <> $USER->id) and !$adminedit) {
error("You can't edit other people's posts!");
}
if (! $discussion = get_record("forum_discussions", "id", $oldpost->discussion)) {
error("This post is not part of a discussion!");
}
if ($discussion->forum != $forum->id) {
error("The forum number is incorrect");
}
if ($discussion->course != $course->id) {
error("The course number is incorrect");
}
if (!($forum->type == 'news' && !$oldpost->parent && $discussion->timestart > time())) {
if (((time() - $oldpost->created) > $CFG->maxeditingtime) and !$adminedit) {
error( get_string("maxtimehaspassed", "forum", format_time($CFG->maxeditingtime)) );
}
}
$updatepost = new object;
$updatepost->id = $oldpost->id;
$updatepost->parent = $oldpost->parent;
$updatepost->forum = $oldpost->forum;
$updatepost->discussion = $oldpost->discussion;
$updatepost->userid = $oldpost->userid;
$updatepost->subject = $post->subject; //already cleaned
$updatepost->message = $post->message; //cleaning only before display
$updatepost->format = $post->format;
$updatepost->attachment = $post->attachment;
$updatepost->course = $course->id;
$updatepost->subscribe = optional_param('subscribe', 0, PARAM_BOOL);
$updatepost->unsubscribe = optional_param('unsubscribe', 0, PARAM_BOOL);
$message = ''; $message = '';
if (get_field('forum', 'type', 'id', $forum) == 'news' && !$oldpost->parent) { //fix for bug #4314
$updatediscussion = new object; if (!$realpost = get_record('forum_posts','id',$post->id)){
$updatediscussion->id = $oldpost->discussion; $realpost = new object;
$realpost->userid = -1;
}
if ( !(($realpost->userid == $USER->id && has_capability('mod/forum:replypost', $modcontext->id)) ||
has_capability('mod/forum:editanypost', $modcontext->id)) )
error("You can not update this post");
}
if (get_field('forum', 'type', 'id', $forum) == 'news' && !$post->parent) {
$updatediscussion->id = $post->discussion;
if (empty($post->timestartdisabled)) { if (empty($post->timestartdisabled)) {
$updatediscussion->timestart = make_timestamp($post->timestartyear, $post->timestartmonth, $post->timestartday); $updatediscussion->timestart = make_timestamp($post->timestartyear, $post->timestartmonth, $post->timestartday);
} else { } else {
@ -158,10 +135,10 @@
if (!isset($post->error)) { if (!isset($post->error)) {
if (forum_update_post($updatepost,$message)) { if (forum_update_post($post,$message)) {
add_to_log($course->id, "forum", "update post", add_to_log($course->id, "forum", "update post",
"discuss.php?d=$updatepost->discussion&amp;parent=$updatepost->id", "$updatepost->id", $cm->id); "discuss.php?d=$post->discussion&amp;parent=$post->id", "$post->id", $cm->id);
$timemessage = 2; $timemessage = 2;
if (!empty($message)) { // if we're printing stuff about the file upload if (!empty($message)) { // if we're printing stuff about the file upload
@ -169,10 +146,10 @@
} }
$message .= '<br />'.get_string("postupdated", "forum"); $message .= '<br />'.get_string("postupdated", "forum");
if ($subscribemessage = forum_post_subscription($updatepost)) { if ($subscribemessage = forum_post_subscription($post)) {
$timemessage = 4; $timemessage = 4;
} }
redirect(forum_go_back_to("discuss.php?d=$updatepost->discussion#$updatepost->id"), $message.$subscribemessage, $timemessage); redirect(forum_go_back_to("discuss.php?d=$post->discussion#$post->id"), $message.$subscribemessage, $timemessage);
} else { } else {
error(get_string("couldnotupdate", "forum"), $errordestination); error(get_string("couldnotupdate", "forum"), $errordestination);
@ -180,49 +157,12 @@
exit; exit;
} }
} else if ($post->discussion) { } else if ($post->discussion) { // Adding a new post to an existing discussion
/// Adding a new post to an existing discussion
if (! $discussion = get_record("forum_discussions", "id", $post->discussion)) {
error("This post is not part of a discussion!");
}
if ($discussion->forum != $forum->id) {
error("The forum number is incorrect");
}
if ($discussion->course != $course->id) {
error("The course number is incorrect");
}
if (! $parent = forum_get_post_full($post->parent)) {
error("Parent post does not exist");
}
if ($parent->discussion != $discussion->id) {
error("Parent not in this discussion");
}
if (! forum_user_can_post($forum)) {
error("Sorry, but you can not post in this forum.");
}
$newpost = new object;
$newpost->parent = $post->parent;
$newpost->forum = $forum->id;
$newpost->discussion = $discussion->id;
$newpost->parent = $parent->id;
$newpost->subject = $post->subject; //already cleaned
$newpost->message = $post->message; //cleaning only before display
$newpost->format = $post->format;
$newpost->mailnow = optional_param('mailnow', 0, PARAM_BOOL);
$newpost->course = $course->id;
$newpost->subscribe = optional_param('subscribe', 0, PARAM_BOOL);
$newpost->unsubscribe = optional_param('unsubscribe', 0, PARAM_BOOL);
$message = ''; $message = '';
if ($post->id = forum_add_new_post($post,$message)) {
if ($newpost->id = forum_add_new_post($newpost,$message)) {
add_to_log($course->id, "forum", "add post", add_to_log($course->id, "forum", "add post",
"discuss.php?d=$newpost->discussion&amp;parent=$newpost->id", "$newpost->id", $cm->id); "discuss.php?d=$post->discussion&amp;parent=$post->id", "$post->id", $cm->id);
$timemessage = 2; $timemessage = 2;
if (!empty($message)) { // if we're printing stuff about the file upload if (!empty($message)) { // if we're printing stuff about the file upload
@ -230,51 +170,29 @@
} }
$message .= '<br />'.get_string("postadded", "forum", format_time($CFG->maxeditingtime)); $message .= '<br />'.get_string("postadded", "forum", format_time($CFG->maxeditingtime));
if ($subscribemessage = forum_post_subscription($newpost)) { if ($subscribemessage = forum_post_subscription($post)) {
$timemessage = 4; $timemessage = 4;
} }
if ($newpost->mailnow) { if ($post->mailnow) {
$message .= get_string("postmailnow", "forum"); $message .= get_string("postmailnow", "forum");
$timemessage = 4; $timemessage = 4;
} }
redirect(forum_go_back_to("discuss.php?d=$newpost->discussion#$newpost->id"), $message.$subscribemessage, $timemessage); redirect(forum_go_back_to("discuss.php?d=$post->discussion#$post->id"), $message.$subscribemessage, $timemessage);
} else { } else {
error(get_string("couldnotadd", "forum"), $errordestination); error(get_string("couldnotadd", "forum"), $errordestination);
} }
exit; exit;
} else { } else { // Adding a new discussion
/// Adding a new discussion $post->mailnow = empty($post->mailnow) ? 0 : 1;
if (! forum_user_can_post_discussion($forum)) { $discussion = $post;
error("Sorry, but you can not post a new discussion in this forum."); $discussion->name = $post->subject;
}
$discussion = new object;
$discussion->forum = $forum->id;
$discussion->course = $course->id;
$discussion->mailnow = optional_param('mailnow', 0, PARAM_BOOL);
$discussion->name = $post->subject;
$discussion->intro = $post->message; $discussion->intro = $post->message;
$discussion->format = $post->format;
$discussion->groupid = get_current_group($course->id);
if (isteacheredit($course->id) and $discussion->groupid == 0) {
$discussion->groupid = -1;
}
$discussion->course = $course->id;
$discussion->subscribe = optional_param('subscribe', 0, PARAM_BOOL);
$discussion->unsubscribe = optional_param('unsubscribe', 0, PARAM_BOOL);
if (! forum_user_can_post_discussion($forum)) {
error("Sorry, but you can not post a new discussion in this forum.");
}
$newstopic = false; $newstopic = false;
if (get_field('forum', 'type', 'id', $forum) == 'news') { if (get_field('forum', 'type', 'id', $forum) == 'news' && !$post->parent) {
$newstopic = true; $newstopic = true;
} }
if ($newstopic && empty($post->timestartdisabled)) { if ($newstopic && empty($post->timestartdisabled)) {
@ -302,7 +220,7 @@
} }
$message .= '<br />'.get_string("postadded", "forum", format_time($CFG->maxeditingtime)); $message .= '<br />'.get_string("postadded", "forum", format_time($CFG->maxeditingtime));
if ($discussion->mailnow) { if ($post->mailnow) {
$message .= get_string("postmailnow", "forum"); $message .= get_string("postmailnow", "forum");
$timemessage = 4; $timemessage = 4;
} }
@ -311,7 +229,7 @@
$timemessage = 4; $timemessage = 4;
} }
redirect(forum_go_back_to("view.php?f=$discussion->forum"), $message.$subscribemessage, $timemessage); redirect(forum_go_back_to("view.php?f=$post->forum"), $message.$subscribemessage, $timemessage);
} else { } else {
error(get_string("couldnotadd", "forum"), $errordestination); error(get_string("couldnotadd", "forum"), $errordestination);
@ -328,8 +246,7 @@
$defaultformat = FORMAT_MOODLE; $defaultformat = FORMAT_MOODLE;
} }
if (!empty($post->error)) { if (isset($post->error)) { // User is re-editing a failed posting
/// User is re-editing a failed posting
// Set up all the required objects again, and reuse the same $post // Set up all the required objects again, and reuse the same $post
@ -369,14 +286,9 @@
} }
} }
} else if (!empty($forum)) { } else if (!empty($forum)) { // User is starting a new discussion in a forum
/// User is starting a new discussion in a forum
if (!empty($_SERVER["HTTP_REFERER"])) { $SESSION->fromurl = $_SERVER["HTTP_REFERER"];
$SESSION->fromurl = $_SERVER["HTTP_REFERER"];
} else {
$SESSION->fromurl = '';
}
if (! $forum = get_record("forum", "id", $forum)) { if (! $forum = get_record("forum", "id", $forum)) {
error("The forum number was incorrect ($forum)"); error("The forum number was incorrect ($forum)");
@ -390,7 +302,7 @@
} }
if ($cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) { if ($cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
if (!$cm->visible and !isteacher($course->id)) { if (!$cm->visible and !has_capability('moodle/course:manageactivities', $coursecontext->id)) {
error(get_string("activityiscurrentlyhidden")); error(get_string("activityiscurrentlyhidden"));
} }
} }
@ -406,10 +318,14 @@
$post->message = ""; $post->message = "";
$post->format = $defaultformat; $post->format = $defaultformat;
$post->groupid = get_current_group($course->id);
if ($post->groupid == 0) {
$post->groupid = -1;
}
forum_set_return(); forum_set_return();
} else if (!empty($reply)) { } else if (!empty($reply)) { // User is writing a new reply
/// User is writing a new reply
if (! $parent = forum_get_post_full($reply)) { if (! $parent = forum_get_post_full($reply)) {
error("Parent post ID was incorrect"); error("Parent post ID was incorrect");
@ -429,13 +345,13 @@
} }
if ($cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) { if ($cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
if (groupmode($course, $cm) and !isteacheredit($course->id)) { // Make sure user can post here if (groupmode($course, $cm)) { // Make sure user can post here
$mygroupid = mygroupid($course->id); $mygroupid = mygroupid($course->id);
if (!((empty($mygroupid) and $discussion->groupid == -1) || (ismember($discussion->groupid)/*$mygroupid == $discussion->groupid*/))) { if (!((empty($mygroupid) and $discussion->groupid == -1) || (ismember($discussion->groupid)/*$mygroupid == $discussion->groupid*/))) {
error("Sorry, but you can not post in this discussion."); error("Sorry, but you can not post in this discussion.");
} }
} }
if (!$cm->visible and !isteacher($course->id)) { if (!$cm->visible and !has_capability('moodle/course:manageactivities', $coursecontext->id)) {
error(get_string("activityiscurrentlyhidden")); error(get_string("activityiscurrentlyhidden"));
} }
} }
@ -458,15 +374,13 @@
unset($SESSION->fromdiscussion); unset($SESSION->fromdiscussion);
} else if (!empty($edit)) { } else if (!empty($edit)) { // User is editing their own post
/// User is editing their own post
$adminedit = (isadmin() and !empty($CFG->admineditalways));
if (! $post = forum_get_post_full($edit)) { if (! $post = forum_get_post_full($edit)) {
error("Post ID was incorrect"); error("Post ID was incorrect");
} }
if (($post->userid <> $USER->id) and !$adminedit) { if (($post->userid <> $USER->id) and
!has_capability('mod/forum:editanypost', $modcontext->id)) {
error("You can't edit other people's posts!"); error("You can't edit other people's posts!");
} }
if ($post->parent) { if ($post->parent) {
@ -481,9 +395,9 @@
error("The forum number was incorrect ($discussion->forum)"); error("The forum number was incorrect ($discussion->forum)");
} }
if (!($forum->type == 'news' && !$post->parent && $discussion->timestart > time())) { if (!($forum->type == 'news' && !$post->parent && $discussion->timestart > time())) {
if (((time() - $post->created) > $CFG->maxeditingtime) and !$adminedit) { if (((time() - $post->created) > $CFG->maxeditingtime) and
error( get_string("maxtimehaspassed", "forum", format_time($CFG->maxeditingtime)), !has_capability('mod/forum:editanypost', $modcontext->id)) {
"$CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id#$post->id" ); error( get_string("maxtimehaspassed", "forum", format_time($CFG->maxeditingtime)) );
} }
} }
if (! $course = get_record("course", "id", $discussion->course)) { if (! $course = get_record("course", "id", $discussion->course)) {
@ -500,8 +414,7 @@
unset($SESSION->fromdiscussion); unset($SESSION->fromdiscussion);
} else if (!empty($delete)) { } else if (!empty($delete)) { // User is deleting a post
/// User is deleting a post
if (! $post = forum_get_post_full($delete)) { if (! $post = forum_get_post_full($delete)) {
error("Post ID was incorrect"); error("Post ID was incorrect");
@ -512,8 +425,9 @@
if (! $forum = get_record("forum", "id", $discussion->forum)) { if (! $forum = get_record("forum", "id", $discussion->forum)) {
error("The forum number was incorrect ($discussion->forum)"); error("The forum number was incorrect ($discussion->forum)");
} }
if (($post->userid <> $USER->id) and !isteacher($forum->course)) { if ( !(($post->userid == $USER->id && has_capability('mod/forum:deleteownpost', $modcontext->id))
error("You can't delete other people's posts!"); || has_capability('mod/forum:deleteanypost', $modcontext->id)) ) {
error("You can't delete this post!");
} }
if (!empty($forum->course)) { if (!empty($forum->course)) {
if ($course = get_record('course', 'id', $forum->course)) { if ($course = get_record('course', 'id', $forum->course)) {
@ -525,13 +439,13 @@
$replycount = forum_count_replies($post); $replycount = forum_count_replies($post);
if (!empty($confirm) and confirm_sesskey()) { // User has confirmed the delete if (!empty($confirm)) { // User has confirmed the delete
if ($post->totalscore) { if ($post->totalscore) {
notice(get_string("couldnotdeleteratings", "forum"), notice(get_string("couldnotdeleteratings", "forum"),
forum_go_back_to("discuss.php?d=$post->discussion")); forum_go_back_to("discuss.php?d=$post->discussion"));
} else if ($replycount && !isteacher($course->id)) { } else if ($replycount && !has_capability('mod/forum:deleteanypost', $modcontext->id)) {
error(get_string("couldnotdeletereplies", "forum"), error(get_string("couldnotdeletereplies", "forum"),
forum_go_back_to("discuss.php?d=$post->discussion")); forum_go_back_to("discuss.php?d=$post->discussion"));
@ -552,7 +466,7 @@
redirect("view.php?f=$discussion->forum", redirect("view.php?f=$discussion->forum",
get_string("deleteddiscussion", "forum"), 1); get_string("deleteddiscussion", "forum"), 1);
} else if (forum_delete_post($post, isteacher($course->id))) { } else if (forum_delete_post($post, has_capability('mod/forum:deleteanypost', $modcontext->id))) {
add_to_log($discussion->course, "forum", "delete post", add_to_log($discussion->course, "forum", "delete post",
"discuss.php?d=$post->discussion", "$post->id", $cm->id); "discuss.php?d=$post->discussion", "$post->id", $cm->id);
@ -565,19 +479,18 @@
} }
} else { } else { // User just asked to delete something
// User just asked to delete something
forum_set_return(); forum_set_return();
if ($replycount) { if ($replycount) {
if (!isteacher($course->id)) { if (!has_capability('mof/forum:deleteanypost', $modcontext->id)) {
error(get_string("couldnotdeletereplies", "forum"), error(get_string("couldnotdeletereplies", "forum"),
forum_go_back_to("discuss.php?d=$post->discussion")); forum_go_back_to("discuss.php?d=$post->discussion"));
} }
print_header(); print_header();
notice_yesno(get_string("deletesureplural", "forum", $replycount+1), notice_yesno(get_string("deletesureplural", "forum", $replycount+1),
"post.php?delete=$delete&amp;confirm=$delete&amp;sesskey=".sesskey(), "post.php?delete=$delete&amp;confirm=$delete",
$_SERVER["HTTP_REFERER"]); $_SERVER["HTTP_REFERER"]);
forum_print_post($post, $course->id, $ownpost=false, $reply=false, $link=false); forum_print_post($post, $course->id, $ownpost=false, $reply=false, $link=false);
@ -592,7 +505,7 @@
} else { } else {
print_header(); print_header();
notice_yesno(get_string("deletesure", "forum", $replycount), notice_yesno(get_string("deletesure", "forum", $replycount),
"post.php?delete=$delete&amp;confirm=$delete&amp;sesskey=".sesskey(), "post.php?delete=$delete&amp;confirm=$delete",
$_SERVER["HTTP_REFERER"]); $_SERVER["HTTP_REFERER"]);
forum_print_post($post, $forum->course, $ownpost=false, $reply=false, $link=false); forum_print_post($post, $forum->course, $ownpost=false, $reply=false, $link=false);
} }
@ -602,8 +515,7 @@
die; die;
} else if (!empty($prune)) { } else if (!empty($prune)) { // Teacher is pruning
// Teacher is pruning
if (!$post = forum_get_post_full($prune)) { if (!$post = forum_get_post_full($prune)) {
error("Post ID was incorrect"); error("Post ID was incorrect");
@ -614,7 +526,7 @@
if (!$forum = get_record("forum", "id", $discussion->forum)) { if (!$forum = get_record("forum", "id", $discussion->forum)) {
error("The forum number was incorrect ($discussion->forum)"); error("The forum number was incorrect ($discussion->forum)");
} }
if (!isteacher($forum->course)) { if (!has_capability('mod/forum:splitdiscussions', $modcontext->id)) {
error("You can't split discussions!"); error("You can't split discussions!");
} }
if (!$post->parent) { if (!$post->parent) {
@ -624,12 +536,11 @@
$cm->id = 0; $cm->id = 0;
} }
if (!empty($name) and confirm_sesskey()) { // User has confirmed the prune if (!empty($name)) { // User has confirmed the prune
$newdiscussion = new object;
$newdiscussion->course = $discussion->course; $newdiscussion->course = $discussion->course;
$newdiscussion->forum = $discussion->forum; $newdiscussion->forum = $discussion->forum;
$newdiscussion->name = strip_tags($name, '<lang><span>'); // Strip all tags except multilang $newdiscussion->name = $name;
$newdiscussion->firstpost = $post->id; $newdiscussion->firstpost = $post->id;
$newdiscussion->userid = $discussion->userid; $newdiscussion->userid = $discussion->userid;
$newdiscussion->groupid = $discussion->groupid; $newdiscussion->groupid = $discussion->groupid;
@ -644,7 +555,7 @@
$newpost->id = $post->id; $newpost->id = $post->id;
$newpost->parent = 0; $newpost->parent = 0;
$newpost->subject = $newdiscussion->name; $newpost->subject = $name;
if (!update_record("forum_posts", $newpost)) { if (!update_record("forum_posts", $newpost)) {
error('Could not update the original post'); error('Could not update the original post');
@ -752,11 +663,12 @@
if (!empty($parent) && !forum_user_can_see_post($forum,$discussion,$post)) { if (!empty($parent) && !forum_user_can_see_post($forum,$discussion,$post)) {
error("You cannot reply to this post"); error("You cannot reply to this post");
} }
if (empty($parent) && !forum_user_can_post_discussion($forum, false, '', $edit)) { if (empty($parent) && !forum_user_can_post_discussion($forum)) {
error("You cannot start a new discussion in this forum"); error("You cannot start a new discussion in this forum");
} }
if ($forum->type == 'qanda' && !isteacher($forum->course) && !forum_user_has_posted($forum->id,$discussion->id,$USER->id)) { if ($forum->type == 'qanda' && !has_capability('mod/forum:viewqandawithoutposting', $modcontext->id) &&
!forum_user_has_posted($forum->id,$discussion->id,$USER->id)) {
notify(get_string('qandanotify','forum')); notify(get_string('qandanotify','forum'));
} }
@ -770,7 +682,7 @@
} else { } else {
$user_read_array = array(); $user_read_array = array();
} }
if ($forum->type != 'qanda' || forum_user_can_see_discussion($forum,$discussion)) { if ($forum->type != 'qanda' || forum_user_can_see_discussion($forum, $discussion, $modcontext->id)) {
forum_print_posts_threaded($parent->id, $course->id, 0, false, false, $user_read_array, $discussion->forum); forum_print_posts_threaded($parent->id, $course->id, 0, false, false, $user_read_array, $discussion->forum);
} }
} }

View file

@ -11,7 +11,6 @@
<td align="center" colspan="2"> <td align="center" colspan="2">
<input type="hidden" name="prune" value="<?php p($prune) ?>" /> <input type="hidden" name="prune" value="<?php p($prune) ?>" />
<input type="hidden" name="confirm" value="<?php p($prune) ?>" /> <input type="hidden" name="confirm" value="<?php p($prune) ?>" />
<input type="hidden" name="sesskey" value="<?php echo sesskey() ?>" />
<input type="submit" value="<?php print_string('prune', 'forum'); ?>" /> <input type="submit" value="<?php print_string('prune', 'forum'); ?>" />
</td> </td>
</tr> </tr>

View file

@ -6,11 +6,20 @@
require_once("../../config.php"); require_once("../../config.php");
require_once("lib.php"); require_once("lib.php");
if (isguest()) {
error("Guests are not allowed to rate posts.", $_SERVER["HTTP_REFERER"]); $id = required_param('id',PARAM_INT); // The course these ratings are part of
$forumid = required_param('forumid',PARAM_INT); // The forum the rated posts are from
if (! $cm = get_coursemodule_from_instance('forum', $forumid, $id)) {
error('Course Module ID was incorrect');
}
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
if (!has_capability('mod/forum:ratepost', $context->id) {
error('You do not have the permission to rate this post');
} }
$id = required_param('id',PARAM_INT); // The course these ratings are part of
if (! $course = get_record("course", "id", $id)) { if (! $course = get_record("course", "id", $id)) {
error("Course ID was incorrect"); error("Course ID was incorrect");

View file

@ -5,8 +5,7 @@
require_once("../../config.php"); require_once("../../config.php");
require_once("lib.php"); require_once("lib.php");
$id = required_param('id',PARAM_INT); $id = required_param('id',PARAM_INT);
$sort = optional_param('sort', '', PARAM_RAW);
if (! $post = get_record("forum_posts", "id", $id)) { if (! $post = get_record("forum_posts", "id", $id)) {
error("Post ID was incorrect"); error("Post ID was incorrect");
@ -24,15 +23,21 @@
error("Course ID was incorrect"); error("Course ID was incorrect");
} }
if (!isteacher($course->id) and $USER->id != $post->userid) { if (! $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) {
error("You can only look at results for posts you own"); error('Course Module ID was incorrect');
} }
switch ($sort) { $context = get_context_instance(CONTEXT_MODULE, $cm->id);
case 'time': $sqlsort = "r.time ASC"; break;
case 'firstname': $sqlsort = "u.firstname ASC"; break; if (!has_capability('mod/forum:viewrating', $context->id)) {
case 'rating': $sqlsort = "r.rating ASC"; break; error('You do not have the capability to view post ratings');
default: $sqlsort = "r.time ASC"; }
if (!has_capability('mod/forum:viewanyrating', $context->id) and $USER->id != $post->userid) {
error("You can only look at results for posts that you made");
}
if (!isset($sort)) {
$sort = "r.time";
} }
$scalemenu = make_grades_menu($forum->scale); $scalemenu = make_grades_menu($forum->scale);
@ -44,22 +49,18 @@
print_header("$strratings: ".format_string($post->subject)); print_header("$strratings: ".format_string($post->subject));
if (!$ratings = forum_get_ratings($post->id, $sqlsort)) { if (!$ratings = forum_get_ratings($post->id, $sort)) {
error("No ratings for this post: \"".format_string($post->subject)."\""); error("No ratings for this post: \"".format_string($post->subject)."\"");
} else { } else {
echo "<table border=\"0\" cellpadding=\"3\" cellspacing=\"3\" class=\"generalbox\" width=\"100%\">"; echo "<table border=\"0\" cellpadding=\"3\" cellspacing=\"3\" class=\"generalbox\" width=\"100%\">";
echo "<tr>"; echo "<tr>";
echo "<th>&nbsp;</th>"; echo "<th>&nbsp;</th>";
echo "<th><a href=\"report.php?id=$post->id&amp;sort=firstname\">$strname</a>"; echo "<th><a href=\"report.php?id=$post->id&amp;sort=u.firstname\">$strname</a>";
echo "<th width=\"100%\"><a href=\"report.php?id=$post->id&amp;sort=rating\">$strrating</a>"; echo "<th width=\"100%\"><a href=\"report.php?id=$post->id&amp;sort=r.rating\">$strrating</a>";
echo "<th><a href=\"report.php?id=$post->id&amp;sort=time\">$strtime</a>"; echo "<th><a href=\"report.php?id=$post->id&amp;sort=r.time\">$strtime</a>";
foreach ($ratings as $rating) { foreach ($ratings as $rating) {
if (isteacher($discussion->course, $rating->id)) { echo '<tr class="forumpostheader">';
echo '<tr class="forumpostheadertopic">';
} else {
echo '<tr class="forumpostheader">';
}
echo "<td>"; echo "<td>";
print_user_picture($rating->id, $forum->course, $rating->picture); print_user_picture($rating->id, $forum->course, $rating->picture);
echo '<td nowrap="nowrap"><p><font size="-1">'.fullname($rating).'</p>'; echo '<td nowrap="nowrap"><p><font size="-1">'.fullname($rating).'</p>';

View file

@ -165,11 +165,7 @@
$status = true; $status = true;
//Get the discussions array //Get the discussions array
if (!empty($info['MOD']['#']['SUBSCRIPTIONS'])) { $subscriptions = $info['MOD']['#']['SUBSCRIPTIONS']['0']['#']['SUBSCRIPTION'];
$subscriptions = $info['MOD']['#']['SUBSCRIPTIONS']['0']['#']['SUBSCRIPTION'];
} else {
$subscriptions = array();
}
//Iterate over subscriptions //Iterate over subscriptions
for($i = 0; $i < sizeof($subscriptions); $i++) { for($i = 0; $i < sizeof($subscriptions); $i++) {
@ -226,11 +222,7 @@
$status = true; $status = true;
//Get the discussions array //Get the discussions array
if (!empty($info['MOD']['#']['DISCUSSIONS'])) { $discussions = $info['MOD']['#']['DISCUSSIONS']['0']['#']['DISCUSSION'];
$discussions = $info['MOD']['#']['DISCUSSIONS']['0']['#']['DISCUSSION'];
} else {
$discussions = array();
}
//Iterate over discussions //Iterate over discussions
for($i = 0; $i < sizeof($discussions); $i++) { for($i = 0; $i < sizeof($discussions); $i++) {
@ -331,11 +323,7 @@
$status = true; $status = true;
//Get the read array //Get the read array
if (!empty($info['MOD']['#']['READPOSTS'])) { $readposts = $info['MOD']['#']['READPOSTS']['0']['#']['READ'];
$readposts = $info['MOD']['#']['READPOSTS']['0']['#']['READ'];
} else {
$readposts = array();
}
//Iterate over readposts //Iterate over readposts
for($i = 0; $i < sizeof($readposts); $i++) { for($i = 0; $i < sizeof($readposts); $i++) {
@ -878,17 +866,6 @@
$log->url = "search.php?id=".$log->course."&search=".urlencode($log->info); $log->url = "search.php?id=".$log->course."&search=".urlencode($log->info);
$status = true; $status = true;
break; break;
case "user report":
//recode the info field (it's the user id)
$user = backup_getid($restore->backup_unique_code,"user",$log->info);
if ($user) {
$log->info = $user->new_id;
//Now, extract the mode from the url field
$mode = substr(strrchr($log->url,"="),1);
$log->url = "user.php?course=".$log->course."&id=".$log->info."&mode=".$mode;
$status = true;
}
break;
default: default:
if (!defined('RESTORE_SILENTLY')) { if (!defined('RESTORE_SILENTLY')) {
echo "action (".$log->module."-".$log->action.") unknown. Not restored<br />"; //Debug echo "action (".$log->module."-".$log->action.") unknown. Not restored<br />"; //Debug

View file

@ -79,20 +79,6 @@
return $status; return $status;
} }
// Given a forum object, deletes the RSS file
function forum_rss_delete_file($forum) {
global $CFG;
//return unlink("{$CFG->dataroot}/rss/{$modname}/{$forum->id}.xml");
$rssfile = rss_file_name('forum', $forum);
if (file_exists($rssfile)) {
return unlink($rssfile);
} else {
return true;
}
}
function forum_rss_newstuff($forum, $time) { function forum_rss_newstuff($forum, $time) {
// If there is new stuff in the forum since $time then this returns // If there is new stuff in the forum since $time then this returns
// true. Otherwise it returns false. // true. Otherwise it returns false.
@ -172,7 +158,7 @@
$items = array(); $items = array();
if ($newsince) { if ($newsince) {
$newsince = " AND (p.modified > '$newsince' OR d.timemodified > '$newsince')"; $newsince = " AND p.modified > '$newsince'";
} else { } else {
$newsince = ""; $newsince = "";
} }
@ -232,7 +218,7 @@
$items = array(); $items = array();
if ($newsince) { if ($newsince) {
$newsince = " AND (p.modified > '$newsince' OR d.timemodified > '$newsince')"; $newsince = " AND p.modified > '$newsince'";
} else { } else {
$newsince = ""; $newsince = "";
} }
@ -277,7 +263,7 @@
$item->description = format_text($rec->postmessage,$rec->postformat,NULL,$forum->course); $item->description = format_text($rec->postmessage,$rec->postformat,NULL,$forum->course);
$post_file_area_name = "$forum->course/$CFG->moddata/forum/$forum->id/$rec->postid"; $post_file_area_name = str_replace('//', '/', "$forum->course/$CFG->moddata/$rec->course/forum/$forum->id/$rec->postid");
$post_files = get_directory_list("$CFG->dataroot/$post_file_area_name"); $post_files = get_directory_list("$CFG->dataroot/$post_file_area_name");
if (!empty($post_files)) { if (!empty($post_files)) {

View file

@ -114,13 +114,13 @@
$searchform = forum_search_form($course, $search); $searchform = forum_search_form($course, $search);
if ((!isteacheredit($course->id)) and forum_get_separate_modules($course->id)) { if ($group = user_group($course->id, $USER->id)) {
$sepgroups = user_group($course->id, $USER->id); $groupid = $group->id;
} else { } else {
$sepgroups = false; $groupid = 0;
} }
if (!$posts = forum_search_posts($searchterms, $course->id, $page*$perpage, $perpage, $totalcount, $sepgroups)) { if (!$posts = forum_search_posts($searchterms, $course->id, $page*$perpage, $perpage, $totalcount, $groupid)) {
print_header_simple("$strsearchresults", "", print_header_simple("$strsearchresults", "",
"<a href=\"index.php?id=$course->id\">$strforums</a> -> "<a href=\"index.php?id=$course->id\">$strforums</a> ->
@ -361,15 +361,7 @@ function forum_clean_search_terms($words, $prefix='') {
function forum_menu_list($course) { function forum_menu_list($course) {
$menu = array(); $menu = array();
$currentgroup = get_current_group($course->id); $currentgroup = get_current_group($course->id);
$isteacher = isteacher($course->id);
if ($isteacher) { // Add teacher forum
if ($forum = forum_get_course_forum($course->id, 'teacher')) {
$menu[$forum->id] = format_string($forum->name,true);
}
}
if ($forums = get_all_instances_in_course("forum", $course)) { if ($forums = get_all_instances_in_course("forum", $course)) {
if ($course->format == 'weeks') { if ($course->format == 'weeks') {
@ -379,23 +371,19 @@ function forum_menu_list($course) {
} }
foreach ($forums as $forum) { foreach ($forums as $forum) {
if (!$isteacher) { // Non-teachers if ($cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) {
if ($forum->type == "teacher") { if (!isset($forum->visible)) {
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
if (!instance_is_visible("forum", $forum) &&
!has_capability('moodle/course:viewhiddenactivities', $context->id)) {
continue;
}
}
$groupmode = groupmode($course, $cm); // Groups are being used
if (($groupmode == SEPARATEGROUPS) and ($currentgroup === false)) {
continue; continue;
} }
if (!isset($forum->visible)) {
if (! instance_is_visible("forum", $forum)) {
continue;
}
}
if ($cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) {
$groupmode = groupmode($course, $cm); // Groups are being used
if (($groupmode == SEPARATEGROUPS) and ($currentgroup === false)) {
continue;
}
}
} }
$menu[$forum->id] = format_string($forum->name,true); $menu[$forum->id] = format_string($forum->name,true);
} }
} }
@ -404,4 +392,3 @@ function forum_menu_list($course) {
} }
?> ?>

View file

@ -27,7 +27,7 @@
if (isguest()) { // Guests can't change tracking if (isguest()) { // Guests can't change tracking
$wwwroot = $CFG->wwwroot.'/login/index.php'; $wwwroot = $CFG->wwwroot.'/login/index.php';
if (!empty($CFG->loginhttps)) { if (!empty($CFG->loginhttps)) {
$wwwroot = str_replace('http:','https:', $wwwroot); $wwwroot = str_replace('http','https', $wwwroot);
} }
$strforums = get_string('modulenameplural', 'forum'); $strforums = get_string('modulenameplural', 'forum');

View file

@ -18,20 +18,24 @@
} }
if ($cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) { if ($cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
if (groupmode($course, $cm) and !isteacheredit($course->id)) { // Make sure user is allowed
if (! mygroupid($course->id)) { $context = get_context_instance(CONTEXT_MODULE, $cm->id);
error("Sorry, but you must be a group member to subscribe."); if (groupmode($course, $cm) and
!has_capability('mod/forum:viewdiscussionsfromallgroups', $context->id)) {
if (!mygroupid($course->id)) {
error('Sorry, but you must be a group member to subscribe.');
} }
} }
} else { } else {
$cm->id = 0; $cm->id = 0;
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
} }
if ($user) { if ($user) {
if (!isteacher($course->id)) { if (!has_capability('mod/forum:managesubscriptions', $context->id)) {
error("Only teachers can subscribe/unsubscribe other people!"); error('You do not have the permission to subscribe/unsubscribe other people!');
} }
if (! $user = get_record("user", "id", $user)) { if (!$user = get_record("user", "id", $user)) {
error("User ID was incorrect"); error("User ID was incorrect");
} }
} else { } else {
@ -43,7 +47,7 @@
if (isguest()) { // Guests can't subscribe if (isguest()) { // Guests can't subscribe
$wwwroot = $CFG->wwwroot.'/login/index.php'; $wwwroot = $CFG->wwwroot.'/login/index.php';
if (!empty($CFG->loginhttps)) { if (!empty($CFG->loginhttps)) {
$wwwroot = str_replace('http:','https:', $wwwroot); $wwwroot = str_replace('http','https', $wwwroot);
} }
$strforums = get_string('modulenameplural', 'forum'); $strforums = get_string('modulenameplural', 'forum');
@ -63,15 +67,9 @@
exit; exit;
} }
if ($forum->type == "teacher") {
if (!isteacher($course->id)) {
error("You must be a $course->teacher to subscribe to this forum");
}
}
$returnto = forum_go_back_to("index.php?id=$course->id"); $returnto = forum_go_back_to("index.php?id=$course->id");
if ($force and isteacher($course->id)) { if ($force and has_capability('mod/forum:managesubscriptions', $context->id)) {
if (forum_is_forcesubscribed($forum->id)) { if (forum_is_forcesubscribed($forum->id)) {
forum_forcesubscribe($forum->id, 0); forum_forcesubscribe($forum->id, 0);
redirect($returnto, get_string("everyonecanchoose", "forum"), 1); redirect($returnto, get_string("everyonecanchoose", "forum"), 1);
@ -97,7 +95,8 @@
} }
} else { // subscribe } else { // subscribe
if ($forum->forcesubscribe == FORUM_DISALLOWSUBSCRIBE && !isteacher($forum->course)) { if ($forum->forcesubscribe == FORUM_DISALLOWSUBSCRIBE &&
!has_capability('mod/forum:managesubscriptions', $context->id)) {
error(get_string('disallowsubscribe'),$_SERVER["HTTP_REFERER"]); error(get_string('disallowsubscribe'),$_SERVER["HTTP_REFERER"]);
} }
if (forum_subscribe($user->id, $forum->id) ) { if (forum_subscribe($user->id, $forum->id) ) {

View file

@ -21,18 +21,16 @@
require_login($course->id, false, $cm); require_login($course->id, false, $cm);
if (!isteacher($course->id)) { $context = get_context_instance(CONTEXT_MODULE, $cm->id);
error("This page is for teachers only");
if (!has_capability('mod/forum:viewsubscribers', $context->id)) {
error('You do not have the permission to view forum subscribers');
} }
unset($SESSION->fromdiscussion); unset($SESSION->fromdiscussion);
add_to_log($course->id, "forum", "view subscribers", "subscribers.php?id=$forum->id", $forum->id, $cm->id); add_to_log($course->id, "forum", "view subscribers", "subscribers.php?id=$forum->id", $forum->id, $cm->id);
if ($edit != -1) {
$USER->subscriptionsediting = $edit;
}
$strsubscribeall = get_string("subscribeall", "forum"); $strsubscribeall = get_string("subscribeall", "forum");
$strsubscribenone = get_string("subscribenone", "forum"); $strsubscribenone = get_string("subscribenone", "forum");
$strsubscribers = get_string("subscribers", "forum"); $strsubscribers = get_string("subscribers", "forum");
@ -41,8 +39,16 @@
$navigation = "<a href=\"index.php?id=$course->id\">$strforums</a> -> $navigation = "<a href=\"index.php?id=$course->id\">$strforums</a> ->
<a href=\"view.php?f=$forum->id\">".format_string($forum->name,true)."</a> -> $strsubscribers"; <a href=\"view.php?f=$forum->id\">".format_string($forum->name,true)."</a> -> $strsubscribers";
print_header_simple("$strsubscribers", "", "$navigation", if (has_capability('mod/forum:managesubscriptions', $context->id)) {
"", "", true, forum_update_subscriptions_button($course->id, $id)); print_header_simple("$strsubscribers", "", "$navigation",
"", "", true, forum_update_subscriptions_button($course->id, $id));
if ($edit != -1) {
$USER->subscriptionsediting = $edit;
}
} else {
print_header_simple("$strsubscribers", "", "$navigation", "", "", true, '');
unset($USER->subscriptionsediting);
}
/// Check to see if groups are being used in this forum /// Check to see if groups are being used in this forum
if ($groupmode = groupmode($course, $cm)) { // Groups are being used if ($groupmode = groupmode($course, $cm)) { // Groups are being used

View file

@ -27,7 +27,7 @@
require_course_login($course); require_course_login($course);
add_to_log($course->id, "forum", "user report", "user.php?course=$course->id&amp;id=$user->id&amp;mode=$mode", "$user->id"); add_to_log($course->id, "forum", "user report", "user.php?id=$course->id&amp;user=$user->id&amp;mode=$mode", "$user->id");
$strforumposts = get_string('forumposts', 'forum'); $strforumposts = get_string('forumposts', 'forum');
$strparticipants = get_string('participants'); $strparticipants = get_string('participants');
@ -49,11 +49,18 @@
$currenttab = $mode; $currenttab = $mode;
include($CFG->dirroot.'/user/tabs.php'); /// Prints out tabs as part of user page include($CFG->dirroot.'/user/tabs.php'); /// Prints out tabs as part of user page
if ((!isteacheredit($course->id)) and forum_get_separate_modules($course->id)) { $isseparategroups = /*(($course->groupmode == SEPARATEGROUPS and
$sepgroups = user_group($course->id, $USER->id); $course->groupmodeforce and
} else { !isteacheredit($course->id))*/forum_get_separate_modules($course->id);
$sepgroups = false;
/*
//editting teacher can view everything so do not pass in groupid
if (isteacheredit ($course->id)){
$isseparategroups = false;
} }
*/
$groupid = $isseparategroups ? /*get_current_group*/mygroupid($course->id) : NULL;
switch ($mode) { switch ($mode) {
case 'posts' : case 'posts' :
@ -68,8 +75,10 @@
} }
echo '<div class="user-content">'; echo '<div class="user-content">';
// Get the posts regardless of group first.
if ($posts = forum_search_posts($searchterms, $course->id, $page*$perpage, $perpage, if ($posts = forum_search_posts($searchterms, $course->id, $page*$perpage, $perpage,
$totalcount, $sepgroups, $extrasql)) { $totalcount, $groupid, $extrasql)) {
print_paging_bar($totalcount, $page, $perpage, print_paging_bar($totalcount, $page, $perpage,
"user.php?id=$user->id&amp;course=$course->id&amp;mode=$mode&amp;perpage=$perpage&amp;"); "user.php?id=$user->id&amp;course=$course->id&amp;mode=$mode&amp;perpage=$perpage&amp;");
foreach ($posts as $post) { foreach ($posts as $post) {
@ -89,7 +98,8 @@
} }
} }
if (isadmin() && $course->id == SITEID) { $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
if ($course->id == SITEID && has_capability('moodle/site:config', $context->id)) {
$postcoursename = get_field('course', 'shortname', 'id', $forum->course); $postcoursename = get_field('course', 'shortname', 'id', $forum->course);
$fullsubject = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$forum->course.'">'.$postcoursename.'</a> -> '. $fullsubject; $fullsubject = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$forum->course.'">'.$postcoursename.'</a> -> '. $fullsubject;
} }

View file

@ -5,7 +5,7 @@
// This fragment is called by /admin/index.php // This fragment is called by /admin/index.php
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
$module->version = 2006011702; $module->version = 2006080800;
$module->requires = 2005031000; // Requires this Moodle version $module->requires = 2005031000; // Requires this Moodle version
$module->cron = 60; $module->cron = 60;

View file

@ -60,12 +60,15 @@
$navigation = "<a href=\"index.php?id=$course->id\">$strforums</a> ->"; $navigation = "<a href=\"index.php?id=$course->id\">$strforums</a> ->";
if ($forum->type == "teacher") {
if (!isteacher($course->id)) { /// Check whether the should be able to view this forum.
error("You must be a $course->teacher to view this forum"); $context = get_context_instance(CONTEXT_MODULE, $cm->id);
}
if (!has_capability('mod/forum:viewforum', $context->id)) {
error('You do not have the permission to view this forum');
} }
if ($cm->id) { if ($cm->id) {
add_to_log($course->id, "forum", "view forum", "view.php?id=$cm->id", "$forum->id", $cm->id); add_to_log($course->id, "forum", "view forum", "view.php?id=$cm->id", "$forum->id", $cm->id);
} else { } else {
@ -75,7 +78,7 @@
print_header_simple(format_string($forum->name), "", print_header_simple(format_string($forum->name), "",
"$navigation ".format_string($forum->name), "", "", true, $buttontext, navmenu($course, $cm)); "$navigation ".format_string($forum->name), "", "", true, $buttontext, navmenu($course, $cm));
if (empty($cm->visible) and !isteacher($course->id)) { if (empty($cm->visible) and !has_capability('moodle/course:manageactivities', $context->id)) {
notice(get_string("activityiscurrentlyhidden")); notice(get_string("activityiscurrentlyhidden"));
} }
@ -91,7 +94,9 @@
$currentgroup = get_and_set_current_group($course, $groupmode, $changegroup); $currentgroup = get_and_set_current_group($course, $groupmode, $changegroup);
if ($groupmode and ($currentgroup === false) and !isteacheredit($course->id)) { if ($groupmode and ($currentgroup === false) and
!has_capability('mod/forum:viewdiscussionsfromallgroups', $context->id)) {
print_heading(get_string("notingroup", "forum")); print_heading(get_string("notingroup", "forum"));
print_footer($course); print_footer($course);
exit; exit;
@ -108,7 +113,9 @@
///menu for students in forums. ///menu for students in forums.
//now we need a menu for separategroups as well! //now we need a menu for separategroups as well!
if ($groupmode == VISIBLEGROUPS or ($groupmode and isteacheredit($course->id))) { if ($groupmode == VISIBLEGROUPS or ($groupmode and
has_capability('module:forum:viewdiscussionsfromallgroups', $context->id))) {
//the following query really needs to change //the following query really needs to change
if ($groups = get_records_menu("groups", "courseid", $course->id, "name ASC", "id,name")) { if ($groups = get_records_menu("groups", "courseid", $course->id, "name ASC", "id,name")) {
echo '<td>'; echo '<td>';
@ -143,7 +150,7 @@
$strallowchoice = get_string('allowchoice', 'forum'); $strallowchoice = get_string('allowchoice', 'forum');
helpbutton("subscription", $streveryoneissubscribed, "forum"); helpbutton("subscription", $streveryoneissubscribed, "forum");
echo '&nbsp;<span class="helplink">'; echo '&nbsp;<span class="helplink">';
if (isteacher($course->id)) { if (has_capability('moodle/course:manageactivities', $context->id)) {
echo "<a title=\"$strallowchoice\" href=\"subscribe.php?id=$forum->id&amp;force=no\">$streveryoneissubscribed</a>"; echo "<a title=\"$strallowchoice\" href=\"subscribe.php?id=$forum->id&amp;force=no\">$streveryoneissubscribed</a>";
} else { } else {
echo $streveryoneissubscribed; echo $streveryoneissubscribed;
@ -161,7 +168,7 @@
helpbutton("subscription", $streveryonecanchoose, "forum"); helpbutton("subscription", $streveryonecanchoose, "forum");
echo '&nbsp;'; echo '&nbsp;';
if (isteacher($course->id)) { if (has_capability('moodle/course:manageactivities', $context->id)) {
echo "<span class=\"helplink\"><a title=\"$strforcesubscribe\" href=\"subscribe.php?id=$forum->id&amp;force=yes\">$streveryonecanchoose</a></span>"; echo "<span class=\"helplink\"><a title=\"$strforcesubscribe\" href=\"subscribe.php?id=$forum->id&amp;force=yes\">$streveryonecanchoose</a></span>";
echo "<br />"; echo "<br />";
echo "<span class=\"helplink\"><a href=\"subscribers.php?id=$forum->id\">$strshowsubscribers</a></span>"; echo "<span class=\"helplink\"><a href=\"subscribers.php?id=$forum->id\">$strshowsubscribers</a></span>";
@ -223,7 +230,7 @@
notify(get_string('thisforumisthrottled','forum',$a)); notify(get_string('thisforumisthrottled','forum',$a));
} }
if ($forum->type == 'qanda' && !isteacher($forum->course)) { if ($forum->type == 'qanda' && !has_capability('moodle/course:manageactivities', $context->id)) {
notify(get_string('qandanotify','forum')); notify(get_string('qandanotify','forum'));
} }
@ -246,7 +253,8 @@
set_user_preference("forum_displaymode", $mode); set_user_preference("forum_displaymode", $mode);
} }
$displaymode = get_user_preferences("forum_displaymode", $CFG->forum_displaymode); $displaymode = get_user_preferences("forum_displaymode", $CFG->forum_displaymode);
forum_print_discussion($course, $forum, $discussion, $post, $displaymode); $canrate = has_capability('mod/forum:rate', $context->id);
forum_print_discussion($course, $forum, $discussion, $post, $displaymode, NULL, $canrate);
break; break;
case 'eachuser': case 'eachuser':

View file

@ -22,9 +22,10 @@
} }
require_login($course->id, false, $cm); require_login($course->id, false, $cm);
if (!isteacher($course->id)) {
error("You must be a teacher to use this page."); $context = get_context_instance(CONTEXT_MODULE, $cm->id);
} has_capability('mod/glossary:approve', $context->id, true);
$newentry->id = $eid; $newentry->id = $eid;
$newentry->approved = 1; $newentry->approved = 1;

View file

@ -38,7 +38,9 @@
require_login($course->id, false, $cm); require_login($course->id, false, $cm);
if (isguest()) { $context = get_context_instance(CONTEXT_MODULE, $cm->id);
if (isguest()) {
error('Guests are not allowed to post comments', $_SERVER['HTTP_REFERER']); error('Guests are not allowed to post comments', $_SERVER['HTTP_REFERER']);
} }
add_to_log($course->id, 'glossary', 'view', "view.php?id=$cm->id", "$glossary->id",$cm->id); add_to_log($course->id, 'glossary', 'view', "view.php?id=$cm->id", "$glossary->id",$cm->id);
@ -72,10 +74,10 @@
/// Input section /// Input section
if ( $action == 'delete' ) { if ( $action == 'delete' ) {
if (($comment->userid <> $USER->id) and !isteacher($glossary->course)) { if (($comment->userid <> $USER->id) and !has_capability('mod/glossary:managecomments', $context->id)) {
error('You can\'t delete other people\'s comments!'); error('You can\'t delete other people\'s comments!');
} }
if (!$glossary->allowcomments && !isteacher($glossary->course)) { if (!$glossary->allowcomments && !has_capability('mod/glossary:managecomments', $context->id)) {
error('You can\'t delete comments in this glossary!'); error('You can\'t delete comments in this glossary!');
} }
if ( $confirm ) { if ( $confirm ) {
@ -111,7 +113,7 @@
print_simple_box_end(); print_simple_box_end();
} }
} else { } else {
if (!$glossary->allowcomments && !isteacher($glossary->course)) { if (!$glossary->allowcomments && !has_capability('mod/glossary:comment', $context->id)) {
error('You can\'t add/edit comments to this glossary!'); error('You can\'t add/edit comments to this glossary!');
} }
if ( $action == 'edit' ) { if ( $action == 'edit' ) {
@ -121,7 +123,7 @@
$timetocheck = $comment->timemodified; $timetocheck = $comment->timemodified;
} }
$ineditperiod = ((time() - $timetocheck < $CFG->maxeditingtime) || $glossary->editalways); $ineditperiod = ((time() - $timetocheck < $CFG->maxeditingtime) || $glossary->editalways);
if ( (!$ineditperiod || $USER->id != $comment->userid) and !isteacher($course->id) and $cid) { if ( (!$ineditperiod || $USER->id != $comment->userid) and !has_capability('mod/glossary:comment', $context->id) and $cid) {
if ( $USER->id != $comment->userid ) { if ( $USER->id != $comment->userid ) {
error('You can\'t edit other people\'s comments!'); error('You can\'t edit other people\'s comments!');
} elseif (!$ineditperiod) { } elseif (!$ineditperiod) {

View file

@ -25,6 +25,7 @@
error("Entry is incorrect"); error("Entry is incorrect");
} }
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
require_login($course->id, false, $cm); require_login($course->id, false, $cm);
@ -56,7 +57,7 @@
print_heading(format_string(get_string('commentson','glossary')." <b>\"$entry->concept\"</b>")); print_heading(format_string(get_string('commentson','glossary')." <b>\"$entry->concept\"</b>"));
if ($glossary->allowcomments || isteacher($glossary->course)) { if ($glossary->allowcomments || has_capability('mod/glossary:managecomments', $context->id)) {
print_heading("<a href=\"comment.php?id=$cm->id&amp;eid=$entry->id\">$straddcomment</a> <img title=\"$straddcomment\" src=\"comment.gif\" height=\"11\" width=\"11\" border=\"0\" alt=\"\" />"); print_heading("<a href=\"comment.php?id=$cm->id&amp;eid=$entry->id\">$straddcomment</a> <img title=\"$straddcomment\" src=\"comment.gif\" height=\"11\" width=\"11\" border=\"0\" alt=\"\" />");
} }

Some files were not shown because too many files have changed in this diff Show more