Файловый менеджер - Редактировать - /home/harasnat/www/mf/locallib.php.tar
Назад
home/harasnat/www/learning/blog/locallib.php 0000604 00000117444 15062104360 0015141 0 ustar 00 <?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Classes for Blogs. * * @package moodlecore * @subpackage blog * @copyright 2009 Nicolas Connault * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); require_once($CFG->libdir . '/filelib.php'); /** * Blog_entry class. Represents an entry in a user's blog. Contains all methods for managing this entry. * This class does not contain any HTML-generating code. See blog_listing sub-classes for such code. * This class follows the Object Relational Mapping technique, its member variables being mapped to * the fields of the post table. * * @package moodlecore * @subpackage blog * @copyright 2009 Nicolas Connault * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class blog_entry implements renderable { // Public Database fields. public $id; public $userid; public $subject; public $summary; public $rating = 0; public $attachment; public $publishstate; // Locked Database fields (Don't touch these). public $courseid = 0; public $groupid = 0; public $module = 'blog'; public $moduleid = 0; public $coursemoduleid = 0; public $content; public $format = 1; public $uniquehash = ''; public $lastmodified; public $created; public $usermodified; // Other class variables. public $form; public $tags = array(); /** @var StdClass Data needed to render the entry */ public $renderable; /** @var string summary format. */ public string $summaryformat; /** @var array summary editor. */ public array $summary_editor; /** @var string */ public $summarytrust; /** @var int course associated with the blog post. */ public $courseassoc; /** @var string module associated with the blog post. */ public $modassoc; /** @var mixed attachment. */ public $attachment_filemanager; /** @var string blog post body. */ public $body; /** @var int attachment entry id. */ public $entryid; /** @var string|null submit button. */ public $submitbutton; /** @var string|null user alias. */ public $useridalias; /** @var string|null user picture. */ public $picture; /** @var string|null user first name. */ public $firstname; /** @var string|null user middle name. */ public $middlename; /** @var string|null user last name. */ public $lastname; /** @var string|null user first name phonetic. */ public $firstnamephonetic; /** @var string|null user last name phonetic. */ public $lastnamephonetic; /** @var string|null user alternate name. */ public $alternatename; /** @var string|null user email address. */ public $email; /** @var string */ public $action; /** @var string|null user picture description. */ public $imagealt; /** @var int module instance id. */ public $modid; /** * Constructor. If given an id, will fetch the corresponding record from the DB. * * @param mixed $idorparams A blog entry id if INT, or data for a new entry if array */ public function __construct($id=null, $params=null, $form=null) { global $DB, $PAGE, $CFG; if (!empty($id)) { $object = $DB->get_record('post', array('id' => $id)); foreach ($object as $var => $val) { $this->$var = $val; } } else if (!empty($params) && (is_array($params) || is_object($params))) { foreach ($params as $var => $val) { $this->$var = $val; } } if (!empty($CFG->useblogassociations)) { $associations = $DB->get_records('blog_association', array('blogid' => $this->id)); foreach ($associations as $association) { $context = context::instance_by_id($association->contextid); if ($context->contextlevel == CONTEXT_COURSE) { $this->courseassoc = $association->contextid; } else if ($context->contextlevel == CONTEXT_MODULE) { $this->modassoc = $association->contextid; } } } $this->form = $form; } /** * Gets the required data to print the entry */ public function prepare_render() { global $DB, $CFG, $PAGE; $this->renderable = new StdClass(); $this->renderable->user = $DB->get_record('user', array('id' => $this->userid)); // Entry comments. if (!empty($CFG->usecomments) and $CFG->blogusecomments) { require_once($CFG->dirroot . '/comment/lib.php'); $cmt = new stdClass(); $cmt->context = context_user::instance($this->userid); $cmt->courseid = $PAGE->course->id; $cmt->area = 'format_blog'; $cmt->itemid = $this->id; $cmt->showcount = $CFG->blogshowcommentscount; $cmt->component = 'blog'; $this->renderable->comment = new comment($cmt); } $this->summary = file_rewrite_pluginfile_urls($this->summary, 'pluginfile.php', SYSCONTEXTID, 'blog', 'post', $this->id); // External blog link. if ($this->uniquehash && $this->content) { if ($externalblog = $DB->get_record('blog_external', array('id' => $this->content))) { $urlparts = parse_url($externalblog->url); $this->renderable->externalblogtext = get_string('retrievedfrom', 'blog') . get_string('labelsep', 'langconfig'); $this->renderable->externalblogtext .= html_writer::link($urlparts['scheme'] . '://' . $urlparts['host'], $externalblog->name); } } // Retrieve associations. $this->renderable->unassociatedentry = false; if (!empty($CFG->useblogassociations)) { // Adding the entry associations data. if ($associations = $associations = $DB->get_records('blog_association', array('blogid' => $this->id))) { // Check to see if the entry is unassociated with group/course level access. if ($this->publishstate == 'group' || $this->publishstate == 'course') { $this->renderable->unassociatedentry = true; } foreach ($associations as $key => $assocrec) { if (!$context = context::instance_by_id($assocrec->contextid, IGNORE_MISSING)) { unset($associations[$key]); continue; } // The renderer will need the contextlevel of the association. $associations[$key]->contextlevel = $context->contextlevel; // Course associations. if ($context->contextlevel == CONTEXT_COURSE) { // TODO: performance!!!! $instancename = $DB->get_field('course', 'shortname', array('id' => $context->instanceid)); $associations[$key]->url = $assocurl = new moodle_url('/course/view.php', array('id' => $context->instanceid)); $associations[$key]->text = $instancename; $associations[$key]->icon = new pix_icon('i/course', $associations[$key]->text); } // Mod associations. if ($context->contextlevel == CONTEXT_MODULE) { // Getting the activity type and the activity instance id. $sql = 'SELECT cm.instance, m.name FROM {course_modules} cm JOIN {modules} m ON m.id = cm.module WHERE cm.id = :cmid'; $modinfo = $DB->get_record_sql($sql, array('cmid' => $context->instanceid)); // TODO: performance!!!! $instancename = $DB->get_field($modinfo->name, 'name', array('id' => $modinfo->instance)); $associations[$key]->type = get_string('modulename', $modinfo->name); $associations[$key]->url = new moodle_url('/mod/' . $modinfo->name . '/view.php', array('id' => $context->instanceid)); $associations[$key]->text = $instancename; $associations[$key]->icon = new pix_icon('icon', $associations[$key]->text, $modinfo->name); } } } $this->renderable->blogassociations = $associations; } // Entry attachments. $this->renderable->attachments = $this->get_attachments(); $this->renderable->usercanedit = blog_user_can_edit_entry($this); } /** * Gets the entry attachments list * @return array List of blog_entry_attachment instances */ public function get_attachments() { global $CFG; require_once($CFG->libdir.'/filelib.php'); $syscontext = context_system::instance(); $fs = get_file_storage(); $files = $fs->get_area_files($syscontext->id, 'blog', 'attachment', $this->id); // Adding a blog_entry_attachment for each non-directory file. $attachments = array(); foreach ($files as $file) { if ($file->is_directory()) { continue; } $attachments[] = new blog_entry_attachment($file, $this->id); } return $attachments; } /** * Inserts this entry in the database. Access control checks must be done by calling code. * * @param mform $form Used for attachments * @return void */ public function process_attachment($form) { $this->form = $form; } /** * Inserts this entry in the database. Access control checks must be done by calling code. * TODO Set the publishstate correctly * @return void */ public function add() { global $CFG, $USER, $DB; unset($this->id); $this->module = 'blog'; $this->userid = (empty($this->userid)) ? $USER->id : $this->userid; $this->lastmodified = time(); $this->created = time(); // Insert the new blog entry. $this->id = $DB->insert_record('post', $this); if (!empty($CFG->useblogassociations)) { $this->add_associations(); } core_tag_tag::set_item_tags('core', 'post', $this->id, context_user::instance($this->userid), $this->tags); // Trigger an event for the new entry. $event = \core\event\blog_entry_created::create(array( 'objectid' => $this->id, 'relateduserid' => $this->userid )); $event->set_blog_entry($this); $event->trigger(); } /** * Updates this entry in the database. Access control checks must be done by calling code. * * @param array $params Entry parameters. * @param moodleform $form Used for attachments. * @param array $summaryoptions Summary options. * @param array $attachmentoptions Attachment options. * * @return void */ public function edit($params=array(), $form=null, $summaryoptions=array(), $attachmentoptions=array()) { global $CFG, $DB; $sitecontext = context_system::instance(); $entry = $this; $this->form = $form; foreach ($params as $var => $val) { $entry->$var = $val; } $entry = file_postupdate_standard_editor($entry, 'summary', $summaryoptions, $sitecontext, 'blog', 'post', $entry->id); $entry = file_postupdate_standard_filemanager($entry, 'attachment', $attachmentoptions, $sitecontext, 'blog', 'attachment', $entry->id); if (!empty($CFG->useblogassociations)) { $entry->add_associations(); } $entry->lastmodified = time(); // Update record. $DB->update_record('post', $entry); core_tag_tag::set_item_tags('core', 'post', $entry->id, context_user::instance($this->userid), $entry->tags); $event = \core\event\blog_entry_updated::create(array( 'objectid' => $entry->id, 'relateduserid' => $entry->userid )); $event->set_blog_entry($entry); $event->trigger(); } /** * Deletes this entry from the database. Access control checks must be done by calling code. * * @return void */ public function delete() { global $DB; $this->delete_attachments(); $this->remove_associations(); // Get record to pass onto the event. $record = $DB->get_record('post', array('id' => $this->id)); $DB->delete_records('post', array('id' => $this->id)); core_tag_tag::remove_all_item_tags('core', 'post', $this->id); $event = \core\event\blog_entry_deleted::create(array( 'objectid' => $this->id, 'relateduserid' => $this->userid )); $event->add_record_snapshot("post", $record); $event->set_blog_entry($this); $event->trigger(); } /** * Function to add all context associations to an entry. * * @param string $unused This does nothing, do not use it. */ public function add_associations($unused = null) { if ($unused !== null) { debugging('Illegal argument used in blog_entry->add_associations()', DEBUG_DEVELOPER); } $this->remove_associations(); if (!empty($this->courseassoc)) { $this->add_association($this->courseassoc); } if (!empty($this->modassoc)) { $this->add_association($this->modassoc); } } /** * Add a single association for a blog entry * * @param int $contextid - id of context to associate with the blog entry. * @param string $unused This does nothing, do not use it. */ public function add_association($contextid, $unused = null) { global $DB; if ($unused !== null) { debugging('Illegal argument used in blog_entry->add_association()', DEBUG_DEVELOPER); } $assocobject = new StdClass; $assocobject->contextid = $contextid; $assocobject->blogid = $this->id; $id = $DB->insert_record('blog_association', $assocobject); // Trigger an association created event. $context = context::instance_by_id($contextid); $eventparam = array( 'objectid' => $id, 'other' => array('associateid' => $context->instanceid, 'subject' => $this->subject, 'blogid' => $this->id), 'relateduserid' => $this->userid ); if ($context->contextlevel == CONTEXT_COURSE) { $eventparam['other']['associatetype'] = 'course'; } else if ($context->contextlevel == CONTEXT_MODULE) { $eventparam['other']['associatetype'] = 'coursemodule'; } $event = \core\event\blog_association_created::create($eventparam); $event->trigger(); } /** * remove all associations for a blog entry * * @return void */ public function remove_associations() { global $DB; $associations = $DB->get_records('blog_association', array('blogid' => $this->id)); foreach ($associations as $association) { // Trigger an association deleted event. $context = context::instance_by_id($association->contextid); $eventparam = array( 'objectid' => $this->id, 'other' => array('subject' => $this->subject, 'blogid' => $this->id), 'relateduserid' => $this->userid ); $event = \core\event\blog_association_deleted::create($eventparam); $event->add_record_snapshot('blog_association', $association); $event->trigger(); // Now remove the association. $DB->delete_records('blog_association', array('id' => $association->id)); } } /** * Deletes all the user files in the attachments area for an entry * * @return void */ public function delete_attachments() { $fs = get_file_storage(); $fs->delete_area_files(SYSCONTEXTID, 'blog', 'attachment', $this->id); $fs->delete_area_files(SYSCONTEXTID, 'blog', 'post', $this->id); } /** * User can edit a blog entry if this is their own blog entry and they have * the capability moodle/blog:create, or if they have the capability * moodle/blog:manageentries. * This also applies to deleting of entries. * * @param int $userid Optional. If not given, $USER is used * @return boolean */ public function can_user_edit($userid=null) { global $CFG, $USER; if (empty($userid)) { $userid = $USER->id; } $sitecontext = context_system::instance(); if (has_capability('moodle/blog:manageentries', $sitecontext)) { return true; // Can edit any blog entry. } if ($this->userid == $userid && has_capability('moodle/blog:create', $sitecontext)) { return true; // Can edit own when having blog:create capability. } return false; } /** * Checks to see if a user can view the blogs of another user. * Only blog level is checked here, the capabilities are enforced * in blog/index.php * * @param int $targetuserid ID of the user we are checking * * @return bool */ public function can_user_view($targetuserid) { global $CFG, $USER, $DB; $sitecontext = context_system::instance(); if (empty($CFG->enableblogs) || !has_capability('moodle/blog:view', $sitecontext)) { return false; // Blog system disabled or user has no blog view capability. } if (isloggedin() && $USER->id == $targetuserid) { return true; // Can view own entries in any case. } if (has_capability('moodle/blog:manageentries', $sitecontext)) { return true; // Can manage all entries. } // Coming for 1 entry, make sure it's not a draft. if ($this->publishstate == 'draft' && !has_capability('moodle/blog:viewdrafts', $sitecontext)) { return false; // Can not view draft of others. } // Coming for 1 entry, make sure user is logged in, if not a public blog. if ($this->publishstate != 'public' && !isloggedin()) { return false; } switch ($CFG->bloglevel) { case BLOG_GLOBAL_LEVEL: return true; break; case BLOG_SITE_LEVEL: if (isloggedin()) { // Not logged in viewers forbidden. return true; } return false; break; case BLOG_USER_LEVEL: default: $personalcontext = context_user::instance($targetuserid); return has_capability('moodle/user:readuserblogs', $personalcontext); break; } } /** * Use this function to retrieve a list of publish states available for * the currently logged in user. * * @return array This function returns an array ideal for sending to moodles' * choose_from_menu function. */ public static function get_applicable_publish_states() { global $CFG; $options = array(); // Everyone gets draft access. if ($CFG->bloglevel >= BLOG_USER_LEVEL) { $options['draft'] = get_string('publishtonoone', 'blog'); } if ($CFG->bloglevel > BLOG_USER_LEVEL) { $options['site'] = get_string('publishtosite', 'blog'); } if ($CFG->bloglevel >= BLOG_GLOBAL_LEVEL) { $options['public'] = get_string('publishtoworld', 'blog'); } return $options; } } /** * Abstract Blog_Listing class: used to gather blog entries and output them as listings. One of the subclasses must be used. * * @package moodlecore * @subpackage blog * @copyright 2009 Nicolas Connault * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class blog_listing { /** * Array of blog_entry objects. * @var array $entries */ public $entries = null; /** * Caches the total number of the entries. * @var int */ public $totalentries = null; /** * An array of blog_filter_* objects * @var array $filters */ public $filters = array(); /** * Constructor * * @param array $filters An associative array of filtername => filterid */ public function __construct($filters=array()) { // Unset filters overridden by more specific filters. foreach ($filters as $type => $id) { if (!empty($type) && !empty($id)) { $this->filters[$type] = blog_filter::get_instance($id, $type); } } foreach ($this->filters as $type => $filter) { foreach ($filter->overrides as $override) { if (array_key_exists($override, $this->filters)) { unset($this->filters[$override]); } } } } /** * Fetches the array of blog entries. * * @return array */ public function get_entries($start=0, $limit=10) { global $DB; if ($this->entries === null) { if ($sqlarray = $this->get_entry_fetch_sql(false, 'created DESC')) { $this->entries = $DB->get_records_sql($sqlarray['sql'], $sqlarray['params'], $start, $limit); if (!$start && count($this->entries) < $limit) { $this->totalentries = count($this->entries); } } else { return false; } } return $this->entries; } /** * Finds total number of blog entries * * @return int */ public function count_entries() { global $DB; if ($this->totalentries === null) { if ($sqlarray = $this->get_entry_fetch_sql(true)) { $this->totalentries = $DB->count_records_sql($sqlarray['sql'], $sqlarray['params']); } else { $this->totalentries = 0; } } return $this->totalentries; } public function get_entry_fetch_sql($count=false, $sort='lastmodified DESC', $userid = false) { global $DB, $USER, $CFG; if (!$userid) { $userid = $USER->id; } $userfieldsapi = \core_user\fields::for_userpic(); $allnamefields = $userfieldsapi->get_sql('u', false, '', 'useridalias', false)->selects; // The query used to locate blog entries is complicated. It will be built from the following components: $requiredfields = "p.*, $allnamefields"; // The SELECT clause. $tables = array('p' => 'post', 'u' => 'user'); // Components of the FROM clause (table_id => table_name). // Components of the WHERE clause (conjunction). $conditions = array('u.deleted = 0', 'p.userid = u.id', '(p.module = \'blog\' OR p.module = \'blog_external\')'); // Build up a clause for permission constraints. $params = array(); // Fix for MDL-9165, use with readuserblogs capability in a user context can read that user's private blogs. // Admins can see all blogs regardless of publish states, as described on the help page. if (has_capability('moodle/user:readuserblogs', context_system::instance())) { // Don't add permission constraints. } else if (!empty($this->filters['user']) && has_capability('moodle/user:readuserblogs', context_user::instance((empty($this->filters['user']->id) ? 0 : $this->filters['user']->id)))) { // Don't add permission constraints. } else { if (isloggedin() and !isguestuser()) { // Dont check association records if there aren't any. $assocexists = $DB->record_exists('blog_association', array()); // Begin permission sql clause. $permissionsql = '(p.userid = ? '; $params[] = $userid; if ($CFG->bloglevel >= BLOG_SITE_LEVEL) { // Add permission to view site-level entries. $permissionsql .= " OR p.publishstate = 'site' "; } if ($CFG->bloglevel >= BLOG_GLOBAL_LEVEL) { // Add permission to view global entries. $permissionsql .= " OR p.publishstate = 'public' "; } $permissionsql .= ') '; // Close permissions sql clause. } else { // Default is access to public entries. $permissionsql = "p.publishstate = 'public'"; } $conditions[] = $permissionsql; // Add permission constraints. } foreach ($this->filters as $type => $blogfilter) { $conditions = array_merge($conditions, $blogfilter->conditions); $params = array_merge($params, $blogfilter->params); $tables = array_merge($tables, $blogfilter->tables); } $tablessql = ''; // Build up the FROM clause. foreach ($tables as $tablename => $table) { $tablessql .= ($tablessql ? ', ' : '').'{'.$table.'} '.$tablename; } $sql = ($count) ? 'SELECT COUNT(*)' : 'SELECT ' . $requiredfields; $sql .= " FROM $tablessql WHERE " . implode(' AND ', $conditions); $sql .= ($count) ? '' : " ORDER BY $sort"; return array('sql' => $sql, 'params' => $params); } /** * Outputs all the blog entries aggregated by this blog listing. * * @return void */ public function print_entries() { global $CFG, $USER, $DB, $OUTPUT, $PAGE; $sitecontext = context_system::instance(); // Blog renderer. $output = $PAGE->get_renderer('blog'); $page = optional_param('blogpage', 0, PARAM_INT); $limit = optional_param('limit', get_user_preferences('blogpagesize', 10), PARAM_INT); $start = $page * $limit; $morelink = '<br /> '; $entries = $this->get_entries($start, $limit); $totalentries = $this->count_entries(); $pagingbar = new paging_bar($totalentries, $page, $limit, $this->get_baseurl()); $pagingbar->pagevar = 'blogpage'; $blogheaders = blog_get_headers(); echo $OUTPUT->render($pagingbar); if (has_capability('moodle/blog:create', $sitecontext)) { // The user's blog is enabled and they are viewing their own blog. $userid = optional_param('userid', null, PARAM_INT); if (empty($userid) || (!empty($userid) && $userid == $USER->id)) { $courseid = optional_param('courseid', null, PARAM_INT); $modid = optional_param('modid', null, PARAM_INT); $addurl = new moodle_url("$CFG->wwwroot/blog/edit.php"); $urlparams = array('action' => 'add', 'userid' => $userid, 'courseid' => $courseid, 'groupid' => optional_param('groupid', null, PARAM_INT), 'modid' => $modid, 'tagid' => optional_param('tagid', null, PARAM_INT), 'tag' => optional_param('tag', null, PARAM_INT), 'search' => optional_param('search', null, PARAM_INT)); $urlparams = array_filter($urlparams); $addurl->params($urlparams); $addlink = '<div class="addbloglink">'; $addlink .= '<a href="'.$addurl->out().'">'. $blogheaders['stradd'].'</a>'; $addlink .= '</div>'; echo $addlink; } } if ($entries) { $count = 0; foreach ($entries as $entry) { $blogentry = new blog_entry(null, $entry); // Get the required blog entry data to render it. $blogentry->prepare_render(); echo $output->render($blogentry); $count++; } echo $OUTPUT->render($pagingbar); if (!$count) { print '<br /><div style="text-align:center">'. get_string('noentriesyet', 'blog') .'</div><br />'; } print $morelink.'<br />'."\n"; return; } } // Find the base url from $_GET variables, for print_paging_bar. public function get_baseurl() { $getcopy = $_GET; unset($getcopy['blogpage']); if (!empty($getcopy)) { $first = false; $querystring = ''; foreach ($getcopy as $var => $val) { if (!$first) { $first = true; $querystring .= "?$var=$val"; } else { $querystring .= '&'.$var.'='.$val; $hasparam = true; } } } else { $querystring = '?'; } return strip_querystring(qualified_me()) . $querystring; } } /** * Abstract class for blog_filter objects. * A set of core filters are implemented here. To write new filters, you need to subclass * blog_filter and give it the name of the type you want (for example, blog_filter_entry). * The blog_filter abstract class will automatically use it when the filter is added to the * URL. The first parameter of the constructor is the ID of your filter, but it can be a string * or have any other meaning you wish it to have. The second parameter is called $type and is * used as a sub-type for filters that have a very similar implementation (see blog_filter_context for an example) */ abstract class blog_filter { /** * An array of strings representing the available filter types for each blog_filter. * @var array $availabletypes */ public $availabletypes = array(); /** * The type of filter (for example, types of blog_filter_context are site, course and module) * @var string $type */ public $type; /** * The unique ID for a filter's associated record * @var int $id */ public $id; /** * An array of table aliases that are used in the WHERE conditions * @var array $tables */ public $tables = array(); /** * An array of WHERE conditions * @var array $conditions */ public $conditions = array(); /** * An array of SQL params * @var array $params */ public $params = array(); /** * An array of filter types which this particular filter type overrides: their conditions will not be evaluated */ public $overrides = array(); public function __construct($id, $type=null) { $this->id = $id; $this->type = $type; } /** * TODO This is poor design. A parent class should not know anything about its children. * The default case helps to resolve this design issue */ public static function get_instance($id, $type) { switch ($type) { case 'site': case 'course': case 'module': return new blog_filter_context($id, $type); break; case 'group': case 'user': return new blog_filter_user($id, $type); break; case 'tag': return new blog_filter_tag($id); break; default: $classname = "blog_filter_$type"; if (class_exists($classname)) { return new $classname($id, $type); } } } } /** * This filter defines the context level of the blog entries being searched: site, course, module */ class blog_filter_context extends blog_filter { /** * Constructor * * @param string $type * @param int $id */ public function __construct($id=null, $type='site') { global $SITE, $CFG, $DB; if (empty($id)) { $this->type = 'site'; } else { $this->id = $id; $this->type = $type; } $this->availabletypes = array('site' => get_string('site'), 'course' => get_string('course'), 'module' => get_string('activity'), 'context' => get_string('coresystem')); switch ($this->type) { case 'course': // Careful of site course! // Ignore course filter if blog associations are not enabled. if ($this->id != $SITE->id && !empty($CFG->useblogassociations)) { $this->overrides = array('site', 'context'); $context = context_course::instance($this->id); $this->tables['ba'] = 'blog_association'; $this->conditions[] = 'p.id = ba.blogid'; $this->conditions[] = 'ba.contextid = '.$context->id; break; } else { // We are dealing with the site course, do not break from the current case. } case 'site': // No special constraints. break; case 'module': if (!empty($CFG->useblogassociations)) { $this->overrides = array('course', 'site', 'context'); $context = context_module::instance($this->id); $this->tables['ba'] = 'blog_association'; $this->tables['p'] = 'post'; $this->conditions = array('p.id = ba.blogid', 'ba.contextid = ?'); $this->params = array($context->id); } break; case 'context': if ($id != context_system::instance()->id && !empty($CFG->useblogassociations)) { $this->overrides = array('site'); $context = context::instance_by_id($this->id); $this->tables['ba'] = 'blog_association'; $this->tables['ctx'] = 'context'; $this->conditions[] = 'p.id = ba.blogid'; $this->conditions[] = 'ctx.id = ba.contextid'; $this->conditions[] = 'ctx.path LIKE ?'; $this->params = array($context->path . '%'); } break; } } } /** * This filter defines the user level of the blog entries being searched: a userid or a groupid. * It can be combined with a context filter in order to refine the search. */ class blog_filter_user extends blog_filter { public $tables = array('u' => 'user'); /** * Constructor * * @param string $type * @param int $id */ public function __construct($id=null, $type='user') { global $CFG, $DB, $USER; $this->availabletypes = array('user' => get_string('user'), 'group' => get_string('group')); if (empty($id)) { $this->id = $USER->id; $this->type = 'user'; } else { $this->id = $id; $this->type = $type; } if ($this->type == 'user') { $this->conditions = array('u.id = ?'); $this->params = array($this->id); $this->overrides = array('group'); } else if ($this->type == 'group') { $this->overrides = array('course', 'site'); $this->tables['gm'] = 'groups_members'; $this->conditions[] = 'p.userid = gm.userid'; $this->conditions[] = 'gm.groupid = ?'; $this->params[] = $this->id; if (!empty($CFG->useblogassociations)) { // Only show blog entries associated with this course. $coursecontext = context_course::instance($DB->get_field('groups', 'courseid', array('id' => $this->id))); $this->tables['ba'] = 'blog_association'; $this->conditions[] = 'gm.groupid = ?'; $this->conditions[] = 'ba.contextid = ?'; $this->conditions[] = 'ba.blogid = p.id'; $this->params[] = $this->id; $this->params[] = $coursecontext->id; } } } } /** * This filter defines a tag by which blog entries should be searched. */ class blog_filter_tag extends blog_filter { public $tables = array('t' => 'tag', 'ti' => 'tag_instance', 'p' => 'post'); /** * Constructor * * @return void */ public function __construct($id) { global $DB; $this->id = $id; $this->conditions = array('ti.tagid = t.id', "ti.itemtype = 'post'", "ti.component = 'core'", 'ti.itemid = p.id', 't.id = ?'); $this->params = array($this->id); } } /** * This filter defines a specific blog entry id. */ class blog_filter_entry extends blog_filter { public $conditions = array('p.id = ?'); public $overrides = array('site', 'course', 'module', 'group', 'user', 'tag'); public function __construct($id) { $this->id = $id; $this->params[] = $this->id; } } /** * This filter restricts the results to a time interval in seconds up to time() */ class blog_filter_since extends blog_filter { public function __construct($interval) { $this->conditions[] = 'p.lastmodified >= ? AND p.lastmodified <= ?'; $this->params[] = time() - $interval; $this->params[] = time(); } } /** * Filter used to perform full-text search on an entry's subject, summary and content */ class blog_filter_search extends blog_filter { public function __construct($searchterm) { global $DB; $this->conditions = array("(".$DB->sql_like('p.summary', '?', false)." OR ".$DB->sql_like('p.content', '?', false)." OR ".$DB->sql_like('p.subject', '?', false).")"); $this->params[] = "%$searchterm%"; $this->params[] = "%$searchterm%"; $this->params[] = "%$searchterm%"; } } /** * Renderable class to represent an entry attachment */ class blog_entry_attachment implements renderable { public $filename; public $url; public $file; /** * Gets the file data * * @param stored_file $file * @param int $entryid Attachment entry id */ public function __construct($file, $entryid) { global $CFG; $this->file = $file; $this->filename = $file->get_filename(); $this->url = file_encode_url($CFG->wwwroot . '/pluginfile.php', '/' . SYSCONTEXTID . '/blog/attachment/' . $entryid . '/' . $this->filename); } } home/harasnat/www/learning/tag/locallib.php 0000604 00000002050 15062106131 0014751 0 ustar 00 <?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Moodle tag local library - output functions * * @package core_tag * @copyright 2007 Luiz Cruz <luiz.laydner@gmail.com> * @license http://www.gnu.org/copyleft/gpl.html GNU Public License */ debugging('All functions from /tags/locallib.php were deprecated and it will be removed soon, '. 'do not include this file in your code', DEBUG_DEVELOPER); home/harasnat/www/learning/comment/locallib.php 0000604 00000024071 15062107542 0015656 0 ustar 00 <?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * comment_manager is helper class to manage moodle comments in admin page (Reports->Comments) * * @package core_comment * @copyright 2010 Dongsheng Cai {@link http://dongsheng.org} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class comment_manager { /** @var int The number of comments to display per page */ private $perpage; /** @var stdClass Course data. */ protected $course; /** @var context|bool To store the context object or false if not found. */ protected $context; /** @var stdClass Course module. */ protected $cm; /** @var course_modinfo Module information for course, or null if resetting. */ protected $modinfo; /** @var string plugin type. */ protected $plugintype; /** @var string plugin name. */ protected $pluginname; /** * Constructs the comment_manage object */ public function __construct() { global $CFG; $this->perpage = $CFG->commentsperpage; } /** * Return comments by pages * * @global moodle_database $DB * @param int $page * @return array An array of comments */ function get_comments($page) { global $DB; if ($page == 0) { $start = 0; } else { $start = $page * $this->perpage; } $comments = array(); $userfieldsapi = \core_user\fields::for_name(); $usernamefields = $userfieldsapi->get_sql('u', false, '', '', false)->selects; $sql = "SELECT c.id, c.contextid, c.itemid, c.component, c.commentarea, c.userid, c.content, $usernamefields, c.timecreated FROM {comments} c JOIN {user} u ON u.id=c.userid ORDER BY c.timecreated ASC"; $rs = $DB->get_recordset_sql($sql, null, $start, $this->perpage); $formatoptions = array('overflowdiv' => true, 'blanktarget' => true); foreach ($rs as $item) { // Set calculated fields $item->fullname = fullname($item); $item->time = userdate($item->timecreated); $item->content = format_text($item->content, FORMAT_MOODLE, $formatoptions); // Unset fields not related to the comment foreach (\core_user\fields::get_name_fields() as $namefield) { unset($item->$namefield); } unset($item->timecreated); // Record the comment $comments[] = $item; } $rs->close(); return $comments; } /** * Records the course object * * @global moodle_page $PAGE * @global moodle_database $DB * @param int $courseid */ private function setup_course($courseid) { global $PAGE, $DB; if (!empty($this->course) && $this->course->id == $courseid) { // already set, stop return; } if ($courseid == $PAGE->course->id) { $this->course = $PAGE->course; } else if (!$this->course = $DB->get_record('course', array('id' => $courseid))) { $this->course = null; } } /** * Sets up the module or block information for a comment * * @global moodle_database $DB * @param stdClass $comment * @return bool */ private function setup_plugin($comment) { global $DB; $this->context = context::instance_by_id($comment->contextid, IGNORE_MISSING); if (!$this->context) { return false; } switch ($this->context->contextlevel) { case CONTEXT_BLOCK: if ($block = $DB->get_record('block_instances', array('id' => $this->context->instanceid))) { $this->plugintype = 'block'; $this->pluginname = $block->blockname; } else { return false; } break; case CONTEXT_MODULE: $this->plugintype = 'mod'; $this->cm = get_coursemodule_from_id('', $this->context->instanceid); $this->setup_course($this->cm->course); $this->modinfo = get_fast_modinfo($this->course); $this->pluginname = $this->modinfo->cms[$this->cm->id]->modname; break; } return true; } /** * Print comments * @param int $page * @return bool return false if no comments available * * @deprecated since Moodle 4.2 - please do not use this function any more */ public function print_comments($page = 0) { global $OUTPUT, $CFG, $OUTPUT, $DB; debugging('The function ' . __FUNCTION__ . '() is deprecated, please do not use it any more. ' . 'See \'comments\' system report class for replacement', DEBUG_DEVELOPER); $count = $DB->count_records('comments'); $comments = $this->get_comments($page); if (count($comments) == 0) { echo $OUTPUT->notification(get_string('nocomments', 'moodle')); return false; } $table = new html_table(); $table->head = array ( html_writer::checkbox('selectall', '', false, get_string('selectall'), array('id' => 'comment_select_all', 'class' => 'mr-1')), get_string('author', 'search'), get_string('content'), get_string('action') ); $table->colclasses = array ('leftalign', 'leftalign', 'leftalign', 'leftalign'); $table->attributes = array('class'=>'admintable generaltable'); $table->id = 'commentstable'; $table->data = array(); $link = new moodle_url('/comment/index.php', array('action' => 'delete', 'sesskey' => sesskey())); foreach ($comments as $c) { $userdata = html_writer::link(new moodle_url('/user/profile.php', ['id' => $c->userid]), $c->fullname); $this->setup_plugin($c); if (!empty($this->plugintype)) { $context_url = plugin_callback($this->plugintype, $this->pluginname, 'comment', 'url', array($c)); } $checkbox = html_writer::checkbox('comments', $c->id, false); $action = html_writer::link(new moodle_url($link, array('commentid' => $c->id)), get_string('delete')); if (!empty($context_url)) { $action .= html_writer::empty_tag('br'); $action .= html_writer::link($context_url, get_string('commentincontext'), array('target'=>'_blank')); } $table->data[] = array($checkbox, $userdata, $c->content, $action); } echo html_writer::table($table); echo $OUTPUT->paging_bar($count, $page, $this->perpage, $CFG->wwwroot.'/comment/index.php'); return true; } /** * Delete a comment * * @param int $commentid * @return bool */ public function delete_comment($commentid) { global $DB; if ($DB->record_exists('comments', array('id' => $commentid))) { $DB->delete_records('comments', array('id' => $commentid)); return true; } return false; } /** * Delete comments * * @param string $list A list of comment ids separated by hyphens * @return bool */ public function delete_comments($list) { global $DB; $ids = explode('-', $list); foreach ($ids as $id) { $id = (int)$id; if ($DB->record_exists('comments', array('id' => $id))) { $DB->delete_records('comments', array('id' => $id)); } } return true; } /** * Get comments created since a given time. * * @param stdClass $course course object * @param stdClass $context context object * @param string $component component name * @param int $since the time to check * @param stdClass $cm course module object * @return array list of comments db records since the given timelimit * @since Moodle 3.2 */ public function get_component_comments_since($course, $context, $component, $since, $cm = null) { global $DB; $commentssince = array(); $where = 'contextid = ? AND component = ? AND timecreated > ?'; $comments = $DB->get_records_select('comments', $where, array($context->id, $component, $since)); // Check item by item if we have permissions. $managersviewstatus = array(); foreach ($comments as $comment) { // Check if the manager for the item is cached. if (!isset($managersviewstatus[$comment->commentarea]) or !isset($managersviewstatus[$comment->commentarea][$comment->itemid])) { $args = new stdClass; $args->area = $comment->commentarea; $args->itemid = $comment->itemid; $args->context = $context; $args->course = $course; $args->client_id = 0; $args->component = $component; if (!empty($cm)) { $args->cm = $cm; } $manager = new comment($args); $managersviewstatus[$comment->commentarea][$comment->itemid] = $manager->can_view(); } if ($managersviewstatus[$comment->commentarea][$comment->itemid]) { $commentssince[$comment->id] = $comment; } } return $commentssince; } } home/harasnat/www/learning/enrol/locallib.php 0000604 00000171404 15062107740 0015336 0 ustar 00 <?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * This file contains the course_enrolment_manager class which is used to interface * with the functions that exist in enrollib.php in relation to a single course. * * @package core_enrol * @copyright 2010 Sam Hemelryk * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ use core_user\fields; defined('MOODLE_INTERNAL') || die(); /** * This class provides a targeted tied together means of interfacing the enrolment * tasks together with a course. * * It is provided as a convenience more than anything else. * * @copyright 2010 Sam Hemelryk * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class course_enrolment_manager { /** * The course context * @var context */ protected $context; /** * The course we are managing enrolments for * @var stdClass */ protected $course = null; /** * Limits the focus of the manager to one enrolment plugin instance * @var string */ protected $instancefilter = null; /** * Limits the focus of the manager to users with specified role * @var int */ protected $rolefilter = 0; /** * Limits the focus of the manager to users who match search string * @var string */ protected $searchfilter = ''; /** * Limits the focus of the manager to users in specified group * @var int */ protected $groupfilter = 0; /** * Limits the focus of the manager to users who match status active/inactive * @var int */ protected $statusfilter = -1; /** * The total number of users enrolled in the course * Populated by course_enrolment_manager::get_total_users * @var int */ protected $totalusers = null; /** * An array of users currently enrolled in the course * Populated by course_enrolment_manager::get_users * @var array */ protected $users = array(); /** * An array of users who have roles within this course but who have not * been enrolled in the course * @var array */ protected $otherusers = array(); /** * The total number of users who hold a role within the course but who * arn't enrolled. * @var int */ protected $totalotherusers = null; /** * The current moodle_page object * @var moodle_page */ protected $moodlepage = null; /**#@+ * These variables are used to cache the information this class uses * please never use these directly instead use their get_ counterparts. * @access private * @var array */ private $_instancessql = null; private $_instances = null; private $_inames = null; private $_plugins = null; private $_allplugins = null; private $_roles = null; private $_visibleroles = null; private $_assignableroles = null; private $_assignablerolesothers = null; private $_groups = null; /**#@-*/ /** * Constructs the course enrolment manager * * @param moodle_page $moodlepage * @param stdClass $course * @param string $instancefilter * @param int $rolefilter If non-zero, filters to users with specified role * @param string $searchfilter If non-blank, filters to users with search text * @param int $groupfilter if non-zero, filter users with specified group * @param int $statusfilter if not -1, filter users with active/inactive enrollment. */ public function __construct(moodle_page $moodlepage, $course, $instancefilter = null, $rolefilter = 0, $searchfilter = '', $groupfilter = 0, $statusfilter = -1) { $this->moodlepage = $moodlepage; $this->context = context_course::instance($course->id); $this->course = $course; $this->instancefilter = $instancefilter; $this->rolefilter = $rolefilter; $this->searchfilter = $searchfilter; $this->groupfilter = $groupfilter; $this->statusfilter = $statusfilter; } /** * Returns the current moodle page * @return moodle_page */ public function get_moodlepage() { return $this->moodlepage; } /** * Returns the total number of enrolled users in the course. * * If a filter was specificed this will be the total number of users enrolled * in this course by means of that instance. * * @global moodle_database $DB * @return int */ public function get_total_users() { global $DB; if ($this->totalusers === null) { list($instancessql, $params, $filter) = $this->get_instance_sql(); list($filtersql, $moreparams) = $this->get_filter_sql(); $params += $moreparams; $sqltotal = "SELECT COUNT(DISTINCT u.id) FROM {user} u JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid $instancessql) JOIN {enrol} e ON (e.id = ue.enrolid)"; if ($this->groupfilter) { $sqltotal .= " LEFT JOIN ({groups_members} gm JOIN {groups} g ON (g.id = gm.groupid)) ON (u.id = gm.userid AND g.courseid = e.courseid)"; } $sqltotal .= "WHERE $filtersql"; $this->totalusers = (int)$DB->count_records_sql($sqltotal, $params); } return $this->totalusers; } /** * Returns the total number of enrolled users in the course. * * If a filter was specificed this will be the total number of users enrolled * in this course by means of that instance. * * @global moodle_database $DB * @return int */ public function get_total_other_users() { global $DB; if ($this->totalotherusers === null) { list($ctxcondition, $params) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'ctx'); $params['courseid'] = $this->course->id; $sql = "SELECT COUNT(DISTINCT u.id) FROM {role_assignments} ra JOIN {user} u ON u.id = ra.userid JOIN {context} ctx ON ra.contextid = ctx.id LEFT JOIN ( SELECT ue.id, ue.userid FROM {user_enrolments} ue LEFT JOIN {enrol} e ON e.id=ue.enrolid WHERE e.courseid = :courseid ) ue ON ue.userid=u.id WHERE ctx.id $ctxcondition AND ue.id IS NULL"; $this->totalotherusers = (int)$DB->count_records_sql($sql, $params); } return $this->totalotherusers; } /** * Gets all of the users enrolled in this course. * * If a filter was specified this will be the users who were enrolled * in this course by means of that instance. If role or search filters were * specified then these will also be applied. * * @global moodle_database $DB * @param string $sort * @param string $direction ASC or DESC * @param int $page First page should be 0 * @param int $perpage Defaults to 25 * @return array */ public function get_users($sort, $direction='ASC', $page=0, $perpage=25) { global $DB; if ($direction !== 'ASC') { $direction = 'DESC'; } $key = md5("$sort-$direction-$page-$perpage"); if (!array_key_exists($key, $this->users)) { list($instancessql, $params, $filter) = $this->get_instance_sql(); list($filtersql, $moreparams) = $this->get_filter_sql(); $params += $moreparams; $userfields = fields::for_identity($this->get_context())->with_userpic()->excluding('lastaccess'); ['selects' => $fieldselect, 'joins' => $fieldjoin, 'params' => $fieldjoinparams] = (array)$userfields->get_sql('u', true, '', '', false); $params += $fieldjoinparams; $sql = "SELECT DISTINCT $fieldselect, COALESCE(ul.timeaccess, 0) AS lastcourseaccess FROM {user} u JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid $instancessql) JOIN {enrol} e ON (e.id = ue.enrolid) $fieldjoin LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = u.id)"; if ($this->groupfilter) { $sql .= " LEFT JOIN ({groups_members} gm JOIN {groups} g ON (g.id = gm.groupid)) ON (u.id = gm.userid AND g.courseid = e.courseid)"; } $sql .= "WHERE $filtersql ORDER BY $sort $direction"; $this->users[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage); } return $this->users[$key]; } /** * Obtains WHERE clause to filter results by defined search and role filter * (instance filter is handled separately in JOIN clause, see * get_instance_sql). * * @return array Two-element array with SQL and params for WHERE clause */ protected function get_filter_sql() { global $DB; // Search condition. // TODO Does not support custom user profile fields (MDL-70456). $extrafields = fields::get_identity_fields($this->get_context(), false); list($sql, $params) = users_search_sql($this->searchfilter, 'u', USER_SEARCH_CONTAINS, $extrafields); // Role condition. if ($this->rolefilter) { // Get context SQL. $contextids = $this->context->get_parent_context_ids(); $contextids[] = $this->context->id; list($contextsql, $contextparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED); $params += $contextparams; // Role check condition. $sql .= " AND (SELECT COUNT(1) FROM {role_assignments} ra WHERE ra.userid = u.id " . "AND ra.roleid = :roleid AND ra.contextid $contextsql) > 0"; $params['roleid'] = $this->rolefilter; } // Group condition. if ($this->groupfilter) { if ($this->groupfilter < 0) { // Show users who are not in any group. $sql .= " AND gm.groupid IS NULL"; } else { $sql .= " AND gm.groupid = :groupid"; $params['groupid'] = $this->groupfilter; } } // Status condition. if ($this->statusfilter === ENROL_USER_ACTIVE) { $sql .= " AND ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)"; $now = round(time(), -2); // rounding helps caching in DB $params += array('enabled' => ENROL_INSTANCE_ENABLED, 'active' => ENROL_USER_ACTIVE, 'now1' => $now, 'now2' => $now); } else if ($this->statusfilter === ENROL_USER_SUSPENDED) { $sql .= " AND (ue.status = :inactive OR e.status = :disabled OR ue.timestart > :now1 OR (ue.timeend <> 0 AND ue.timeend < :now2))"; $now = round(time(), -2); // rounding helps caching in DB $params += array('disabled' => ENROL_INSTANCE_DISABLED, 'inactive' => ENROL_USER_SUSPENDED, 'now1' => $now, 'now2' => $now); } return array($sql, $params); } /** * Gets and array of other users. * * Other users are users who have been assigned roles or inherited roles * within this course but who have not been enrolled in the course * * @global moodle_database $DB * @param string $sort * @param string $direction * @param int $page * @param int $perpage * @return array */ public function get_other_users($sort, $direction='ASC', $page=0, $perpage=25) { global $DB; if ($direction !== 'ASC') { $direction = 'DESC'; } $key = md5("$sort-$direction-$page-$perpage"); if (!array_key_exists($key, $this->otherusers)) { list($ctxcondition, $params) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'ctx'); $params['courseid'] = $this->course->id; $params['cid'] = $this->course->id; $userfields = fields::for_identity($this->get_context())->with_userpic(); ['selects' => $fieldselect, 'joins' => $fieldjoin, 'params' => $fieldjoinparams] = (array)$userfields->get_sql('u', true); $params += $fieldjoinparams; $sql = "SELECT ra.id as raid, ra.contextid, ra.component, ctx.contextlevel, ra.roleid, coalesce(u.lastaccess,0) AS lastaccess $fieldselect FROM {role_assignments} ra JOIN {user} u ON u.id = ra.userid JOIN {context} ctx ON ra.contextid = ctx.id $fieldjoin LEFT JOIN ( SELECT ue.id, ue.userid FROM {user_enrolments} ue JOIN {enrol} e ON e.id = ue.enrolid WHERE e.courseid = :courseid ) ue ON ue.userid=u.id WHERE ctx.id $ctxcondition AND ue.id IS NULL ORDER BY $sort $direction, ctx.depth DESC"; $this->otherusers[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage); } return $this->otherusers[$key]; } /** * Helper method used by {@link get_potential_users()} and {@link search_other_users()}. * * @param string $search the search term, if any. * @param bool $searchanywhere Can the search term be anywhere, or must it be at the start. * @return array with three elements: * string list of fields to SELECT, * string possible database joins for user fields * string contents of SQL WHERE clause, * array query params. Note that the SQL snippets use named parameters. */ protected function get_basic_search_conditions($search, $searchanywhere) { global $DB, $CFG; // Get custom user field SQL used for querying all the fields we need (identity, name, and // user picture). $userfields = fields::for_identity($this->context)->with_name()->with_userpic() ->excluding('username', 'lastaccess', 'maildisplay'); ['selects' => $fieldselects, 'joins' => $fieldjoins, 'params' => $params, 'mappings' => $mappings] = (array)$userfields->get_sql('u', true, '', '', false); // Searchable fields are only the identity and name ones (not userpic, and without exclusions). $searchablefields = fields::for_identity($this->context)->with_name(); $searchable = array_fill_keys($searchablefields->get_required_fields(), true); if (array_key_exists('username', $searchable)) { // Add the username into the mappings list from the other query, because it was excluded. $mappings['username'] = 'u.username'; } // Add some additional sensible conditions $tests = array("u.id <> :guestid", 'u.deleted = 0', 'u.confirmed = 1'); $params['guestid'] = $CFG->siteguest; if (!empty($search)) { // Include identity and name fields as conditions. foreach ($mappings as $fieldname => $fieldsql) { if (array_key_exists($fieldname, $searchable)) { $conditions[] = $fieldsql; } } $conditions[] = $DB->sql_fullname('u.firstname', 'u.lastname'); if ($searchanywhere) { $searchparam = '%' . $search . '%'; } else { $searchparam = $search . '%'; } $i = 0; foreach ($conditions as $key => $condition) { $conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false); $params["con{$i}00"] = $searchparam; $i++; } $tests[] = '(' . implode(' OR ', $conditions) . ')'; } $wherecondition = implode(' AND ', $tests); $selects = $fieldselects . ', u.username, u.lastaccess, u.maildisplay'; return [$selects, $fieldjoins, $params, $wherecondition]; } /** * Helper method used by {@link get_potential_users()} and {@link search_other_users()}. * * @param string $search the search string, if any. * @param string $fields the first bit of the SQL when returning some users. * @param string $countfields fhe first bit of the SQL when counting the users. * @param string $sql the bulk of the SQL statement. * @param array $params query parameters. * @param int $page which page number of the results to show. * @param int $perpage number of users per page. * @param int $addedenrollment number of users added to enrollment. * @param bool $returnexactcount Return the exact total users using count_record or not. * @return array with two or three elements: * int totalusers Number users matching the search. (This element only exist if $returnexactcount was set to true) * array users List of user objects returned by the query. * boolean moreusers True if there are still more users, otherwise is False. * @throws dml_exception */ protected function execute_search_queries($search, $fields, $countfields, $sql, array $params, $page, $perpage, $addedenrollment = 0, $returnexactcount = false) { global $DB, $CFG; list($sort, $sortparams) = users_order_by_sql('u', $search, $this->get_context()); $order = ' ORDER BY ' . $sort; $totalusers = 0; $moreusers = false; $results = []; $availableusers = $DB->get_records_sql($fields . $sql . $order, array_merge($params, $sortparams), ($page * $perpage) - $addedenrollment, $perpage + 1); if ($availableusers) { $totalusers = count($availableusers); $moreusers = $totalusers > $perpage; if ($moreusers) { // We need to discard the last record. array_pop($availableusers); } if ($returnexactcount && $moreusers) { // There is more data. We need to do the exact count. $totalusers = $DB->count_records_sql($countfields . $sql, $params); } } $results['users'] = $availableusers; $results['moreusers'] = $moreusers; if ($returnexactcount) { // Include totalusers in result if $returnexactcount flag is true. $results['totalusers'] = $totalusers; } return $results; } /** * Gets an array of the users that can be enrolled in this course. * * @global moodle_database $DB * @param int $enrolid * @param string $search * @param bool $searchanywhere * @param int $page Defaults to 0 * @param int $perpage Defaults to 25 * @param int $addedenrollment Defaults to 0 * @param bool $returnexactcount Return the exact total users using count_record or not. * @return array with two or three elements: * int totalusers Number users matching the search. (This element only exist if $returnexactcount was set to true) * array users List of user objects returned by the query. * boolean moreusers True if there are still more users, otherwise is False. * @throws dml_exception */ public function get_potential_users($enrolid, $search = '', $searchanywhere = false, $page = 0, $perpage = 25, $addedenrollment = 0, $returnexactcount = false) { global $DB; [$ufields, $joins, $params, $wherecondition] = $this->get_basic_search_conditions($search, $searchanywhere); $fields = 'SELECT '.$ufields; $countfields = 'SELECT COUNT(1)'; $sql = " FROM {user} u $joins LEFT JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid = :enrolid) WHERE $wherecondition AND ue.id IS NULL"; $params['enrolid'] = $enrolid; return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage, $addedenrollment, $returnexactcount); } /** * Searches other users and returns paginated results * * @global moodle_database $DB * @param string $search * @param bool $searchanywhere * @param int $page Starting at 0 * @param int $perpage * @param bool $returnexactcount Return the exact total users using count_record or not. * @return array with two or three elements: * int totalusers Number users matching the search. (This element only exist if $returnexactcount was set to true) * array users List of user objects returned by the query. * boolean moreusers True if there are still more users, otherwise is False. * @throws dml_exception */ public function search_other_users($search = '', $searchanywhere = false, $page = 0, $perpage = 25, $returnexactcount = false) { global $DB, $CFG; [$ufields, $joins, $params, $wherecondition] = $this->get_basic_search_conditions($search, $searchanywhere); $fields = 'SELECT ' . $ufields; $countfields = 'SELECT COUNT(u.id)'; $sql = " FROM {user} u $joins LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid = :contextid) WHERE $wherecondition AND ra.id IS NULL"; $params['contextid'] = $this->context->id; return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage, 0, $returnexactcount); } /** * Searches through the enrolled users in this course. * * @param string $search The search term. * @param bool $searchanywhere Can the search term be anywhere, or must it be at the start. * @param int $page Starting at 0. * @param int $perpage Number of users returned per page. * @param bool $returnexactcount Return the exact total users using count_record or not. * @return array with two or three elements: * int totalusers Number users matching the search. (This element only exist if $returnexactcount was set to true) * array users List of user objects returned by the query. * boolean moreusers True if there are still more users, otherwise is False. */ public function search_users(string $search = '', bool $searchanywhere = false, int $page = 0, int $perpage = 25, bool $returnexactcount = false) { global $USER; [$ufields, $joins, $params, $wherecondition] = $this->get_basic_search_conditions($search, $searchanywhere); $groupmode = groups_get_course_groupmode($this->course); if ($groupmode == SEPARATEGROUPS && !has_capability('moodle/site:accessallgroups', $this->context)) { $groups = groups_get_all_groups($this->course->id, $USER->id, 0, 'g.id'); $groupids = array_column($groups, 'id'); } else { $groupids = []; } [$enrolledsql, $enrolledparams] = get_enrolled_sql($this->context, '', $groupids); $fields = 'SELECT ' . $ufields; $countfields = 'SELECT COUNT(u.id)'; $sql = " FROM {user} u $joins JOIN ($enrolledsql) je ON je.id = u.id WHERE $wherecondition"; $params = array_merge($params, $enrolledparams); return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage, 0, $returnexactcount); } /** * Gets an array containing some SQL to user for when selecting, params for * that SQL, and the filter that was used in constructing the sql. * * @global moodle_database $DB * @return array */ protected function get_instance_sql() { global $DB; if ($this->_instancessql === null) { $instances = $this->get_enrolment_instances(); $filter = $this->get_enrolment_filter(); if ($filter && array_key_exists($filter, $instances)) { $sql = " = :ifilter"; $params = array('ifilter'=>$filter); } else { $filter = 0; if ($instances) { list($sql, $params) = $DB->get_in_or_equal(array_keys($this->get_enrolment_instances()), SQL_PARAMS_NAMED); } else { // no enabled instances, oops, we should probably say something $sql = "= :never"; $params = array('never'=>-1); } } $this->instancefilter = $filter; $this->_instancessql = array($sql, $params, $filter); } return $this->_instancessql; } /** * Returns all of the enrolment instances for this course. * * @param bool $onlyenabled Whether to return data from enabled enrolment instance names only. * @return array */ public function get_enrolment_instances($onlyenabled = false) { if ($this->_instances === null) { $this->_instances = enrol_get_instances($this->course->id, $onlyenabled); } return $this->_instances; } /** * Returns the names for all of the enrolment instances for this course. * * @param bool $onlyenabled Whether to return data from enabled enrolment instance names only. * @return array */ public function get_enrolment_instance_names($onlyenabled = false) { if ($this->_inames === null) { $instances = $this->get_enrolment_instances($onlyenabled); $plugins = $this->get_enrolment_plugins(false); foreach ($instances as $key=>$instance) { if (!isset($plugins[$instance->enrol])) { // weird, some broken stuff in plugin unset($instances[$key]); continue; } $this->_inames[$key] = $plugins[$instance->enrol]->get_instance_name($instance); } } return $this->_inames; } /** * Gets all of the enrolment plugins that are available for this course. * * @param bool $onlyenabled return only enabled enrol plugins * @return array */ public function get_enrolment_plugins($onlyenabled = true) { if ($this->_plugins === null) { $this->_plugins = enrol_get_plugins(true); } if ($onlyenabled) { return $this->_plugins; } if ($this->_allplugins === null) { // Make sure we have the same objects in _allplugins and _plugins. $this->_allplugins = $this->_plugins; foreach (enrol_get_plugins(false) as $name=>$plugin) { if (!isset($this->_allplugins[$name])) { $this->_allplugins[$name] = $plugin; } } } return $this->_allplugins; } /** * Gets all of the roles this course can contain. * * @return array */ public function get_all_roles() { if ($this->_roles === null) { $this->_roles = role_fix_names(get_all_roles($this->context), $this->context); } return $this->_roles; } /** * Gets all of the roles this course can contain. * * @return array */ public function get_viewable_roles() { if ($this->_visibleroles === null) { $this->_visibleroles = get_viewable_roles($this->context); } return $this->_visibleroles; } /** * Gets all of the assignable roles for this course. * * @return array */ public function get_assignable_roles($otherusers = false) { if ($this->_assignableroles === null) { $this->_assignableroles = get_assignable_roles($this->context, ROLENAME_ALIAS, false); // verifies unassign access control too } if ($otherusers) { if (!is_array($this->_assignablerolesothers)) { $this->_assignablerolesothers = array(); list($courseviewroles, $ignored) = get_roles_with_cap_in_context($this->context, 'moodle/course:view'); foreach ($this->_assignableroles as $roleid=>$role) { if (isset($courseviewroles[$roleid])) { $this->_assignablerolesothers[$roleid] = $role; } } } return $this->_assignablerolesothers; } else { return $this->_assignableroles; } } /** * Gets all of the assignable roles for this course, wrapped in an array to ensure * role sort order is not lost during json deserialisation. * * @param boolean $otherusers whether to include the assignable roles for other users * @return array */ public function get_assignable_roles_for_json($otherusers = false) { $rolesarray = array(); $assignable = $this->get_assignable_roles($otherusers); foreach ($assignable as $id => $role) { $rolesarray[] = array('id' => $id, 'name' => $role); } return $rolesarray; } /** * Gets all of the groups for this course. * * @return array */ public function get_all_groups() { if ($this->_groups === null) { $this->_groups = groups_get_all_groups($this->course->id); foreach ($this->_groups as $gid=>$group) { $this->_groups[$gid]->name = format_string($group->name); } } return $this->_groups; } /** * Unenrols a user from the course given the users ue entry * * @global moodle_database $DB * @param stdClass $ue * @return bool */ public function unenrol_user($ue) { global $DB; list ($instance, $plugin) = $this->get_user_enrolment_components($ue); if ($instance && $plugin && $plugin->allow_unenrol_user($instance, $ue) && has_capability("enrol/$instance->enrol:unenrol", $this->context)) { $plugin->unenrol_user($instance, $ue->userid); return true; } return false; } /** * Given a user enrolment record this method returns the plugin and enrolment * instance that relate to it. * * @param stdClass|int $userenrolment * @return array array($instance, $plugin) */ public function get_user_enrolment_components($userenrolment) { global $DB; if (is_numeric($userenrolment)) { $userenrolment = $DB->get_record('user_enrolments', array('id'=>(int)$userenrolment)); } $instances = $this->get_enrolment_instances(); $plugins = $this->get_enrolment_plugins(false); if (!$userenrolment || !isset($instances[$userenrolment->enrolid])) { return array(false, false); } $instance = $instances[$userenrolment->enrolid]; $plugin = $plugins[$instance->enrol]; return array($instance, $plugin); } /** * Removes an assigned role from a user. * * @global moodle_database $DB * @param int $userid * @param int $roleid * @return bool */ public function unassign_role_from_user($userid, $roleid) { global $DB; // Admins may unassign any role, others only those they could assign. if (!is_siteadmin() and !array_key_exists($roleid, $this->get_assignable_roles())) { if (defined('AJAX_SCRIPT')) { throw new moodle_exception('invalidrole'); } return false; } $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST); $ras = $DB->get_records('role_assignments', array('contextid'=>$this->context->id, 'userid'=>$user->id, 'roleid'=>$roleid)); foreach ($ras as $ra) { if ($ra->component) { if (strpos($ra->component, 'enrol_') !== 0) { continue; } if (!$plugin = enrol_get_plugin(substr($ra->component, 6))) { continue; } if ($plugin->roles_protected()) { continue; } } role_unassign($ra->roleid, $ra->userid, $ra->contextid, $ra->component, $ra->itemid); } return true; } /** * Assigns a role to a user. * * @param int $roleid * @param int $userid * @return int|false */ public function assign_role_to_user($roleid, $userid) { require_capability('moodle/role:assign', $this->context); if (!array_key_exists($roleid, $this->get_assignable_roles())) { if (defined('AJAX_SCRIPT')) { throw new moodle_exception('invalidrole'); } return false; } return role_assign($roleid, $userid, $this->context->id, '', NULL); } /** * Adds a user to a group * * @param stdClass $user * @param int $groupid * @return bool */ public function add_user_to_group($user, $groupid) { require_capability('moodle/course:managegroups', $this->context); $group = $this->get_group($groupid); if (!$group) { return false; } return groups_add_member($group->id, $user->id); } /** * Removes a user from a group * * @global moodle_database $DB * @param StdClass $user * @param int $groupid * @return bool */ public function remove_user_from_group($user, $groupid) { global $DB; require_capability('moodle/course:managegroups', $this->context); $group = $this->get_group($groupid); if (!groups_remove_member_allowed($group, $user)) { return false; } if (!$group) { return false; } return groups_remove_member($group, $user); } /** * Gets the requested group * * @param int $groupid * @return stdClass|int */ public function get_group($groupid) { $groups = $this->get_all_groups(); if (!array_key_exists($groupid, $groups)) { return false; } return $groups[$groupid]; } /** * Edits an enrolment * * @param stdClass $userenrolment * @param stdClass $data * @return bool */ public function edit_enrolment($userenrolment, $data) { //Only allow editing if the user has the appropriate capability //Already checked in /user/index.php but checking again in case this function is called from elsewhere list($instance, $plugin) = $this->get_user_enrolment_components($userenrolment); if ($instance && $plugin && $plugin->allow_manage($instance) && has_capability("enrol/$instance->enrol:manage", $this->context)) { if (!isset($data->status)) { $data->status = $userenrolment->status; } $plugin->update_user_enrol($instance, $userenrolment->userid, $data->status, $data->timestart, $data->timeend); return true; } return false; } /** * Returns the current enrolment filter that is being applied by this class * @return string */ public function get_enrolment_filter() { return $this->instancefilter; } /** * Gets the roles assigned to this user that are applicable for this course. * * @param int $userid * @return array */ public function get_user_roles($userid) { $roles = array(); $ras = get_user_roles($this->context, $userid, true, 'c.contextlevel DESC, r.sortorder ASC'); $plugins = $this->get_enrolment_plugins(false); foreach ($ras as $ra) { if ($ra->contextid != $this->context->id) { if (!array_key_exists($ra->roleid, $roles)) { $roles[$ra->roleid] = null; } // higher ras, course always takes precedence continue; } if (array_key_exists($ra->roleid, $roles) && $roles[$ra->roleid] === false) { continue; } $changeable = true; if ($ra->component) { $changeable = false; if (strpos($ra->component, 'enrol_') === 0) { $plugin = substr($ra->component, 6); if (isset($plugins[$plugin])) { $changeable = !$plugins[$plugin]->roles_protected(); } } } $roles[$ra->roleid] = $changeable; } return $roles; } /** * Gets the enrolments this user has in the course - including all suspended plugins and instances. * * @global moodle_database $DB * @param int $userid * @return array */ public function get_user_enrolments($userid) { global $DB; list($instancessql, $params, $filter) = $this->get_instance_sql(); $params['userid'] = $userid; $userenrolments = $DB->get_records_select('user_enrolments', "enrolid $instancessql AND userid = :userid", $params); $instances = $this->get_enrolment_instances(); $plugins = $this->get_enrolment_plugins(false); $inames = $this->get_enrolment_instance_names(); foreach ($userenrolments as &$ue) { $ue->enrolmentinstance = $instances[$ue->enrolid]; $ue->enrolmentplugin = $plugins[$ue->enrolmentinstance->enrol]; $ue->enrolmentinstancename = $inames[$ue->enrolmentinstance->id]; } return $userenrolments; } /** * Gets the groups this user belongs to * * @param int $userid * @return array */ public function get_user_groups($userid) { return groups_get_all_groups($this->course->id, $userid, 0, 'g.id'); } /** * Retursn an array of params that would go into the URL to return to this * exact page. * * @return array */ public function get_url_params() { $args = array( 'id' => $this->course->id ); if (!empty($this->instancefilter)) { $args['ifilter'] = $this->instancefilter; } if (!empty($this->rolefilter)) { $args['role'] = $this->rolefilter; } if ($this->searchfilter !== '') { $args['search'] = $this->searchfilter; } if (!empty($this->groupfilter)) { $args['filtergroup'] = $this->groupfilter; } if ($this->statusfilter !== -1) { $args['status'] = $this->statusfilter; } return $args; } /** * Returns the course this object is managing enrolments for * * @return stdClass */ public function get_course() { return $this->course; } /** * Returns the course context * * @return context */ public function get_context() { return $this->context; } /** * Gets an array of other users in this course ready for display. * * Other users are users who have been assigned or inherited roles within this * course but have not been enrolled. * * @param core_enrol_renderer $renderer * @param moodle_url $pageurl * @param string $sort * @param string $direction ASC | DESC * @param int $page Starting from 0 * @param int $perpage * @return array */ public function get_other_users_for_display(core_enrol_renderer $renderer, moodle_url $pageurl, $sort, $direction, $page, $perpage) { $userroles = $this->get_other_users($sort, $direction, $page, $perpage); $roles = $this->get_all_roles(); $plugins = $this->get_enrolment_plugins(false); $context = $this->get_context(); $now = time(); // TODO Does not support custom user profile fields (MDL-70456). $extrafields = fields::get_identity_fields($context, false); $users = array(); foreach ($userroles as $userrole) { $contextid = $userrole->contextid; unset($userrole->contextid); // This would collide with user avatar. if (!array_key_exists($userrole->id, $users)) { $users[$userrole->id] = $this->prepare_user_for_display($userrole, $extrafields, $now); } $a = new stdClass; $a->role = $roles[$userrole->roleid]->localname; if ($contextid == $this->context->id) { $changeable = true; if ($userrole->component) { $changeable = false; if (strpos($userrole->component, 'enrol_') === 0) { $plugin = substr($userrole->component, 6); if (isset($plugins[$plugin])) { $changeable = !$plugins[$plugin]->roles_protected(); } } } $roletext = get_string('rolefromthiscourse', 'enrol', $a); } else { $changeable = false; switch ($userrole->contextlevel) { case CONTEXT_COURSE : // Meta course $roletext = get_string('rolefrommetacourse', 'enrol', $a); break; case CONTEXT_COURSECAT : $roletext = get_string('rolefromcategory', 'enrol', $a); break; case CONTEXT_SYSTEM: default: $roletext = get_string('rolefromsystem', 'enrol', $a); break; } } if (!isset($users[$userrole->id]['roles'])) { $users[$userrole->id]['roles'] = array(); } $users[$userrole->id]['roles'][$userrole->roleid] = array( 'text' => $roletext, 'unchangeable' => !$changeable ); } return $users; } /** * Gets an array of users for display, this includes minimal user information * as well as minimal information on the users roles, groups, and enrolments. * * @param core_enrol_renderer $renderer * @param moodle_url $pageurl * @param int $sort * @param string $direction ASC or DESC * @param int $page * @param int $perpage * @return array */ public function get_users_for_display(course_enrolment_manager $manager, $sort, $direction, $page, $perpage) { $pageurl = $manager->get_moodlepage()->url; $users = $this->get_users($sort, $direction, $page, $perpage); $now = time(); $straddgroup = get_string('addgroup', 'group'); $strunenrol = get_string('unenrol', 'enrol'); $stredit = get_string('edit'); $visibleroles = $this->get_viewable_roles(); $assignable = $this->get_assignable_roles(); $allgroups = $this->get_all_groups(); $context = $this->get_context(); $canmanagegroups = has_capability('moodle/course:managegroups', $context); $url = new moodle_url($pageurl, $this->get_url_params()); // TODO Does not support custom user profile fields (MDL-70456). $extrafields = fields::get_identity_fields($context, false); $enabledplugins = $this->get_enrolment_plugins(true); $userdetails = array(); foreach ($users as $user) { $details = $this->prepare_user_for_display($user, $extrafields, $now); // Roles $details['roles'] = array(); foreach ($this->get_user_roles($user->id) as $rid=>$rassignable) { $unchangeable = !$rassignable; if (!is_siteadmin() and !isset($assignable[$rid])) { $unchangeable = true; } if (isset($visibleroles[$rid])) { $label = $visibleroles[$rid]; } else { $label = get_string('novisibleroles', 'role'); $unchangeable = true; } $details['roles'][$rid] = array('text' => $label, 'unchangeable' => $unchangeable); } // Users $usergroups = $this->get_user_groups($user->id); $details['groups'] = array(); foreach($usergroups as $gid=>$unused) { $details['groups'][$gid] = $allgroups[$gid]->name; } // Enrolments $details['enrolments'] = array(); foreach ($this->get_user_enrolments($user->id) as $ue) { if (!isset($enabledplugins[$ue->enrolmentinstance->enrol])) { $details['enrolments'][$ue->id] = array( 'text' => $ue->enrolmentinstancename, 'period' => null, 'dimmed' => true, 'actions' => array() ); continue; } else if ($ue->timestart and $ue->timeend) { $period = get_string('periodstartend', 'enrol', array('start'=>userdate($ue->timestart), 'end'=>userdate($ue->timeend))); $periodoutside = ($ue->timestart && $ue->timeend && ($now < $ue->timestart || $now > $ue->timeend)); } else if ($ue->timestart) { $period = get_string('periodstart', 'enrol', userdate($ue->timestart)); $periodoutside = ($ue->timestart && $now < $ue->timestart); } else if ($ue->timeend) { $period = get_string('periodend', 'enrol', userdate($ue->timeend)); $periodoutside = ($ue->timeend && $now > $ue->timeend); } else { // If there is no start or end show when user was enrolled. $period = get_string('periodnone', 'enrol', userdate($ue->timecreated)); $periodoutside = false; } $details['enrolments'][$ue->id] = array( 'text' => $ue->enrolmentinstancename, 'period' => $period, 'dimmed' => ($periodoutside or $ue->status != ENROL_USER_ACTIVE or $ue->enrolmentinstance->status != ENROL_INSTANCE_ENABLED), 'actions' => $ue->enrolmentplugin->get_user_enrolment_actions($manager, $ue) ); } $userdetails[$user->id] = $details; } return $userdetails; } /** * Prepare a user record for display * * This function is called by both {@link get_users_for_display} and {@link get_other_users_for_display} to correctly * prepare user fields for display * * Please note that this function does not check capability for moodle/coures:viewhiddenuserfields * * @param object $user The user record * @param array $extrafields The list of fields as returned from \core_user\fields::get_identity_fields used to determine which * additional fields may be displayed * @param int $now The time used for lastaccess calculation * @return array The fields to be displayed including userid, courseid, picture, firstname, lastcourseaccess, lastaccess and any * additional fields from $extrafields */ private function prepare_user_for_display($user, $extrafields, $now) { $details = array( 'userid' => $user->id, 'courseid' => $this->get_course()->id, 'picture' => new user_picture($user), 'userfullnamedisplay' => fullname($user, has_capability('moodle/site:viewfullnames', $this->get_context())), 'lastaccess' => get_string('never'), 'lastcourseaccess' => get_string('never'), ); foreach ($extrafields as $field) { $details[$field] = s($user->{$field}); } // Last time user has accessed the site. if (!empty($user->lastaccess)) { $details['lastaccess'] = format_time($now - $user->lastaccess); } // Last time user has accessed the course. if (!empty($user->lastcourseaccess)) { $details['lastcourseaccess'] = format_time($now - $user->lastcourseaccess); } return $details; } public function get_manual_enrol_buttons() { $plugins = $this->get_enrolment_plugins(true); // Skip disabled plugins. $buttons = array(); foreach ($plugins as $plugin) { $newbutton = $plugin->get_manual_enrol_button($this); if (is_array($newbutton)) { $buttons += $newbutton; } else if ($newbutton instanceof enrol_user_button) { $buttons[] = $newbutton; } } return $buttons; } public function has_instance($enrolpluginname) { // Make sure manual enrolments instance exists foreach ($this->get_enrolment_instances() as $instance) { if ($instance->enrol == $enrolpluginname) { return true; } } return false; } /** * Returns the enrolment plugin that the course manager was being filtered to. * * If no filter was being applied then this function returns false. * * @return enrol_plugin */ public function get_filtered_enrolment_plugin() { $instances = $this->get_enrolment_instances(); $plugins = $this->get_enrolment_plugins(false); if (empty($this->instancefilter) || !array_key_exists($this->instancefilter, $instances)) { return false; } $instance = $instances[$this->instancefilter]; return $plugins[$instance->enrol]; } /** * Returns and array of users + enrolment details. * * Given an array of user id's this function returns and array of user enrolments for those users * as well as enough user information to display the users name and picture for each enrolment. * * @global moodle_database $DB * @param array $userids * @return array */ public function get_users_enrolments(array $userids) { global $DB; $instances = $this->get_enrolment_instances(); $plugins = $this->get_enrolment_plugins(false); if (!empty($this->instancefilter)) { $instancesql = ' = :instanceid'; $instanceparams = array('instanceid' => $this->instancefilter); } else { list($instancesql, $instanceparams) = $DB->get_in_or_equal(array_keys($instances), SQL_PARAMS_NAMED, 'instanceid0000'); } $userfieldsapi = \core_user\fields::for_userpic(); $userfields = $userfieldsapi->get_sql('u', false, '', '', false)->selects; list($idsql, $idparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid0000'); list($sort, $sortparams) = users_order_by_sql('u'); $sql = "SELECT ue.id AS ueid, ue.status, ue.enrolid, ue.userid, ue.timestart, ue.timeend, ue.modifierid, ue.timecreated, ue.timemodified, $userfields FROM {user_enrolments} ue LEFT JOIN {user} u ON u.id = ue.userid WHERE ue.enrolid $instancesql AND u.id $idsql ORDER BY $sort"; $rs = $DB->get_recordset_sql($sql, $idparams + $instanceparams + $sortparams); $users = array(); foreach ($rs as $ue) { $user = user_picture::unalias($ue); $ue->id = $ue->ueid; unset($ue->ueid); if (!array_key_exists($user->id, $users)) { $user->enrolments = array(); $users[$user->id] = $user; } $ue->enrolmentinstance = $instances[$ue->enrolid]; $ue->enrolmentplugin = $plugins[$ue->enrolmentinstance->enrol]; $users[$user->id]->enrolments[$ue->id] = $ue; } $rs->close(); return $users; } } /** * A button that is used to enrol users in a course * * @copyright 2010 Sam Hemelryk * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class enrol_user_button extends single_button { /** * An array containing JS YUI modules required by this button * @var array */ protected $jsyuimodules = array(); /** * An array containing JS initialisation calls required by this button * @var array */ protected $jsinitcalls = array(); /** * An array strings required by JS for this button * @var array */ protected $jsstrings = array(); /** * Initialises the new enrol_user_button * * @staticvar int $count The number of enrol user buttons already created * @param moodle_url $url * @param string $label The text to display in the button * @param string $method Either post or get */ public function __construct(moodle_url $url, $label, $method = 'post') { static $count = 0; $count ++; parent::__construct($url, $label, $method); $this->class = 'singlebutton enrolusersbutton'; $this->formid = 'enrolusersbutton-'.$count; } /** * Adds a YUI module call that will be added to the page when the button is used. * * @param string|array $modules One or more modules to require * @param string $function The JS function to call * @param array $arguments An array of arguments to pass to the function * @param string $galleryversion Deprecated: The gallery version to use * @param bool $ondomready If true the call is postponed until the DOM is finished loading */ public function require_yui_module($modules, $function, array $arguments = null, $galleryversion = null, $ondomready = false) { if ($galleryversion != null) { debugging('The galleryversion parameter to yui_module has been deprecated since Moodle 2.3.', DEBUG_DEVELOPER); } $js = new stdClass; $js->modules = (array)$modules; $js->function = $function; $js->arguments = $arguments; $js->ondomready = $ondomready; $this->jsyuimodules[] = $js; } /** * Adds a JS initialisation call to the page when the button is used. * * @param string $function The function to call * @param array $extraarguments An array of arguments to pass to the function * @param bool $ondomready If true the call is postponed until the DOM is finished loading * @param array $module A module definition */ public function require_js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) { $js = new stdClass; $js->function = $function; $js->extraarguments = $extraarguments; $js->ondomready = $ondomready; $js->module = $module; $this->jsinitcalls[] = $js; } /** * Requires strings for JS that will be loaded when the button is used. * * @param type $identifiers * @param string $component * @param mixed $a */ public function strings_for_js($identifiers, $component = 'moodle', $a = null) { $string = new stdClass; $string->identifiers = (array)$identifiers; $string->component = $component; $string->a = $a; $this->jsstrings[] = $string; } /** * Initialises the JS that is required by this button * * @param moodle_page $page */ public function initialise_js(moodle_page $page) { foreach ($this->jsyuimodules as $js) { $page->requires->yui_module($js->modules, $js->function, $js->arguments, null, $js->ondomready); } foreach ($this->jsinitcalls as $js) { $page->requires->js_init_call($js->function, $js->extraarguments, $js->ondomready, $js->module); } foreach ($this->jsstrings as $string) { $page->requires->strings_for_js($string->identifiers, $string->component, $string->a); } } } /** * User enrolment action * * This class is used to manage a renderable ue action such as editing an user enrolment or deleting * a user enrolment. * * @copyright 2011 Sam Hemelryk * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class user_enrolment_action implements renderable { /** * The icon to display for the action * @var pix_icon */ protected $icon; /** * The title for the action * @var string */ protected $title; /** * The URL to the action * @var moodle_url */ protected $url; /** * An array of HTML attributes * @var array */ protected $attributes = array(); /** * Constructor * @param pix_icon $icon * @param string $title * @param moodle_url $url * @param array $attributes */ public function __construct(pix_icon $icon, $title, $url, array $attributes = null) { $this->icon = $icon; $this->title = $title; $this->url = new moodle_url($url); if (!empty($attributes)) { $this->attributes = $attributes; } $this->attributes['title'] = $title; } /** * Returns the icon for this action * @return pix_icon */ public function get_icon() { return $this->icon; } /** * Returns the title for this action * @return string */ public function get_title() { return $this->title; } /** * Returns the URL for this action * @return moodle_url */ public function get_url() { return $this->url; } /** * Returns the attributes to use for this action * @return array */ public function get_attributes() { return $this->attributes; } } class enrol_ajax_exception extends moodle_exception { /** * Constructor * @param string $errorcode The name of the string from error.php to print * @param string $module name of module * @param string $link The url where the user will be prompted to continue. If no url is provided the user will be directed to the site index page. * @param object $a Extra words and phrases that might be required in the error string * @param string $debuginfo optional debugging information */ public function __construct($errorcode, $link = '', $a = NULL, $debuginfo = null) { parent::__construct($errorcode, 'enrol', $link, $a, $debuginfo); } } /** * This class is used to manage a bulk operations for enrolment plugins. * * @copyright 2011 Sam Hemelryk * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ abstract class enrol_bulk_enrolment_operation { /** * The course enrolment manager * @var course_enrolment_manager */ protected $manager; /** * The enrolment plugin to which this operation belongs * @var enrol_plugin */ protected $plugin; /** * Contructor * @param course_enrolment_manager $manager * @param stdClass $plugin */ public function __construct(course_enrolment_manager $manager, enrol_plugin $plugin = null) { $this->manager = $manager; $this->plugin = $plugin; } /** * Returns a moodleform used for this operation, or false if no form is required and the action * should be immediatly processed. * * @param moodle_url|string $defaultaction * @param mixed $defaultcustomdata * @return enrol_bulk_enrolment_change_form|moodleform|false */ public function get_form($defaultaction = null, $defaultcustomdata = null) { return false; } /** * Returns the title to use for this bulk operation * * @return string */ abstract public function get_title(); /** * Returns the identifier for this bulk operation. * This should be the same identifier used by the plugins function when returning * all of its bulk operations. * * @return string */ abstract public function get_identifier(); /** * Processes the bulk operation on the given users * * @param course_enrolment_manager $manager * @param array $users * @param stdClass $properties */ abstract public function process(course_enrolment_manager $manager, array $users, stdClass $properties); } home/harasnat/www/learning/mod/workshop/locallib.php 0000604 00000571737 15062255324 0016671 0 ustar 00 <?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Library of internal classes and functions for module workshop * * All the workshop specific functions, needed to implement the module * logic, should go to here. Instead of having bunch of function named * workshop_something() taking the workshop instance as the first * parameter, we use a class workshop that provides all methods. * * @package mod_workshop * @copyright 2009 David Mudrak <david.mudrak@gmail.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); require_once(__DIR__.'/lib.php'); // we extend this library here require_once($CFG->libdir . '/gradelib.php'); // we use some rounding and comparing routines here require_once($CFG->libdir . '/filelib.php'); /** * Full-featured workshop API * * This wraps the workshop database record with a set of methods that are called * from the module itself. The class should be initialized right after you get * $workshop, $cm and $course records at the begining of the script. */ class workshop { /** error status of the {@link self::add_allocation()} */ const ALLOCATION_EXISTS = -9999; /** the internal code of the workshop phases as are stored in the database */ const PHASE_SETUP = 10; const PHASE_SUBMISSION = 20; const PHASE_ASSESSMENT = 30; const PHASE_EVALUATION = 40; const PHASE_CLOSED = 50; /** the internal code of the examples modes as are stored in the database */ const EXAMPLES_VOLUNTARY = 0; const EXAMPLES_BEFORE_SUBMISSION = 1; const EXAMPLES_BEFORE_ASSESSMENT = 2; /** @var stdclass workshop record from database */ public $dbrecord; /** @var cm_info course module record */ public $cm; /** @var stdclass course record */ public $course; /** @var stdclass context object */ public $context; /** @var int workshop instance identifier */ public $id; /** @var string workshop activity name */ public $name; /** @var string introduction or description of the activity */ public $intro; /** @var int format of the {@link $intro} */ public $introformat; /** @var string instructions for the submission phase */ public $instructauthors; /** @var int format of the {@link $instructauthors} */ public $instructauthorsformat; /** @var string instructions for the assessment phase */ public $instructreviewers; /** @var int format of the {@link $instructreviewers} */ public $instructreviewersformat; /** @var int timestamp of when the module was modified */ public $timemodified; /** @var int current phase of workshop, for example {@link workshop::PHASE_SETUP} */ public $phase; /** @var bool optional feature: students practise evaluating on example submissions from teacher */ public $useexamples; /** @var bool optional feature: students perform peer assessment of others' work (deprecated, consider always enabled) */ public $usepeerassessment; /** @var bool optional feature: students perform self assessment of their own work */ public $useselfassessment; /** @var float number (10, 5) unsigned, the maximum grade for submission */ public $grade; /** @var float number (10, 5) unsigned, the maximum grade for assessment */ public $gradinggrade; /** @var string type of the current grading strategy used in this workshop, for example 'accumulative' */ public $strategy; /** @var string the name of the evaluation plugin to use for grading grades calculation */ public $evaluation; /** @var int number of digits that should be shown after the decimal point when displaying grades */ public $gradedecimals; /** @var int number of allowed submission attachments and the files embedded into submission */ public $nattachments; /** @var string list of allowed file types that are allowed to be embedded into submission */ public $submissionfiletypes = null; /** @var bool allow submitting the work after the deadline */ public $latesubmissions; /** @var int maximum size of the one attached file in bytes */ public $maxbytes; /** @var int mode of example submissions support, for example {@link workshop::EXAMPLES_VOLUNTARY} */ public $examplesmode; /** @var int if greater than 0 then the submission is not allowed before this timestamp */ public $submissionstart; /** @var int if greater than 0 then the submission is not allowed after this timestamp */ public $submissionend; /** @var int if greater than 0 then the peer assessment is not allowed before this timestamp */ public $assessmentstart; /** @var int if greater than 0 then the peer assessment is not allowed after this timestamp */ public $assessmentend; /** @var bool automatically switch to the assessment phase after the submissions deadline */ public $phaseswitchassessment; /** @var string conclusion text to be displayed at the end of the activity */ public $conclusion; /** @var int format of the conclusion text */ public $conclusionformat; /** @var int the mode of the overall feedback */ public $overallfeedbackmode; /** @var int maximum number of overall feedback attachments */ public $overallfeedbackfiles; /** @var string list of allowed file types that can be attached to the overall feedback */ public $overallfeedbackfiletypes = null; /** @var int maximum size of one file attached to the overall feedback */ public $overallfeedbackmaxbytes; /** @var int Should the submission form show the text field? */ public $submissiontypetext; /** @var int Should the submission form show the file attachment field? */ public $submissiontypefile; /** * @var workshop_strategy grading strategy instance * Do not use directly, get the instance using {@link workshop::grading_strategy_instance()} */ protected $strategyinstance = null; /** * @var workshop_evaluation grading evaluation instance * Do not use directly, get the instance using {@link workshop::grading_evaluation_instance()} */ protected $evaluationinstance = null; /** * @var array It gets initialised in init_initial_bar, and may have keys 'i_first' and 'i_last' depending on what is selected. */ protected $initialbarprefs = []; /** * Initializes the workshop API instance using the data from DB * * Makes deep copy of all passed records properties. * * For unit testing only, $cm and $course may be set to null. This is so that * you can test without having any real database objects if you like. Not all * functions will work in this situation. * * @param stdClass $dbrecord Workshop instance data from {workshop} table * @param stdClass|cm_info $cm Course module record * @param stdClass $course Course record from {course} table * @param stdClass $context The context of the workshop instance */ public function __construct(stdclass $dbrecord, $cm, $course, stdclass $context=null) { $this->dbrecord = $dbrecord; foreach ($this->dbrecord as $field => $value) { if (property_exists('workshop', $field)) { $this->{$field} = $value; } } if (is_null($cm) || is_null($course)) { throw new coding_exception('Must specify $cm and $course'); } $this->course = $course; if ($cm instanceof cm_info) { $this->cm = $cm; } else { $modinfo = get_fast_modinfo($course); $this->cm = $modinfo->get_cm($cm->id); } if (is_null($context)) { $this->context = context_module::instance($this->cm->id); } else { $this->context = $context; } } //////////////////////////////////////////////////////////////////////////////// // Static methods // //////////////////////////////////////////////////////////////////////////////// /** * Return list of available allocation methods * * @return array Array ['string' => 'string'] of localized allocation method names */ public static function installed_allocators() { $installed = core_component::get_plugin_list('workshopallocation'); $forms = array(); foreach ($installed as $allocation => $allocationpath) { if (file_exists($allocationpath . '/lib.php')) { $forms[$allocation] = get_string('pluginname', 'workshopallocation_' . $allocation); } } // usability - make sure that manual allocation appears the first if (isset($forms['manual'])) { $m = array('manual' => $forms['manual']); unset($forms['manual']); $forms = array_merge($m, $forms); } return $forms; } /** * Returns an array of options for the editors that are used for submitting and assessing instructions * * @param stdClass $context * @uses EDITOR_UNLIMITED_FILES hard-coded value for the 'maxfiles' option * @return array */ public static function instruction_editors_options(stdclass $context) { return array('subdirs' => 1, 'maxbytes' => 0, 'maxfiles' => -1, 'changeformat' => 1, 'context' => $context, 'noclean' => 1, 'trusttext' => 0); } /** * Given the percent and the total, returns the number * * @param float $percent from 0 to 100 * @param float $total the 100% value * @return float */ public static function percent_to_value($percent, $total) { if ($percent < 0 or $percent > 100) { throw new coding_exception('The percent can not be less than 0 or higher than 100'); } return $total * $percent / 100; } /** * Returns an array of numeric values that can be used as maximum grades * * @return array Array of integers */ public static function available_maxgrades_list() { $grades = array(); for ($i=100; $i>=0; $i--) { $grades[$i] = $i; } return $grades; } /** * Returns the localized list of supported examples modes * * @return array */ public static function available_example_modes_list() { $options = array(); $options[self::EXAMPLES_VOLUNTARY] = get_string('examplesvoluntary', 'workshop'); $options[self::EXAMPLES_BEFORE_SUBMISSION] = get_string('examplesbeforesubmission', 'workshop'); $options[self::EXAMPLES_BEFORE_ASSESSMENT] = get_string('examplesbeforeassessment', 'workshop'); return $options; } /** * Returns the list of available grading strategy methods * * @return array ['string' => 'string'] */ public static function available_strategies_list() { $installed = core_component::get_plugin_list('workshopform'); $forms = array(); foreach ($installed as $strategy => $strategypath) { if (file_exists($strategypath . '/lib.php')) { $forms[$strategy] = get_string('pluginname', 'workshopform_' . $strategy); } } return $forms; } /** * Returns the list of available grading evaluation methods * * @return array of (string)name => (string)localized title */ public static function available_evaluators_list() { $evals = array(); foreach (core_component::get_plugin_list_with_file('workshopeval', 'lib.php', false) as $eval => $evalpath) { $evals[$eval] = get_string('pluginname', 'workshopeval_' . $eval); } return $evals; } /** * Return an array of possible values of assessment dimension weight * * @return array of integers 0, 1, 2, ..., 16 */ public static function available_dimension_weights_list() { $weights = array(); for ($i=16; $i>=0; $i--) { $weights[$i] = $i; } return $weights; } /** * Return an array of possible values of assessment weight * * Note there is no real reason why the maximum value here is 16. It used to be 10 in * workshop 1.x and I just decided to use the same number as in the maximum weight of * a single assessment dimension. * The value looks reasonable, though. Teachers who would want to assign themselves * higher weight probably do not want peer assessment really... * * @return array of integers 0, 1, 2, ..., 16 */ public static function available_assessment_weights_list() { $weights = array(); for ($i=16; $i>=0; $i--) { $weights[$i] = $i; } return $weights; } /** * Helper function returning the greatest common divisor * * @param int $a * @param int $b * @return int */ public static function gcd($a, $b) { return ($b == 0) ? ($a):(self::gcd($b, $a % $b)); } /** * Helper function returning the least common multiple * * @param int $a * @param int $b * @return int */ public static function lcm($a, $b) { return ($a / self::gcd($a,$b)) * $b; } /** * Returns an object suitable for strings containing dates/times * * The returned object contains properties date, datefullshort, datetime, ... containing the given * timestamp formatted using strftimedate, strftimedatefullshort, strftimedatetime, ... from the * current lang's langconfig.php * This allows translators and administrators customize the date/time format. * * @param int $timestamp the timestamp in UTC * @return stdclass */ public static function timestamp_formats($timestamp) { $formats = array('date', 'datefullshort', 'dateshort', 'datetime', 'datetimeshort', 'daydate', 'daydatetime', 'dayshort', 'daytime', 'monthyear', 'recent', 'recentfull', 'time'); $a = new stdclass(); foreach ($formats as $format) { $a->{$format} = userdate($timestamp, get_string('strftime'.$format, 'langconfig')); } $day = userdate($timestamp, '%Y%m%d', 99, false); $today = userdate(time(), '%Y%m%d', 99, false); $tomorrow = userdate(time() + DAYSECS, '%Y%m%d', 99, false); $yesterday = userdate(time() - DAYSECS, '%Y%m%d', 99, false); $distance = (int)round(abs(time() - $timestamp) / DAYSECS); if ($day == $today) { $a->distanceday = get_string('daystoday', 'workshop'); } elseif ($day == $yesterday) { $a->distanceday = get_string('daysyesterday', 'workshop'); } elseif ($day < $today) { $a->distanceday = get_string('daysago', 'workshop', $distance); } elseif ($day == $tomorrow) { $a->distanceday = get_string('daystomorrow', 'workshop'); } elseif ($day > $today) { $a->distanceday = get_string('daysleft', 'workshop', $distance); } return $a; } /** * Converts the argument into an array (list) of file extensions. * * The list can be separated by whitespace, end of lines, commas colons and semicolons. * Empty values are not returned. Values are converted to lowercase. * Duplicates are removed. Glob evaluation is not supported. * * @deprecated since Moodle 3.4 MDL-56486 - please use the {@link core_form\filetypes_util} * @param string|array $extensions list of file extensions * @return array of strings */ public static function normalize_file_extensions($extensions) { debugging('The method workshop::normalize_file_extensions() is deprecated. Please use the methods provided by the \core_form\filetypes_util class.', DEBUG_DEVELOPER); if ($extensions === '') { return array(); } if (!is_array($extensions)) { $extensions = preg_split('/[\s,;:"\']+/', $extensions, -1, PREG_SPLIT_NO_EMPTY); } foreach ($extensions as $i => $extension) { $extension = str_replace('*.', '', $extension); $extension = strtolower($extension); $extension = ltrim($extension, '.'); $extension = trim($extension); $extensions[$i] = $extension; } foreach ($extensions as $i => $extension) { if (strpos($extension, '*') !== false or strpos($extension, '?') !== false) { unset($extensions[$i]); } } $extensions = array_filter($extensions, 'strlen'); $extensions = array_keys(array_flip($extensions)); foreach ($extensions as $i => $extension) { $extensions[$i] = '.'.$extension; } return $extensions; } /** * Cleans the user provided list of file extensions. * * @deprecated since Moodle 3.4 MDL-56486 - please use the {@link core_form\filetypes_util} * @param string $extensions * @return string */ public static function clean_file_extensions($extensions) { debugging('The method workshop::clean_file_extensions() is deprecated. Please use the methods provided by the \core_form\filetypes_util class.', DEBUG_DEVELOPER); $extensions = self::normalize_file_extensions($extensions); foreach ($extensions as $i => $extension) { $extensions[$i] = ltrim($extension, '.'); } return implode(', ', $extensions); } /** * Check given file types and return invalid/unknown ones. * * Empty allowlist is interpretted as "any extension is valid". * * @deprecated since Moodle 3.4 MDL-56486 - please use the {@link core_form\filetypes_util} * @param string|array $extensions list of file extensions * @param string|array $allowlist list of valid extensions * @return array list of invalid extensions not found in the allowlist */ public static function invalid_file_extensions($extensions, $allowlist) { debugging('The method workshop::invalid_file_extensions() is deprecated. Please use the methods provided by the \core_form\filetypes_util class.', DEBUG_DEVELOPER); $extensions = self::normalize_file_extensions($extensions); $allowlist = self::normalize_file_extensions($allowlist); if (empty($extensions) or empty($allowlist)) { return array(); } // Return those items from $extensions that are not present in $allowlist. return array_keys(array_diff_key(array_flip($extensions), array_flip($allowlist))); } /** * Is the file have allowed to be uploaded to the workshop? * * Empty allowlist is interpretted as "any file type is allowed" rather * than "no file can be uploaded". * * @deprecated since Moodle 3.4 MDL-56486 - please use the {@link core_form\filetypes_util} * @param string $filename the file name * @param string|array $allowlist list of allowed file extensions * @return false */ public static function is_allowed_file_type($filename, $allowlist) { debugging('The method workshop::is_allowed_file_type() is deprecated. Please use the methods provided by the \core_form\filetypes_util class.', DEBUG_DEVELOPER); $allowlist = self::normalize_file_extensions($allowlist); if (empty($allowlist)) { return true; } $haystack = strrev(trim(strtolower($filename))); foreach ($allowlist as $extension) { if (strpos($haystack, strrev($extension)) === 0) { // The file name ends with the extension. return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// // Workshop API // //////////////////////////////////////////////////////////////////////////////// /** * Fetches all enrolled users with the capability mod/workshop:submit in the current workshop * * The returned objects contain properties required by user_picture and are ordered by lastname, firstname. * Only users with the active enrolment are returned. * * @param bool $musthavesubmission if true, return only users who have already submitted * @param int $groupid 0 means ignore groups, any other value limits the result by group id * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set) * @param int $limitnum return a subset containing this number of records (optional, required if $limitfrom is set) * @return array array[userid] => stdClass */ public function get_potential_authors($musthavesubmission=true, $groupid=0, $limitfrom=0, $limitnum=0) { global $DB; list($sql, $params) = $this->get_users_with_capability_sql('mod/workshop:submit', $musthavesubmission, $groupid); if (empty($sql)) { return array(); } list($sort, $sortparams) = users_order_by_sql('tmp'); $sql = "SELECT * FROM ($sql) tmp ORDER BY $sort"; return $DB->get_records_sql($sql, array_merge($params, $sortparams), $limitfrom, $limitnum); } /** * Returns the total number of users that would be fetched by {@link self::get_potential_authors()} * * @param bool $musthavesubmission if true, count only users who have already submitted * @param int $groupid 0 means ignore groups, any other value limits the result by group id * @return int */ public function count_potential_authors($musthavesubmission=true, $groupid=0) { global $DB; list($sql, $params) = $this->get_users_with_capability_sql('mod/workshop:submit', $musthavesubmission, $groupid); if (empty($sql)) { return 0; } $sql = "SELECT COUNT(*) FROM ($sql) tmp"; return $DB->count_records_sql($sql, $params); } /** * Fetches all enrolled users with the capability mod/workshop:peerassess in the current workshop * * The returned objects contain properties required by user_picture and are ordered by lastname, firstname. * Only users with the active enrolment are returned. * * @param bool $musthavesubmission if true, return only users who have already submitted * @param int $groupid 0 means ignore groups, any other value limits the result by group id * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set) * @param int $limitnum return a subset containing this number of records (optional, required if $limitfrom is set) * @return array array[userid] => stdClass */ public function get_potential_reviewers($musthavesubmission=false, $groupid=0, $limitfrom=0, $limitnum=0) { global $DB; list($sql, $params) = $this->get_users_with_capability_sql('mod/workshop:peerassess', $musthavesubmission, $groupid); if (empty($sql)) { return array(); } list($sort, $sortparams) = users_order_by_sql('tmp'); $sql = "SELECT * FROM ($sql) tmp ORDER BY $sort"; return $DB->get_records_sql($sql, array_merge($params, $sortparams), $limitfrom, $limitnum); } /** * Returns the total number of users that would be fetched by {@link self::get_potential_reviewers()} * * @param bool $musthavesubmission if true, count only users who have already submitted * @param int $groupid 0 means ignore groups, any other value limits the result by group id * @return int */ public function count_potential_reviewers($musthavesubmission=false, $groupid=0) { global $DB; list($sql, $params) = $this->get_users_with_capability_sql('mod/workshop:peerassess', $musthavesubmission, $groupid); if (empty($sql)) { return 0; } $sql = "SELECT COUNT(*) FROM ($sql) tmp"; return $DB->count_records_sql($sql, $params); } /** * Fetches all enrolled users that are authors or reviewers (or both) in the current workshop * * The returned objects contain properties required by user_picture and are ordered by lastname, firstname. * Only users with the active enrolment are returned. * * @see self::get_potential_authors() * @see self::get_potential_reviewers() * @param bool $musthavesubmission if true, return only users who have already submitted * @param int $groupid 0 means ignore groups, any other value limits the result by group id * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set) * @param int $limitnum return a subset containing this number of records (optional, required if $limitfrom is set) * @return array array[userid] => stdClass */ public function get_participants($musthavesubmission=false, $groupid=0, $limitfrom=0, $limitnum=0) { global $DB; list($sql, $params) = $this->get_participants_sql($musthavesubmission, $groupid); list($filteringsql, $filteringparams) = $this->get_users_with_initial_filtering_sql_where(); $wheresql = ""; if ($filteringsql) { $wheresql .= $filteringsql; $params = array_merge($params, $filteringparams); } if (empty($sql)) { return array(); } list($sort, $sortparams) = users_order_by_sql('tmp'); $sql = "SELECT * FROM ($sql) tmp"; if ($wheresql) { $sql .= " WHERE $wheresql"; } $sql .= " ORDER BY $sort"; return $DB->get_records_sql($sql, array_merge($params, $sortparams), $limitfrom, $limitnum); } /** * Returns the total number of records that would be returned by {@link self::get_participants()} * * @param bool $musthavesubmission if true, return only users who have already submitted * @param int $groupid 0 means ignore groups, any other value limits the result by group id * @return int */ public function count_participants($musthavesubmission=false, $groupid=0) { global $DB; list($sql, $params) = $this->get_participants_sql($musthavesubmission, $groupid); if (empty($sql)) { return 0; } $sql = "SELECT COUNT(*) FROM ($sql) tmp"; return $DB->count_records_sql($sql, $params); } /** * Checks if the given user is an actively enrolled participant in the workshop * * @param int $userid, defaults to the current $USER * @return boolean */ public function is_participant($userid=null) { global $USER, $DB; if (is_null($userid)) { $userid = $USER->id; } list($sql, $params) = $this->get_participants_sql(); if (empty($sql)) { return false; } $sql = "SELECT COUNT(*) FROM {user} uxx JOIN ({$sql}) pxx ON uxx.id = pxx.id WHERE uxx.id = :uxxid"; $params['uxxid'] = $userid; if ($DB->count_records_sql($sql, $params)) { return true; } return false; } /** * Groups the given users by the group membership * * This takes the module grouping settings into account. If a grouping is * set, returns only groups withing the course module grouping. Always * returns group [0] with all the given users. * * @param array $users array[userid] => stdclass{->id ->lastname ->firstname} * @return array array[groupid][userid] => stdclass{->id ->lastname ->firstname} */ public function get_grouped($users) { global $DB; global $CFG; $grouped = array(); // grouped users to be returned if (empty($users)) { return $grouped; } if ($this->cm->groupingid) { // Group workshop set to specified grouping - only consider groups // within this grouping, and leave out users who aren't members of // this grouping. $groupingid = $this->cm->groupingid; // All users that are members of at least one group will be // added into a virtual group id 0 $grouped[0] = array(); } else { $groupingid = 0; // there is no need to be member of a group so $grouped[0] will contain // all users $grouped[0] = $users; } $gmemberships = groups_get_all_groups($this->cm->course, array_keys($users), $groupingid, 'gm.id,gm.groupid,gm.userid'); foreach ($gmemberships as $gmembership) { if (!isset($grouped[$gmembership->groupid])) { $grouped[$gmembership->groupid] = array(); } $grouped[$gmembership->groupid][$gmembership->userid] = $users[$gmembership->userid]; $grouped[0][$gmembership->userid] = $users[$gmembership->userid]; } return $grouped; } /** * Returns the list of all allocations (i.e. assigned assessments) in the workshop * * Assessments of example submissions are ignored * * @return array */ public function get_allocations() { global $DB; $sql = 'SELECT a.id, a.submissionid, a.reviewerid, s.authorid FROM {workshop_assessments} a INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id) WHERE s.example = 0 AND s.workshopid = :workshopid'; $params = array('workshopid' => $this->id); return $DB->get_records_sql($sql, $params); } /** * Returns the total number of records that would be returned by {@link self::get_submissions()} * * @param mixed $authorid int|array|'all' If set to [array of] integer, return submission[s] of the given user[s] only * @param int $groupid If non-zero, return only submissions by authors in the specified group * @return int number of records */ public function count_submissions($authorid='all', $groupid=0) { global $DB; $params = array('workshopid' => $this->id); $sql = "SELECT COUNT(s.id) FROM {workshop_submissions} s JOIN {user} u ON (s.authorid = u.id)"; if ($groupid) { $sql .= " JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = :groupid)"; $params['groupid'] = $groupid; } $sql .= " WHERE s.example = 0 AND s.workshopid = :workshopid"; if ('all' === $authorid) { // no additional conditions } elseif (!empty($authorid)) { list($usql, $uparams) = $DB->get_in_or_equal($authorid, SQL_PARAMS_NAMED); $sql .= " AND authorid $usql"; $params = array_merge($params, $uparams); } else { // $authorid is empty return 0; } return $DB->count_records_sql($sql, $params); } /** * Returns submissions from this workshop * * Fetches data from {workshop_submissions} and adds some useful information from other * tables. Does not return textual fields to prevent possible memory lack issues. * * @see self::count_submissions() * @param mixed $authorid int|array|'all' If set to [array of] integer, return submission[s] of the given user[s] only * @param int $groupid If non-zero, return only submissions by authors in the specified group * @param int $limitfrom Return a subset of records, starting at this point (optional) * @param int $limitnum Return a subset containing this many records in total (optional, required if $limitfrom is set) * @return array of records or an empty array */ public function get_submissions($authorid='all', $groupid=0, $limitfrom=0, $limitnum=0) { global $DB; $userfieldsapi = \core_user\fields::for_userpic(); $authorfields = $userfieldsapi->get_sql('u', false, 'author', 'authoridx', false)->selects; $gradeoverbyfields = $userfieldsapi->get_sql('t', false, 'over', 'gradeoverbyx', false)->selects; $params = array('workshopid' => $this->id); $sql = "SELECT s.id, s.workshopid, s.example, s.authorid, s.timecreated, s.timemodified, s.title, s.grade, s.gradeover, s.gradeoverby, s.published, $authorfields, $gradeoverbyfields FROM {workshop_submissions} s JOIN {user} u ON (s.authorid = u.id)"; if ($groupid) { $sql .= " JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = :groupid)"; $params['groupid'] = $groupid; } $sql .= " LEFT JOIN {user} t ON (s.gradeoverby = t.id) WHERE s.example = 0 AND s.workshopid = :workshopid"; if ('all' === $authorid) { // no additional conditions } elseif (!empty($authorid)) { list($usql, $uparams) = $DB->get_in_or_equal($authorid, SQL_PARAMS_NAMED); $sql .= " AND authorid $usql"; $params = array_merge($params, $uparams); } else { // $authorid is empty return array(); } list($sort, $sortparams) = users_order_by_sql('u'); $sql .= " ORDER BY $sort"; return $DB->get_records_sql($sql, array_merge($params, $sortparams), $limitfrom, $limitnum); } /** * Returns submissions from this workshop that are viewable by the current user (except example submissions). * * @param mixed $authorid int|array If set to [array of] integer, return submission[s] of the given user[s] only * @param int $groupid If non-zero, return only submissions by authors in the specified group. 0 for all groups. * @param int $limitfrom Return a subset of records, starting at this point (optional) * @param int $limitnum Return a subset containing this many records in total (optional, required if $limitfrom is set) * @return array of records and the total submissions count * @since Moodle 3.4 */ public function get_visible_submissions($authorid = 0, $groupid = 0, $limitfrom = 0, $limitnum = 0) { global $DB, $USER; $submissions = array(); $select = "SELECT s.*"; $selectcount = "SELECT COUNT(s.id)"; $from = " FROM {workshop_submissions} s"; $params = array('workshopid' => $this->id); // Check if the passed group (or all groups when groupid is 0) is visible by the current user. if (!groups_group_visible($groupid, $this->course, $this->cm)) { return array($submissions, 0); } if ($groupid) { $from .= " JOIN {groups_members} gm ON (gm.userid = s.authorid AND gm.groupid = :groupid)"; $params['groupid'] = $groupid; } $where = " WHERE s.workshopid = :workshopid AND s.example = 0"; if (!has_capability('mod/workshop:viewallsubmissions', $this->context)) { // Check published submissions. $workshopclosed = $this->phase == self::PHASE_CLOSED; $canviewpublished = has_capability('mod/workshop:viewpublishedsubmissions', $this->context); if ($workshopclosed && $canviewpublished) { $published = " OR s.published = 1"; } else { $published = ''; } // Always get submissions I did or I provided feedback to. $where .= " AND (s.authorid = :authorid OR s.gradeoverby = :graderid $published)"; $params['authorid'] = $USER->id; $params['graderid'] = $USER->id; } // Now, user filtering. if (!empty($authorid)) { list($usql, $uparams) = $DB->get_in_or_equal($authorid, SQL_PARAMS_NAMED); $where .= " AND s.authorid $usql"; $params = array_merge($params, $uparams); } $order = " ORDER BY s.timecreated"; $totalcount = $DB->count_records_sql($selectcount.$from.$where, $params); if ($totalcount) { $submissions = $DB->get_records_sql($select.$from.$where.$order, $params, $limitfrom, $limitnum); } return array($submissions, $totalcount); } /** * Returns a submission record with the author's data * * @param int $id submission id * @return stdclass */ public function get_submission_by_id($id) { global $DB; // we intentionally check the workshopid here, too, so the workshop can't touch submissions // from other instances $userfieldsapi = \core_user\fields::for_userpic(); $authorfields = $userfieldsapi->get_sql('u', false, 'author', 'authoridx', false)->selects; $gradeoverbyfields = $userfieldsapi->get_sql('g', false, 'gradeoverby', 'gradeoverbyx', false)->selects; $sql = "SELECT s.*, $authorfields, $gradeoverbyfields FROM {workshop_submissions} s INNER JOIN {user} u ON (s.authorid = u.id) LEFT JOIN {user} g ON (s.gradeoverby = g.id) WHERE s.example = 0 AND s.workshopid = :workshopid AND s.id = :id"; $params = array('workshopid' => $this->id, 'id' => $id); return $DB->get_record_sql($sql, $params, MUST_EXIST); } /** * Returns a submission submitted by the given author * * @param int $id author id * @return stdclass|false */ public function get_submission_by_author($authorid) { global $DB; if (empty($authorid)) { return false; } $userfieldsapi = \core_user\fields::for_userpic(); $authorfields = $userfieldsapi->get_sql('u', false, 'author', 'authoridx', false)->selects; $gradeoverbyfields = $userfieldsapi->get_sql('g', false, 'gradeoverby', 'gradeoverbyx', false)->selects; $sql = "SELECT s.*, $authorfields, $gradeoverbyfields FROM {workshop_submissions} s INNER JOIN {user} u ON (s.authorid = u.id) LEFT JOIN {user} g ON (s.gradeoverby = g.id) WHERE s.example = 0 AND s.workshopid = :workshopid AND s.authorid = :authorid"; $params = array('workshopid' => $this->id, 'authorid' => $authorid); return $DB->get_record_sql($sql, $params); } /** * Returns published submissions with their authors data * * @return array of stdclass */ public function get_published_submissions($orderby='finalgrade DESC') { global $DB; $userfieldsapi = \core_user\fields::for_userpic(); $authorfields = $userfieldsapi->get_sql('u', false, 'author', 'authoridx', false)->selects; $sql = "SELECT s.id, s.authorid, s.timecreated, s.timemodified, s.title, s.grade, s.gradeover, COALESCE(s.gradeover,s.grade) AS finalgrade, $authorfields FROM {workshop_submissions} s INNER JOIN {user} u ON (s.authorid = u.id) WHERE s.example = 0 AND s.workshopid = :workshopid AND s.published = 1 ORDER BY $orderby"; $params = array('workshopid' => $this->id); return $DB->get_records_sql($sql, $params); } /** * Returns full record of the given example submission * * @param int $id example submission od * @return object */ public function get_example_by_id($id) { global $DB; return $DB->get_record('workshop_submissions', array('id' => $id, 'workshopid' => $this->id, 'example' => 1), '*', MUST_EXIST); } /** * Returns the list of example submissions in this workshop with reference assessments attached * * @return array of objects or an empty array * @see workshop::prepare_example_summary() */ public function get_examples_for_manager() { global $DB; $sql = 'SELECT s.id, s.title, a.id AS assessmentid, a.grade, a.gradinggrade FROM {workshop_submissions} s LEFT JOIN {workshop_assessments} a ON (a.submissionid = s.id AND a.weight = 1) WHERE s.example = 1 AND s.workshopid = :workshopid ORDER BY s.title'; return $DB->get_records_sql($sql, array('workshopid' => $this->id)); } /** * Returns the list of all example submissions in this workshop with the information of assessments done by the given user * * @param int $reviewerid user id * @return array of objects, indexed by example submission id * @see workshop::prepare_example_summary() */ public function get_examples_for_reviewer($reviewerid) { global $DB; if (empty($reviewerid)) { return false; } $sql = 'SELECT s.id, s.title, a.id AS assessmentid, a.grade, a.gradinggrade FROM {workshop_submissions} s LEFT JOIN {workshop_assessments} a ON (a.submissionid = s.id AND a.reviewerid = :reviewerid AND a.weight = 0) WHERE s.example = 1 AND s.workshopid = :workshopid ORDER BY s.title'; return $DB->get_records_sql($sql, array('workshopid' => $this->id, 'reviewerid' => $reviewerid)); } /** * Prepares renderable submission component * * @param stdClass $record required by {@see workshop_submission} * @param bool $showauthor show the author-related information * @return workshop_submission */ public function prepare_submission(stdClass $record, $showauthor = false) { $submission = new workshop_submission($this, $record, $showauthor); $submission->url = $this->submission_url($record->id); return $submission; } /** * Prepares renderable submission summary component * * @param stdClass $record required by {@see workshop_submission_summary} * @param bool $showauthor show the author-related information * @return workshop_submission_summary */ public function prepare_submission_summary(stdClass $record, $showauthor = false) { $summary = new workshop_submission_summary($this, $record, $showauthor); $summary->url = $this->submission_url($record->id); return $summary; } /** * Prepares renderable example submission component * * @param stdClass $record required by {@see workshop_example_submission} * @return workshop_example_submission */ public function prepare_example_submission(stdClass $record) { $example = new workshop_example_submission($this, $record); return $example; } /** * Prepares renderable example submission summary component * * If the example is editable, the caller must set the 'editable' flag explicitly. * * @param stdClass $example as returned by {@link workshop::get_examples_for_manager()} or {@link workshop::get_examples_for_reviewer()} * @return workshop_example_submission_summary to be rendered */ public function prepare_example_summary(stdClass $example) { $summary = new workshop_example_submission_summary($this, $example); if (is_null($example->grade)) { $summary->status = 'notgraded'; $summary->assesslabel = get_string('assess', 'workshop'); } else { $summary->status = 'graded'; $summary->assesslabel = get_string('reassess', 'workshop'); } $summary->gradeinfo = new stdclass(); $summary->gradeinfo->received = $this->real_grade($example->grade); $summary->gradeinfo->max = $this->real_grade(100); $summary->url = new moodle_url($this->exsubmission_url($example->id)); $summary->editurl = new moodle_url($this->exsubmission_url($example->id), array('edit' => 'on')); $summary->assessurl = new moodle_url($this->exsubmission_url($example->id), array('assess' => 'on', 'sesskey' => sesskey())); return $summary; } /** * Prepares renderable assessment component * * The $options array supports the following keys: * showauthor - should the author user info be available for the renderer * showreviewer - should the reviewer user info be available for the renderer * showform - show the assessment form if it is available * showweight - should the assessment weight be available for the renderer * * @param stdClass $record as returned by eg {@link self::get_assessment_by_id()} * @param workshop_assessment_form|null $form as returned by {@link workshop_strategy::get_assessment_form()} * @param array $options * @return workshop_assessment */ public function prepare_assessment(stdClass $record, $form, array $options = array()) { $assessment = new workshop_assessment($this, $record, $options); $assessment->url = $this->assess_url($record->id); $assessment->maxgrade = $this->real_grade(100); if (!empty($options['showform']) and !($form instanceof workshop_assessment_form)) { debugging('Not a valid instance of workshop_assessment_form supplied', DEBUG_DEVELOPER); } if (!empty($options['showform']) and ($form instanceof workshop_assessment_form)) { $assessment->form = $form; } if (empty($options['showweight'])) { $assessment->weight = null; } if (!is_null($record->grade)) { $assessment->realgrade = $this->real_grade($record->grade); } return $assessment; } /** * Prepares renderable example submission's assessment component * * The $options array supports the following keys: * showauthor - should the author user info be available for the renderer * showreviewer - should the reviewer user info be available for the renderer * showform - show the assessment form if it is available * * @param stdClass $record as returned by eg {@link self::get_assessment_by_id()} * @param workshop_assessment_form|null $form as returned by {@link workshop_strategy::get_assessment_form()} * @param array $options * @return workshop_example_assessment */ public function prepare_example_assessment(stdClass $record, $form = null, array $options = array()) { $assessment = new workshop_example_assessment($this, $record, $options); $assessment->url = $this->exassess_url($record->id); $assessment->maxgrade = $this->real_grade(100); if (!empty($options['showform']) and !($form instanceof workshop_assessment_form)) { debugging('Not a valid instance of workshop_assessment_form supplied', DEBUG_DEVELOPER); } if (!empty($options['showform']) and ($form instanceof workshop_assessment_form)) { $assessment->form = $form; } if (!is_null($record->grade)) { $assessment->realgrade = $this->real_grade($record->grade); } $assessment->weight = null; return $assessment; } /** * Prepares renderable example submission's reference assessment component * * The $options array supports the following keys: * showauthor - should the author user info be available for the renderer * showreviewer - should the reviewer user info be available for the renderer * showform - show the assessment form if it is available * * @param stdClass $record as returned by eg {@link self::get_assessment_by_id()} * @param workshop_assessment_form|null $form as returned by {@link workshop_strategy::get_assessment_form()} * @param array $options * @return workshop_example_reference_assessment */ public function prepare_example_reference_assessment(stdClass $record, $form = null, array $options = array()) { $assessment = new workshop_example_reference_assessment($this, $record, $options); $assessment->maxgrade = $this->real_grade(100); if (!empty($options['showform']) and !($form instanceof workshop_assessment_form)) { debugging('Not a valid instance of workshop_assessment_form supplied', DEBUG_DEVELOPER); } if (!empty($options['showform']) and ($form instanceof workshop_assessment_form)) { $assessment->form = $form; } if (!is_null($record->grade)) { $assessment->realgrade = $this->real_grade($record->grade); } $assessment->weight = null; return $assessment; } /** * Removes the submission and all relevant data * * @param stdClass $submission record to delete * @return void */ public function delete_submission(stdclass $submission) { global $DB; $assessments = $DB->get_records('workshop_assessments', array('submissionid' => $submission->id), '', 'id'); $this->delete_assessment(array_keys($assessments)); $fs = get_file_storage(); $fs->delete_area_files($this->context->id, 'mod_workshop', 'submission_content', $submission->id); $fs->delete_area_files($this->context->id, 'mod_workshop', 'submission_attachment', $submission->id); $DB->delete_records('workshop_submissions', array('id' => $submission->id)); // Event information. $params = array( 'context' => $this->context, 'courseid' => $this->course->id, 'relateduserid' => $submission->authorid, 'other' => array( 'submissiontitle' => $submission->title ) ); $params['objectid'] = $submission->id; $event = \mod_workshop\event\submission_deleted::create($params); $event->add_record_snapshot('workshop', $this->dbrecord); $event->trigger(); } /** * Returns the list of all assessments in the workshop with some data added * * Fetches data from {workshop_assessments} and adds some useful information from other * tables. The returned object does not contain textual fields (i.e. comments) to prevent memory * lack issues. * * @return array [assessmentid] => assessment stdclass */ public function get_all_assessments() { global $DB; $userfieldsapi = \core_user\fields::for_userpic(); $reviewerfields = $userfieldsapi->get_sql('reviewer', false, '', 'revieweridx', false)->selects; $authorfields = $userfieldsapi->get_sql('author', false, 'author', 'authorid', false)->selects; $overbyfields = $userfieldsapi->get_sql('overby', false, 'overby', 'gradinggradeoverbyx', false)->selects; list($sort, $params) = users_order_by_sql('reviewer'); $sql = "SELECT a.id, a.submissionid, a.reviewerid, a.timecreated, a.timemodified, a.grade, a.gradinggrade, a.gradinggradeover, a.gradinggradeoverby, $reviewerfields, $authorfields, $overbyfields, s.title FROM {workshop_assessments} a INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id) INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id) INNER JOIN {user} author ON (s.authorid = author.id) LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id) WHERE s.workshopid = :workshopid AND s.example = 0 ORDER BY $sort"; $params['workshopid'] = $this->id; return $DB->get_records_sql($sql, $params); } /** * Get the complete information about the given assessment * * @param int $id Assessment ID * @return stdclass */ public function get_assessment_by_id($id) { global $DB; $userfieldsapi = \core_user\fields::for_userpic(); $reviewerfields = $userfieldsapi->get_sql('reviewer', false, 'reviewer', 'revieweridx', false)->selects; $authorfields = $userfieldsapi->get_sql('author', false, 'author', 'authorid', false)->selects; $overbyfields = $userfieldsapi->get_sql('overby', false, 'overby', 'gradinggradeoverbyx', false)->selects; $sql = "SELECT a.*, s.title, $reviewerfields, $authorfields, $overbyfields FROM {workshop_assessments} a INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id) INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id) INNER JOIN {user} author ON (s.authorid = author.id) LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id) WHERE a.id = :id AND s.workshopid = :workshopid"; $params = array('id' => $id, 'workshopid' => $this->id); return $DB->get_record_sql($sql, $params, MUST_EXIST); } /** * Get the complete information about the user's assessment of the given submission * * @param int $sid submission ID * @param int $uid user ID of the reviewer * @return false|stdclass false if not found, stdclass otherwise */ public function get_assessment_of_submission_by_user($submissionid, $reviewerid) { global $DB; $userfieldsapi = \core_user\fields::for_userpic(); $reviewerfields = $userfieldsapi->get_sql('reviewer', false, 'reviewer', 'revieweridx', false)->selects; $authorfields = $userfieldsapi->get_sql('author', false, 'author', 'authorid', false)->selects; $overbyfields = $userfieldsapi->get_sql('overby', false, 'overby', 'gradinggradeoverbyx', false)->selects; $sql = "SELECT a.*, s.title, $reviewerfields, $authorfields, $overbyfields FROM {workshop_assessments} a INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id) INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id AND s.example = 0) INNER JOIN {user} author ON (s.authorid = author.id) LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id) WHERE s.id = :sid AND reviewer.id = :rid AND s.workshopid = :workshopid"; $params = array('sid' => $submissionid, 'rid' => $reviewerid, 'workshopid' => $this->id); return $DB->get_record_sql($sql, $params, IGNORE_MISSING); } /** * Get the complete information about all assessments of the given submission * * @param int $submissionid * @return array */ public function get_assessments_of_submission($submissionid) { global $DB; $userfieldsapi = \core_user\fields::for_userpic(); $reviewerfields = $userfieldsapi->get_sql('reviewer', false, 'reviewer', 'revieweridx', false)->selects; $overbyfields = $userfieldsapi->get_sql('overby', false, 'overby', 'gradinggradeoverbyx', false)->selects; list($sort, $params) = users_order_by_sql('reviewer'); $sql = "SELECT a.*, s.title, $reviewerfields, $overbyfields FROM {workshop_assessments} a INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id) INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id) LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id) WHERE s.example = 0 AND s.id = :submissionid AND s.workshopid = :workshopid ORDER BY $sort"; $params['submissionid'] = $submissionid; $params['workshopid'] = $this->id; return $DB->get_records_sql($sql, $params); } /** * Get the complete information about all assessments allocated to the given reviewer * * @param int $reviewerid * @return array */ public function get_assessments_by_reviewer($reviewerid) { global $DB; $userfieldsapi = \core_user\fields::for_userpic(); $reviewerfields = $userfieldsapi->get_sql('reviewer', false, 'reviewer', 'revieweridx', false)->selects; $authorfields = $userfieldsapi->get_sql('author', false, 'author', 'authorid', false)->selects; $overbyfields = $userfieldsapi->get_sql('overby', false, 'overby', 'gradinggradeoverbyx', false)->selects; $sql = "SELECT a.*, $reviewerfields, $authorfields, $overbyfields, s.id AS submissionid, s.title AS submissiontitle, s.timecreated AS submissioncreated, s.timemodified AS submissionmodified FROM {workshop_assessments} a INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id) INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id) INNER JOIN {user} author ON (s.authorid = author.id) LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id) WHERE s.example = 0 AND reviewer.id = :reviewerid AND s.workshopid = :workshopid"; $params = array('reviewerid' => $reviewerid, 'workshopid' => $this->id); return $DB->get_records_sql($sql, $params); } /** * Get allocated assessments not graded yet by the given reviewer * * @see self::get_assessments_by_reviewer() * @param int $reviewerid the reviewer id * @param null|int|array $exclude optional assessment id (or list of them) to be excluded * @return array */ public function get_pending_assessments_by_reviewer($reviewerid, $exclude = null) { $assessments = $this->get_assessments_by_reviewer($reviewerid); foreach ($assessments as $id => $assessment) { if (!is_null($assessment->grade)) { unset($assessments[$id]); continue; } if (!empty($exclude)) { if (is_array($exclude) and in_array($id, $exclude)) { unset($assessments[$id]); continue; } else if ($id == $exclude) { unset($assessments[$id]); continue; } } } return $assessments; } /** * Allocate a submission to a user for review * * @param stdClass $submission Submission object with at least id property * @param int $reviewerid User ID * @param int $weight of the new assessment, from 0 to 16 * @param bool $bulk repeated inserts into DB expected * @return int ID of the new assessment or an error code {@link self::ALLOCATION_EXISTS} if the allocation already exists */ public function add_allocation(stdclass $submission, $reviewerid, $weight=1, $bulk=false) { global $DB; if ($DB->record_exists('workshop_assessments', array('submissionid' => $submission->id, 'reviewerid' => $reviewerid))) { return self::ALLOCATION_EXISTS; } $weight = (int)$weight; if ($weight < 0) { $weight = 0; } if ($weight > 16) { $weight = 16; } $now = time(); $assessment = new stdclass(); $assessment->submissionid = $submission->id; $assessment->reviewerid = $reviewerid; $assessment->timecreated = $now; // do not set timemodified here $assessment->weight = $weight; $assessment->feedbackauthorformat = editors_get_preferred_format(); $assessment->feedbackreviewerformat = editors_get_preferred_format(); return $DB->insert_record('workshop_assessments', $assessment, true, $bulk); } /** * Delete assessment record or records. * * Removes associated records from the workshop_grades table, too. * * @param int|array $id assessment id or array of assessments ids * @todo Give grading strategy plugins a chance to clean up their data, too. * @return bool true */ public function delete_assessment($id) { global $DB; if (empty($id)) { return true; } $fs = get_file_storage(); if (is_array($id)) { $DB->delete_records_list('workshop_grades', 'assessmentid', $id); foreach ($id as $itemid) { $fs->delete_area_files($this->context->id, 'mod_workshop', 'overallfeedback_content', $itemid); $fs->delete_area_files($this->context->id, 'mod_workshop', 'overallfeedback_attachment', $itemid); } $DB->delete_records_list('workshop_assessments', 'id', $id); } else { $DB->delete_records('workshop_grades', array('assessmentid' => $id)); $fs->delete_area_files($this->context->id, 'mod_workshop', 'overallfeedback_content', $id); $fs->delete_area_files($this->context->id, 'mod_workshop', 'overallfeedback_attachment', $id); $DB->delete_records('workshop_assessments', array('id' => $id)); } return true; } /** * Returns instance of grading strategy class * * @return stdclass Instance of a grading strategy */ public function grading_strategy_instance() { global $CFG; // because we require other libs here if (is_null($this->strategyinstance)) { $strategylib = __DIR__ . '/form/' . $this->strategy . '/lib.php'; if (is_readable($strategylib)) { require_once($strategylib); } else { throw new coding_exception('the grading forms subplugin must contain library ' . $strategylib); } $classname = 'workshop_' . $this->strategy . '_strategy'; $this->strategyinstance = new $classname($this); if (!in_array('workshop_strategy', class_implements($this->strategyinstance))) { throw new coding_exception($classname . ' does not implement workshop_strategy interface'); } } return $this->strategyinstance; } /** * Sets the current evaluation method to the given plugin. * * @param string $method the name of the workshopeval subplugin * @return bool true if successfully set * @throws coding_exception if attempting to set a non-installed evaluation method */ public function set_grading_evaluation_method($method) { global $DB; $evaluationlib = __DIR__ . '/eval/' . $method . '/lib.php'; if (is_readable($evaluationlib)) { $this->evaluationinstance = null; $this->evaluation = $method; $DB->set_field('workshop', 'evaluation', $method, array('id' => $this->id)); return true; } throw new coding_exception('Attempt to set a non-existing evaluation method.'); } /** * Returns instance of grading evaluation class * * @return stdclass Instance of a grading evaluation */ public function grading_evaluation_instance() { global $CFG; // because we require other libs here if (is_null($this->evaluationinstance)) { if (empty($this->evaluation)) { $this->evaluation = 'best'; } $evaluationlib = __DIR__ . '/eval/' . $this->evaluation . '/lib.php'; if (is_readable($evaluationlib)) { require_once($evaluationlib); } else { // Fall back in case the subplugin is not available. $this->evaluation = 'best'; $evaluationlib = __DIR__ . '/eval/' . $this->evaluation . '/lib.php'; if (is_readable($evaluationlib)) { require_once($evaluationlib); } else { // Fall back in case the subplugin is not available any more. throw new coding_exception('Missing default grading evaluation library ' . $evaluationlib); } } $classname = 'workshop_' . $this->evaluation . '_evaluation'; $this->evaluationinstance = new $classname($this); if (!in_array('workshop_evaluation', class_parents($this->evaluationinstance))) { throw new coding_exception($classname . ' does not extend workshop_evaluation class'); } } return $this->evaluationinstance; } /** * Returns instance of submissions allocator * * @param string $method The name of the allocation method, must be PARAM_ALPHA * @return stdclass Instance of submissions allocator */ public function allocator_instance($method) { global $CFG; // because we require other libs here $allocationlib = __DIR__ . '/allocation/' . $method . '/lib.php'; if (is_readable($allocationlib)) { require_once($allocationlib); } else { throw new coding_exception('Unable to find the allocation library ' . $allocationlib); } $classname = 'workshop_' . $method . '_allocator'; return new $classname($this); } /** * @return moodle_url of this workshop's view page */ public function view_url() { global $CFG; return new moodle_url('/mod/workshop/view.php', array('id' => $this->cm->id)); } /** * @return moodle_url of the page for editing this workshop's grading form */ public function editform_url() { global $CFG; return new moodle_url('/mod/workshop/editform.php', array('cmid' => $this->cm->id)); } /** * @return moodle_url of the page for previewing this workshop's grading form */ public function previewform_url() { global $CFG; return new moodle_url('/mod/workshop/editformpreview.php', array('cmid' => $this->cm->id)); } /** * @param int $assessmentid The ID of assessment record * @return moodle_url of the assessment page */ public function assess_url($assessmentid) { global $CFG; $assessmentid = clean_param($assessmentid, PARAM_INT); return new moodle_url('/mod/workshop/assessment.php', array('asid' => $assessmentid)); } /** * @param int $assessmentid The ID of assessment record * @return moodle_url of the example assessment page */ public function exassess_url($assessmentid) { global $CFG; $assessmentid = clean_param($assessmentid, PARAM_INT); return new moodle_url('/mod/workshop/exassessment.php', array('asid' => $assessmentid)); } /** * @return moodle_url of the page to view a submission, defaults to the own one */ public function submission_url($id=null) { global $CFG; return new moodle_url('/mod/workshop/submission.php', array('cmid' => $this->cm->id, 'id' => $id)); } /** * @param int $id example submission id * @return moodle_url of the page to view an example submission */ public function exsubmission_url($id) { global $CFG; return new moodle_url('/mod/workshop/exsubmission.php', array('cmid' => $this->cm->id, 'id' => $id)); } /** * @param int $sid submission id * @param array $aid of int assessment ids * @return moodle_url of the page to compare assessments of the given submission */ public function compare_url($sid, array $aids) { global $CFG; $url = new moodle_url('/mod/workshop/compare.php', array('cmid' => $this->cm->id, 'sid' => $sid)); $i = 0; foreach ($aids as $aid) { $url->param("aid{$i}", $aid); $i++; } return $url; } /** * @param int $sid submission id * @param int $aid assessment id * @return moodle_url of the page to compare the reference assessments of the given example submission */ public function excompare_url($sid, $aid) { global $CFG; return new moodle_url('/mod/workshop/excompare.php', array('cmid' => $this->cm->id, 'sid' => $sid, 'aid' => $aid)); } /** * @return moodle_url of the mod_edit form */ public function updatemod_url() { global $CFG; return new moodle_url('/course/modedit.php', array('update' => $this->cm->id, 'return' => 1)); } /** * @param string $method allocation method * @return moodle_url to the allocation page */ public function allocation_url($method=null) { global $CFG; $params = array('cmid' => $this->cm->id); if (!empty($method)) { $params['method'] = $method; } return new moodle_url('/mod/workshop/allocation.php', $params); } /** * @param int $phasecode The internal phase code * @return moodle_url of the script to change the current phase to $phasecode */ public function switchphase_url($phasecode) { global $CFG; $phasecode = clean_param($phasecode, PARAM_INT); return new moodle_url('/mod/workshop/switchphase.php', array('cmid' => $this->cm->id, 'phase' => $phasecode)); } /** * @return moodle_url to the aggregation page */ public function aggregate_url() { global $CFG; return new moodle_url('/mod/workshop/aggregate.php', array('cmid' => $this->cm->id)); } /** * @return moodle_url of this workshop's toolbox page */ public function toolbox_url($tool) { global $CFG; return new moodle_url('/mod/workshop/toolbox.php', array('id' => $this->cm->id, 'tool' => $tool)); } /** * Workshop wrapper around {@see add_to_log()} * @deprecated since 2.7 Please use the provided event classes for logging actions. * * @param string $action to be logged * @param moodle_url $url absolute url as returned by {@see workshop::submission_url()} and friends * @param mixed $info additional info, usually id in a table * @param bool $return true to return the arguments for add_to_log. * @return void|array array of arguments for add_to_log if $return is true */ public function log($action, moodle_url $url = null, $info = null, $return = false) { debugging('The log method is now deprecated, please use event classes instead', DEBUG_DEVELOPER); if (is_null($url)) { $url = $this->view_url(); } if (is_null($info)) { $info = $this->id; } $logurl = $this->log_convert_url($url); $args = array($this->course->id, 'workshop', $action, $logurl, $info, $this->cm->id); if ($return) { return $args; } call_user_func_array('add_to_log', $args); } /** * Is the given user allowed to create their submission? * * @param int $userid * @return bool */ public function creating_submission_allowed($userid) { $now = time(); $ignoredeadlines = has_capability('mod/workshop:ignoredeadlines', $this->context, $userid); if ($this->latesubmissions) { if ($this->phase != self::PHASE_SUBMISSION and $this->phase != self::PHASE_ASSESSMENT) { // late submissions are allowed in the submission and assessment phase only return false; } if (!$ignoredeadlines and !empty($this->submissionstart) and $this->submissionstart > $now) { // late submissions are not allowed before the submission start return false; } return true; } else { if ($this->phase != self::PHASE_SUBMISSION) { // submissions are allowed during the submission phase only return false; } if (!$ignoredeadlines and !empty($this->submissionstart) and $this->submissionstart > $now) { // if enabled, submitting is not allowed before the date/time defined in the mod_form return false; } if (!$ignoredeadlines and !empty($this->submissionend) and $now > $this->submissionend ) { // if enabled, submitting is not allowed after the date/time defined in the mod_form unless late submission is allowed return false; } return true; } } /** * Is the given user allowed to modify their existing submission? * * @param int $userid * @return bool */ public function modifying_submission_allowed($userid) { $now = time(); $ignoredeadlines = has_capability('mod/workshop:ignoredeadlines', $this->context, $userid); if ($this->phase != self::PHASE_SUBMISSION) { // submissions can be edited during the submission phase only return false; } if (!$ignoredeadlines and !empty($this->submissionstart) and $this->submissionstart > $now) { // if enabled, re-submitting is not allowed before the date/time defined in the mod_form return false; } if (!$ignoredeadlines and !empty($this->submissionend) and $now > $this->submissionend) { // if enabled, re-submitting is not allowed after the date/time defined in the mod_form even if late submission is allowed return false; } return true; } /** * Is the given reviewer allowed to create/edit their assessments? * * @param int $userid * @return bool */ public function assessing_allowed($userid) { if ($this->phase != self::PHASE_ASSESSMENT) { // assessing is allowed in the assessment phase only, unless the user is a teacher // providing additional assessment during the evaluation phase if ($this->phase != self::PHASE_EVALUATION or !has_capability('mod/workshop:overridegrades', $this->context, $userid)) { return false; } } $now = time(); $ignoredeadlines = has_capability('mod/workshop:ignoredeadlines', $this->context, $userid); if (!$ignoredeadlines and !empty($this->assessmentstart) and $this->assessmentstart > $now) { // if enabled, assessing is not allowed before the date/time defined in the mod_form return false; } if (!$ignoredeadlines and !empty($this->assessmentend) and $now > $this->assessmentend) { // if enabled, assessing is not allowed after the date/time defined in the mod_form return false; } // here we go, assessing is allowed return true; } /** * Are reviewers allowed to create/edit their assessments of the example submissions? * * Returns null if example submissions are not enabled in this workshop. Otherwise returns * true or false. Note this does not check other conditions like the number of already * assessed examples, examples mode etc. * * @return null|bool */ public function assessing_examples_allowed() { if (empty($this->useexamples)) { return null; } if (self::EXAMPLES_VOLUNTARY == $this->examplesmode) { return true; } if (self::EXAMPLES_BEFORE_SUBMISSION == $this->examplesmode and self::PHASE_SUBMISSION == $this->phase) { return true; } if (self::EXAMPLES_BEFORE_ASSESSMENT == $this->examplesmode and self::PHASE_ASSESSMENT == $this->phase) { return true; } return false; } /** * Are the peer-reviews available to the authors? * * @return bool */ public function assessments_available() { return $this->phase == self::PHASE_CLOSED; } /** * Switch to a new workshop phase * * Modifies the underlying database record. You should terminate the script shortly after calling this. * * @param int $newphase new phase code * @return bool true if success, false otherwise */ public function switch_phase($newphase) { global $DB; $known = $this->available_phases_list(); if (!isset($known[$newphase])) { return false; } if (self::PHASE_CLOSED == $newphase) { // push the grades into the gradebook $workshop = new stdclass(); foreach ($this as $property => $value) { $workshop->{$property} = $value; } $workshop->course = $this->course->id; $workshop->cmidnumber = $this->cm->id; $workshop->modname = 'workshop'; workshop_update_grades($workshop); } $DB->set_field('workshop', 'phase', $newphase, array('id' => $this->id)); $this->phase = $newphase; $eventdata = array( 'objectid' => $this->id, 'context' => $this->context, 'other' => array( 'workshopphase' => $this->phase ) ); $event = \mod_workshop\event\phase_switched::create($eventdata); $event->trigger(); return true; } /** * Saves a raw grade for submission as calculated from the assessment form fields * * @param array $assessmentid assessment record id, must exists * @param mixed $grade raw percentual grade from 0.00000 to 100.00000 * @return false|float the saved grade */ public function set_peer_grade($assessmentid, $grade) { global $DB; if (is_null($grade)) { return false; } $data = new stdclass(); $data->id = $assessmentid; $data->grade = $grade; $data->timemodified = time(); $DB->update_record('workshop_assessments', $data); return $grade; } /** * Prepares data object with all workshop grades to be rendered * * @param int $userid the user we are preparing the report for * @param int $groupid if non-zero, prepare the report for the given group only * @param int $page the current page (for the pagination) * @param int $perpage participants per page (for the pagination) * @param string $sortby lastname|firstname|submissiontitle|submissiongrade|gradinggrade * @param string $sorthow ASC|DESC * @return stdclass data for the renderer */ public function prepare_grading_report_data($userid, $groupid, $page, $perpage, $sortby, $sorthow) { global $DB; $canviewall = has_capability('mod/workshop:viewallassessments', $this->context, $userid); $isparticipant = $this->is_participant($userid); if (!$canviewall and !$isparticipant) { // who the hell is this? return array(); } if (!in_array($sortby, array('lastname', 'firstname', 'submissiontitle', 'submissionmodified', 'submissiongrade', 'gradinggrade'))) { $sortby = 'lastname'; } if (!($sorthow === 'ASC' or $sorthow === 'DESC')) { $sorthow = 'ASC'; } // get the list of user ids to be displayed if ($canviewall) { $participants = $this->get_participants(false, $groupid); } else { // this is an ordinary workshop participant (aka student) - display the report just for him/her $participants = array($userid => (object)array('id' => $userid)); } // we will need to know the number of all records later for the pagination purposes $numofparticipants = count($participants); if ($numofparticipants > 0) { // load all fields which can be used for sorting and paginate the records list($participantids, $params) = $DB->get_in_or_equal(array_keys($participants), SQL_PARAMS_NAMED); $params['workshopid1'] = $this->id; $params['workshopid2'] = $this->id; $sqlsort = array(); $sqlsortfields = array($sortby => $sorthow) + array('lastname' => 'ASC', 'firstname' => 'ASC', 'u.id' => 'ASC'); foreach ($sqlsortfields as $sqlsortfieldname => $sqlsortfieldhow) { $sqlsort[] = $sqlsortfieldname . ' ' . $sqlsortfieldhow; } $sqlsort = implode(',', $sqlsort); $userfieldsapi = \core_user\fields::for_userpic(); $picturefields = $userfieldsapi->get_sql('u', false, '', 'userid', false)->selects; $sql = "SELECT $picturefields, s.title AS submissiontitle, s.timemodified AS submissionmodified, s.grade AS submissiongrade, ag.gradinggrade FROM {user} u LEFT JOIN {workshop_submissions} s ON (s.authorid = u.id AND s.workshopid = :workshopid1 AND s.example = 0) LEFT JOIN {workshop_aggregations} ag ON (ag.userid = u.id AND ag.workshopid = :workshopid2) WHERE u.id $participantids ORDER BY $sqlsort"; $participants = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage); } else { $participants = array(); } // this will hold the information needed to display user names and pictures $userinfo = array(); // get the user details for all participants to display $additionalnames = \core_user\fields::get_name_fields(); foreach ($participants as $participant) { if (!isset($userinfo[$participant->userid])) { $userinfo[$participant->userid] = new stdclass(); $userinfo[$participant->userid]->id = $participant->userid; $userinfo[$participant->userid]->picture = $participant->picture; $userinfo[$participant->userid]->imagealt = $participant->imagealt; $userinfo[$participant->userid]->email = $participant->email; foreach ($additionalnames as $addname) { $userinfo[$participant->userid]->$addname = $participant->$addname; } } } // load the submissions details $submissions = $this->get_submissions(array_keys($participants)); // get the user details for all moderators (teachers) that have overridden a submission grade foreach ($submissions as $submission) { if (!isset($userinfo[$submission->gradeoverby])) { $userinfo[$submission->gradeoverby] = new stdclass(); $userinfo[$submission->gradeoverby]->id = $submission->gradeoverby; $userinfo[$submission->gradeoverby]->picture = $submission->overpicture; $userinfo[$submission->gradeoverby]->imagealt = $submission->overimagealt; $userinfo[$submission->gradeoverby]->email = $submission->overemail; foreach ($additionalnames as $addname) { $temp = 'over' . $addname; $userinfo[$submission->gradeoverby]->$addname = $submission->$temp; } } } // get the user details for all reviewers of the displayed participants $reviewers = array(); if ($submissions) { list($submissionids, $params) = $DB->get_in_or_equal(array_keys($submissions), SQL_PARAMS_NAMED); list($sort, $sortparams) = users_order_by_sql('r'); $userfieldsapi = \core_user\fields::for_userpic(); $picturefields = $userfieldsapi->get_sql('r', false, '', 'reviewerid', false)->selects; $sql = "SELECT a.id AS assessmentid, a.submissionid, a.grade, a.gradinggrade, a.gradinggradeover, a.weight, $picturefields, s.id AS submissionid, s.authorid FROM {workshop_assessments} a JOIN {user} r ON (a.reviewerid = r.id) JOIN {workshop_submissions} s ON (a.submissionid = s.id AND s.example = 0) WHERE a.submissionid $submissionids ORDER BY a.weight DESC, $sort"; $reviewers = $DB->get_records_sql($sql, array_merge($params, $sortparams)); foreach ($reviewers as $reviewer) { if (!isset($userinfo[$reviewer->reviewerid])) { $userinfo[$reviewer->reviewerid] = new stdclass(); $userinfo[$reviewer->reviewerid]->id = $reviewer->reviewerid; $userinfo[$reviewer->reviewerid]->picture = $reviewer->picture; $userinfo[$reviewer->reviewerid]->imagealt = $reviewer->imagealt; $userinfo[$reviewer->reviewerid]->email = $reviewer->email; foreach ($additionalnames as $addname) { $userinfo[$reviewer->reviewerid]->$addname = $reviewer->$addname; } } } } // get the user details for all reviewees of the displayed participants $reviewees = array(); if ($participants) { list($participantids, $params) = $DB->get_in_or_equal(array_keys($participants), SQL_PARAMS_NAMED); list($sort, $sortparams) = users_order_by_sql('e'); $params['workshopid'] = $this->id; $userfieldsapi = \core_user\fields::for_userpic(); $picturefields = $userfieldsapi->get_sql('e', false, '', 'authorid', false)->selects; $sql = "SELECT a.id AS assessmentid, a.submissionid, a.grade, a.gradinggrade, a.gradinggradeover, a.reviewerid, a.weight, s.id AS submissionid, $picturefields FROM {user} u JOIN {workshop_assessments} a ON (a.reviewerid = u.id) JOIN {workshop_submissions} s ON (a.submissionid = s.id AND s.example = 0) JOIN {user} e ON (s.authorid = e.id) WHERE u.id $participantids AND s.workshopid = :workshopid ORDER BY a.weight DESC, $sort"; $reviewees = $DB->get_records_sql($sql, array_merge($params, $sortparams)); foreach ($reviewees as $reviewee) { if (!isset($userinfo[$reviewee->authorid])) { $userinfo[$reviewee->authorid] = new stdclass(); $userinfo[$reviewee->authorid]->id = $reviewee->authorid; $userinfo[$reviewee->authorid]->picture = $reviewee->picture; $userinfo[$reviewee->authorid]->imagealt = $reviewee->imagealt; $userinfo[$reviewee->authorid]->email = $reviewee->email; foreach ($additionalnames as $addname) { $userinfo[$reviewee->authorid]->$addname = $reviewee->$addname; } } } } // finally populate the object to be rendered $grades = $participants; foreach ($participants as $participant) { // set up default (null) values $grades[$participant->userid]->submissionid = null; $grades[$participant->userid]->submissiontitle = null; $grades[$participant->userid]->submissiongrade = null; $grades[$participant->userid]->submissiongradeover = null; $grades[$participant->userid]->submissiongradeoverby = null; $grades[$participant->userid]->submissionpublished = null; $grades[$participant->userid]->reviewedby = array(); $grades[$participant->userid]->reviewerof = array(); } unset($participants); unset($participant); foreach ($submissions as $submission) { $grades[$submission->authorid]->submissionid = $submission->id; $grades[$submission->authorid]->submissiontitle = $submission->title; $grades[$submission->authorid]->submissiongrade = $this->real_grade($submission->grade); $grades[$submission->authorid]->submissiongradeover = $this->real_grade($submission->gradeover); $grades[$submission->authorid]->submissiongradeoverby = $submission->gradeoverby; $grades[$submission->authorid]->submissionpublished = $submission->published; } unset($submissions); unset($submission); foreach($reviewers as $reviewer) { $info = new stdclass(); $info->userid = $reviewer->reviewerid; $info->assessmentid = $reviewer->assessmentid; $info->submissionid = $reviewer->submissionid; $info->grade = $this->real_grade($reviewer->grade); $info->gradinggrade = $this->real_grading_grade($reviewer->gradinggrade); $info->gradinggradeover = $this->real_grading_grade($reviewer->gradinggradeover); $info->weight = $reviewer->weight; $grades[$reviewer->authorid]->reviewedby[$reviewer->reviewerid] = $info; } unset($reviewers); unset($reviewer); foreach($reviewees as $reviewee) { $info = new stdclass(); $info->userid = $reviewee->authorid; $info->assessmentid = $reviewee->assessmentid; $info->submissionid = $reviewee->submissionid; $info->grade = $this->real_grade($reviewee->grade); $info->gradinggrade = $this->real_grading_grade($reviewee->gradinggrade); $info->gradinggradeover = $this->real_grading_grade($reviewee->gradinggradeover); $info->weight = $reviewee->weight; $grades[$reviewee->reviewerid]->reviewerof[$reviewee->authorid] = $info; } unset($reviewees); unset($reviewee); foreach ($grades as $grade) { $grade->gradinggrade = $this->real_grading_grade($grade->gradinggrade); } $data = new stdclass(); $data->grades = $grades; $data->userinfo = $userinfo; $data->totalcount = $numofparticipants; $data->maxgrade = $this->real_grade(100); $data->maxgradinggrade = $this->real_grading_grade(100); return $data; } /** * Calculates the real value of a grade * * @param float $value percentual value from 0 to 100 * @param float $max the maximal grade * @return string */ public function real_grade_value($value, $max) { $localized = true; if (is_null($value) or $value === '') { return null; } elseif ($max == 0) { return 0; } else { return format_float($max * $value / 100, $this->gradedecimals, $localized); } } /** * Calculates the raw (percentual) value from a real grade * * This is used in cases when a user wants to give a grade such as 12 of 20 and we need to save * this value in a raw percentual form into DB * @param float $value given grade * @param float $max the maximal grade * @return float suitable to be stored as numeric(10,5) */ public function raw_grade_value($value, $max) { if (is_null($value) or $value === '') { return null; } if ($max == 0 or $value < 0) { return 0; } $p = $value / $max * 100; if ($p > 100) { return $max; } return grade_floatval($p); } /** * Calculates the real value of grade for submission * * @param float $value percentual value from 0 to 100 * @return string */ public function real_grade($value) { return $this->real_grade_value($value, $this->grade); } /** * Calculates the real value of grade for assessment * * @param float $value percentual value from 0 to 100 * @return string */ public function real_grading_grade($value) { return $this->real_grade_value($value, $this->gradinggrade); } /** * Sets the given grades and received grading grades to null * * This does not clear the information about how the peers filled the assessment forms, but * clears the calculated grades in workshop_assessments. Therefore reviewers have to re-assess * the allocated submissions. * * @return void */ public function clear_assessments() { global $DB; $submissions = $this->get_submissions(); if (empty($submissions)) { // no money, no love return; } $submissions = array_keys($submissions); list($sql, $params) = $DB->get_in_or_equal($submissions, SQL_PARAMS_NAMED); $sql = "submissionid $sql"; $DB->set_field_select('workshop_assessments', 'grade', null, $sql, $params); $DB->set_field_select('workshop_assessments', 'gradinggrade', null, $sql, $params); } /** * Sets the grades for submission to null * * @param null|int|array $restrict If null, update all authors, otherwise update just grades for the given author(s) * @return void */ public function clear_submission_grades($restrict=null) { global $DB; $sql = "workshopid = :workshopid AND example = 0"; $params = array('workshopid' => $this->id); if (is_null($restrict)) { // update all users - no more conditions } elseif (!empty($restrict)) { list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED); $sql .= " AND authorid $usql"; $params = array_merge($params, $uparams); } else { throw new coding_exception('Empty value is not a valid parameter here'); } $DB->set_field_select('workshop_submissions', 'grade', null, $sql, $params); } /** * Calculates grades for submission for the given participant(s) and updates it in the database * * @param null|int|array $restrict If null, update all authors, otherwise update just grades for the given author(s) * @return void */ public function aggregate_submission_grades($restrict=null) { global $DB; // fetch a recordset with all assessments to process $sql = 'SELECT s.id AS submissionid, s.grade AS submissiongrade, a.weight, a.grade FROM {workshop_submissions} s LEFT JOIN {workshop_assessments} a ON (a.submissionid = s.id) WHERE s.example=0 AND s.workshopid=:workshopid'; // to be cont. $params = array('workshopid' => $this->id); if (is_null($restrict)) { // update all users - no more conditions } elseif (!empty($restrict)) { list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED); $sql .= " AND s.authorid $usql"; $params = array_merge($params, $uparams); } else { throw new coding_exception('Empty value is not a valid parameter here'); } $sql .= ' ORDER BY s.id'; // this is important for bulk processing $rs = $DB->get_recordset_sql($sql, $params); $batch = array(); // will contain a set of all assessments of a single submission $previous = null; // a previous record in the recordset foreach ($rs as $current) { if (is_null($previous)) { // we are processing the very first record in the recordset $previous = $current; } if ($current->submissionid == $previous->submissionid) { // we are still processing the current submission $batch[] = $current; } else { // process all the assessments of a sigle submission $this->aggregate_submission_grades_process($batch); // and then start to process another submission $batch = array($current); $previous = $current; } } // do not forget to process the last batch! $this->aggregate_submission_grades_process($batch); $rs->close(); } /** * Sets the aggregated grades for assessment to null * * @param null|int|array $restrict If null, update all reviewers, otherwise update just grades for the given reviewer(s) * @return void */ public function clear_grading_grades($restrict=null) { global $DB; $sql = "workshopid = :workshopid"; $params = array('workshopid' => $this->id); if (is_null($restrict)) { // update all users - no more conditions } elseif (!empty($restrict)) { list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED); $sql .= " AND userid $usql"; $params = array_merge($params, $uparams); } else { throw new coding_exception('Empty value is not a valid parameter here'); } $DB->set_field_select('workshop_aggregations', 'gradinggrade', null, $sql, $params); } /** * Calculates grades for assessment for the given participant(s) * * Grade for assessment is calculated as a simple mean of all grading grades calculated by the grading evaluator. * The assessment weight is not taken into account here. * * @param null|int|array $restrict If null, update all reviewers, otherwise update just grades for the given reviewer(s) * @return void */ public function aggregate_grading_grades($restrict=null) { global $DB; // fetch a recordset with all assessments to process $sql = 'SELECT a.reviewerid, a.gradinggrade, a.gradinggradeover, ag.id AS aggregationid, ag.gradinggrade AS aggregatedgrade FROM {workshop_assessments} a INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id) LEFT JOIN {workshop_aggregations} ag ON (ag.userid = a.reviewerid AND ag.workshopid = s.workshopid) WHERE s.example=0 AND s.workshopid=:workshopid'; // to be cont. $params = array('workshopid' => $this->id); if (is_null($restrict)) { // update all users - no more conditions } elseif (!empty($restrict)) { list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED); $sql .= " AND a.reviewerid $usql"; $params = array_merge($params, $uparams); } else { throw new coding_exception('Empty value is not a valid parameter here'); } $sql .= ' ORDER BY a.reviewerid'; // this is important for bulk processing $rs = $DB->get_recordset_sql($sql, $params); $batch = array(); // will contain a set of all assessments of a single submission $previous = null; // a previous record in the recordset foreach ($rs as $current) { if (is_null($previous)) { // we are processing the very first record in the recordset $previous = $current; } if ($current->reviewerid == $previous->reviewerid) { // we are still processing the current reviewer $batch[] = $current; } else { // process all the assessments of a sigle submission $this->aggregate_grading_grades_process($batch); // and then start to process another reviewer $batch = array($current); $previous = $current; } } // do not forget to process the last batch! $this->aggregate_grading_grades_process($batch); $rs->close(); } /** * Returns the mform the teachers use to put a feedback for the reviewer * * @param mixed moodle_url|null $actionurl * @param stdClass $assessment * @param array $options editable, editableweight, overridablegradinggrade * @return workshop_feedbackreviewer_form */ public function get_feedbackreviewer_form($actionurl, stdclass $assessment, $options=array()) { global $CFG; require_once(__DIR__ . '/feedbackreviewer_form.php'); $current = new stdclass(); $current->asid = $assessment->id; $current->weight = $assessment->weight; $current->gradinggrade = $this->real_grading_grade($assessment->gradinggrade); $current->gradinggradeover = $this->real_grading_grade($assessment->gradinggradeover); $current->feedbackreviewer = $assessment->feedbackreviewer; $current->feedbackreviewerformat = $assessment->feedbackreviewerformat; if (is_null($current->gradinggrade)) { $current->gradinggrade = get_string('nullgrade', 'workshop'); } if (!isset($options['editable'])) { $editable = true; // by default } else { $editable = (bool)$options['editable']; } // prepare wysiwyg editor $current = file_prepare_standard_editor($current, 'feedbackreviewer', array()); return new workshop_feedbackreviewer_form($actionurl, array('workshop' => $this, 'current' => $current, 'editoropts' => array(), 'options' => $options), 'post', '', null, $editable); } /** * Returns the mform the teachers use to put a feedback for the author on their submission * * @mixed moodle_url|null $actionurl * @param stdClass $submission * @param array $options editable * @return workshop_feedbackauthor_form */ public function get_feedbackauthor_form($actionurl, stdclass $submission, $options=array()) { global $CFG; require_once(__DIR__ . '/feedbackauthor_form.php'); $current = new stdclass(); $current->submissionid = $submission->id; $current->published = $submission->published; $current->grade = $this->real_grade($submission->grade); $current->gradeover = $this->real_grade($submission->gradeover); $current->feedbackauthor = $submission->feedbackauthor; $current->feedbackauthorformat = $submission->feedbackauthorformat; if (is_null($current->grade)) { $current->grade = get_string('nullgrade', 'workshop'); } if (!isset($options['editable'])) { $editable = true; // by default } else { $editable = (bool)$options['editable']; } // prepare wysiwyg editor $current = file_prepare_standard_editor($current, 'feedbackauthor', array()); return new workshop_feedbackauthor_form($actionurl, array('workshop' => $this, 'current' => $current, 'editoropts' => array(), 'options' => $options), 'post', '', null, $editable); } /** * Returns the information about the user's grades as they are stored in the gradebook * * The submission grade is returned for users with the capability mod/workshop:submit and the * assessment grade is returned for users with the capability mod/workshop:peerassess. Unless the * user has the capability to view hidden grades, grades must be visible to be returned. Null * grades are not returned. If none grade is to be returned, this method returns false. * * @param int $userid the user's id * @return workshop_final_grades|false */ public function get_gradebook_grades($userid) { global $CFG; require_once($CFG->libdir.'/gradelib.php'); if (empty($userid)) { throw new coding_exception('User id expected, empty value given.'); } // Read data via the Gradebook API $gradebook = grade_get_grades($this->course->id, 'mod', 'workshop', $this->id, $userid); $grades = new workshop_final_grades(); if (has_capability('mod/workshop:submit', $this->context, $userid)) { if (!empty($gradebook->items[0]->grades)) { $submissiongrade = reset($gradebook->items[0]->grades); if (!is_null($submissiongrade->grade)) { if (!$submissiongrade->hidden or has_capability('moodle/grade:viewhidden', $this->context, $userid)) { $grades->submissiongrade = $submissiongrade; } } } } if (has_capability('mod/workshop:peerassess', $this->context, $userid)) { if (!empty($gradebook->items[1]->grades)) { $assessmentgrade = reset($gradebook->items[1]->grades); if (!is_null($assessmentgrade->grade)) { if (!$assessmentgrade->hidden or has_capability('moodle/grade:viewhidden', $this->context, $userid)) { $grades->assessmentgrade = $assessmentgrade; } } } } if (!is_null($grades->submissiongrade) or !is_null($grades->assessmentgrade)) { return $grades; } return false; } /** * Return the editor options for the submission content field. * * @return array */ public function submission_content_options() { global $CFG; require_once($CFG->dirroot.'/repository/lib.php'); return array( 'trusttext' => true, 'subdirs' => false, 'maxfiles' => $this->nattachments, 'maxbytes' => $this->maxbytes, 'context' => $this->context, 'return_types' => FILE_INTERNAL | FILE_EXTERNAL, ); } /** * Return the filemanager options for the submission attachments field. * * @return array */ public function submission_attachment_options() { global $CFG; require_once($CFG->dirroot.'/repository/lib.php'); $options = array( 'subdirs' => true, 'maxfiles' => $this->nattachments, 'maxbytes' => $this->maxbytes, 'return_types' => FILE_INTERNAL | FILE_CONTROLLED_LINK, ); $filetypesutil = new \core_form\filetypes_util(); $options['accepted_types'] = $filetypesutil->normalize_file_types($this->submissionfiletypes); return $options; } /** * Return the editor options for the overall feedback for the author. * * @return array */ public function overall_feedback_content_options() { global $CFG; require_once($CFG->dirroot.'/repository/lib.php'); return array( 'subdirs' => 0, 'maxbytes' => $this->overallfeedbackmaxbytes, 'maxfiles' => $this->overallfeedbackfiles, 'changeformat' => 1, 'context' => $this->context, 'return_types' => FILE_INTERNAL, ); } /** * Return the filemanager options for the overall feedback for the author. * * @return array */ public function overall_feedback_attachment_options() { global $CFG; require_once($CFG->dirroot.'/repository/lib.php'); $options = array( 'subdirs' => 1, 'maxbytes' => $this->overallfeedbackmaxbytes, 'maxfiles' => $this->overallfeedbackfiles, 'return_types' => FILE_INTERNAL | FILE_CONTROLLED_LINK, ); $filetypesutil = new \core_form\filetypes_util(); $options['accepted_types'] = $filetypesutil->normalize_file_types($this->overallfeedbackfiletypes); return $options; } /** * Performs the reset of this workshop instance. * * @param stdClass $data The actual course reset settings. * @return array List of results, each being array[(string)component, (string)item, (string)error] */ public function reset_userdata(stdClass $data) { $componentstr = get_string('pluginname', 'workshop').': '.format_string($this->name); $status = array(); if (!empty($data->reset_workshop_assessments) or !empty($data->reset_workshop_submissions)) { // Reset all data related to assessments, including assessments of // example submissions. $result = $this->reset_userdata_assessments($data); if ($result === true) { $status[] = array( 'component' => $componentstr, 'item' => get_string('resetassessments', 'mod_workshop'), 'error' => false, ); } else { $status[] = array( 'component' => $componentstr, 'item' => get_string('resetassessments', 'mod_workshop'), 'error' => $result, ); } } if (!empty($data->reset_workshop_submissions)) { // Reset all remaining data related to submissions. $result = $this->reset_userdata_submissions($data); if ($result === true) { $status[] = array( 'component' => $componentstr, 'item' => get_string('resetsubmissions', 'mod_workshop'), 'error' => false, ); } else { $status[] = array( 'component' => $componentstr, 'item' => get_string('resetsubmissions', 'mod_workshop'), 'error' => $result, ); } } if (!empty($data->reset_workshop_phase)) { // Do not use the {@link workshop::switch_phase()} here, we do not // want to trigger events. $this->reset_phase(); $status[] = array( 'component' => $componentstr, 'item' => get_string('resetsubmissions', 'mod_workshop'), 'error' => false, ); } return $status; } /** * Check if the current user can access the other user's group. * * This is typically used for teacher roles that have permissions like * 'view all submissions'. Even with such a permission granted, we have to * check the workshop activity group mode. * * If the workshop is not in a group mode, or if it is in the visible group * mode, this method returns true. This is consistent with how the * {@link groups_get_activity_allowed_groups()} behaves. * * If the workshop is in a separate group mode, the current user has to * have the 'access all groups' permission, or share at least one * accessible group with the other user. * * @param int $otheruserid The ID of the other user, e.g. the author of a submission. * @return bool False if the current user cannot access the other user's group. */ public function check_group_membership($otheruserid) { global $USER; if (groups_get_activity_groupmode($this->cm) != SEPARATEGROUPS) { // The workshop is not in a group mode, or it is in a visible group mode. return true; } else if (has_capability('moodle/site:accessallgroups', $this->context)) { // The current user can access all groups. return true; } else { $thisusersgroups = groups_get_all_groups($this->course->id, $USER->id, $this->cm->groupingid, 'g.id'); $otherusersgroups = groups_get_all_groups($this->course->id, $otheruserid, $this->cm->groupingid, 'g.id'); $commongroups = array_intersect_key($thisusersgroups, $otherusersgroups); if (empty($commongroups)) { // The current user has no group common with the other user. return false; } else { // The current user has a group common with the other user. return true; } } } /** * Check whether the given user has assessed all his required examples before submission. * * @param int $userid the user to check * @return bool false if there are examples missing assessment, true otherwise. * @since Moodle 3.4 */ public function check_examples_assessed_before_submission($userid) { if ($this->useexamples and $this->examplesmode == self::EXAMPLES_BEFORE_SUBMISSION and !has_capability('mod/workshop:manageexamples', $this->context)) { // Check that all required examples have been assessed by the user. $examples = $this->get_examples_for_reviewer($userid); foreach ($examples as $exampleid => $example) { if (is_null($example->assessmentid)) { $examples[$exampleid]->assessmentid = $this->add_allocation($example, $userid, 0); } if (is_null($example->grade)) { return false; } } } return true; } /** * Check that all required examples have been assessed by the given user. * * @param stdClass $userid the user (reviewer) to check * @return mixed bool|state false and notice code if there are examples missing assessment, true otherwise. * @since Moodle 3.4 */ public function check_examples_assessed_before_assessment($userid) { if ($this->useexamples and $this->examplesmode == self::EXAMPLES_BEFORE_ASSESSMENT and !has_capability('mod/workshop:manageexamples', $this->context)) { // The reviewer must have submitted their own submission. $reviewersubmission = $this->get_submission_by_author($userid); if (!$reviewersubmission) { // No money, no love. return array(false, 'exampleneedsubmission'); } else { $examples = $this->get_examples_for_reviewer($userid); foreach ($examples as $exampleid => $example) { if (is_null($example->grade)) { return array(false, 'exampleneedassessed'); } } } } return array(true, null); } /** * Trigger module viewed event and set the module viewed for completion. * * @since Moodle 3.4 */ public function set_module_viewed() { global $CFG; require_once($CFG->libdir . '/completionlib.php'); // Mark viewed. $completion = new completion_info($this->course); $completion->set_module_viewed($this->cm); $eventdata = array(); $eventdata['objectid'] = $this->id; $eventdata['context'] = $this->context; // Trigger module viewed event. $event = \mod_workshop\event\course_module_viewed::create($eventdata); $event->add_record_snapshot('course', $this->course); $event->add_record_snapshot('workshop', $this->dbrecord); $event->add_record_snapshot('course_modules', $this->cm); $event->trigger(); } /** * Validates the submission form or WS data. * * @param array $data the data to be validated * @return array the validation errors (if any) * @since Moodle 3.4 */ public function validate_submission_data($data) { global $DB, $USER; $errors = array(); if (empty($data['id']) and empty($data['example'])) { // Make sure there is no submission saved meanwhile from another browser window. $sql = "SELECT COUNT(s.id) FROM {workshop_submissions} s JOIN {workshop} w ON (s.workshopid = w.id) JOIN {course_modules} cm ON (w.id = cm.instance) JOIN {modules} m ON (m.name = 'workshop' AND m.id = cm.module) WHERE cm.id = ? AND s.authorid = ? AND s.example = 0"; if ($DB->count_records_sql($sql, array($data['cmid'], $USER->id))) { $errors['title'] = get_string('err_multiplesubmissions', 'mod_workshop'); } } // Get the workshop record by id or cmid, depending on whether we're creating or editing a submission. if (empty($data['workshopid'])) { $workshop = $DB->get_record_select('workshop', 'id = (SELECT instance FROM {course_modules} WHERE id = ?)', [$data['cmid']]); } else { $workshop = $DB->get_record('workshop', ['id' => $data['workshopid']]); } if (isset($data['attachment_filemanager'])) { $getfiles = file_get_drafarea_files($data['attachment_filemanager']); $attachments = $getfiles->list; } else { $attachments = array(); } if ($workshop->submissiontypefile == WORKSHOP_SUBMISSION_TYPE_REQUIRED) { if (empty($attachments)) { $errors['attachment_filemanager'] = get_string('err_required', 'form'); } } else if ($workshop->submissiontypefile == WORKSHOP_SUBMISSION_TYPE_DISABLED && !empty($data['attachment_filemanager'])) { $errors['attachment_filemanager'] = get_string('submissiontypedisabled', 'mod_workshop'); } if ($workshop->submissiontypetext == WORKSHOP_SUBMISSION_TYPE_REQUIRED && html_is_blank($data['content_editor']['text'])) { $errors['content_editor'] = get_string('err_required', 'form'); } else if ($workshop->submissiontypetext == WORKSHOP_SUBMISSION_TYPE_DISABLED && !empty($data['content_editor']['text'])) { $errors['content_editor'] = get_string('submissiontypedisabled', 'mod_workshop'); } // If neither type is explicitly required, one or the other must be submitted. if ($workshop->submissiontypetext != WORKSHOP_SUBMISSION_TYPE_REQUIRED && $workshop->submissiontypefile != WORKSHOP_SUBMISSION_TYPE_REQUIRED && empty($attachments) && html_is_blank($data['content_editor']['text'])) { $errors['content_editor'] = get_string('submissionrequiredcontent', 'mod_workshop'); $errors['attachment_filemanager'] = get_string('submissionrequiredfile', 'mod_workshop'); } return $errors; } /** * Adds or updates a submission. * * @param stdClass $submission The submissin data (via form or via WS). * @return the new or updated submission id. * @since Moodle 3.4 */ public function edit_submission($submission) { global $USER, $DB; if ($submission->example == 0) { // This was used just for validation, it must be set to zero when dealing with normal submissions. unset($submission->example); } else { throw new coding_exception('Invalid submission form data value: example'); } $timenow = time(); if (is_null($submission->id)) { $submission->workshopid = $this->id; $submission->example = 0; $submission->authorid = $USER->id; $submission->timecreated = $timenow; $submission->feedbackauthorformat = editors_get_preferred_format(); } $submission->timemodified = $timenow; $submission->title = trim($submission->title); $submission->content = ''; // Updated later. $submission->contentformat = FORMAT_HTML; // Updated later. $submission->contenttrust = 0; // Updated later. $submission->late = 0x0; // Bit mask. if (!empty($this->submissionend) and ($this->submissionend < time())) { $submission->late = $submission->late | 0x1; } if ($this->phase == self::PHASE_ASSESSMENT) { $submission->late = $submission->late | 0x2; } // Event information. $params = array( 'context' => $this->context, 'courseid' => $this->course->id, 'other' => array( 'submissiontitle' => $submission->title ) ); $logdata = null; if (is_null($submission->id)) { $submission->id = $DB->insert_record('workshop_submissions', $submission); $params['objectid'] = $submission->id; $event = \mod_workshop\event\submission_created::create($params); $event->trigger(); } else { if (empty($submission->id) or empty($submission->id) or ($submission->id != $submission->id)) { throw new moodle_exception('err_submissionid', 'workshop'); } } $params['objectid'] = $submission->id; // Save and relink embedded images and save attachments. if ($this->submissiontypetext != WORKSHOP_SUBMISSION_TYPE_DISABLED) { $submission = file_postupdate_standard_editor($submission, 'content', $this->submission_content_options(), $this->context, 'mod_workshop', 'submission_content', $submission->id); } $submission = file_postupdate_standard_filemanager($submission, 'attachment', $this->submission_attachment_options(), $this->context, 'mod_workshop', 'submission_attachment', $submission->id); if (empty($submission->attachment)) { // Explicit cast to zero integer. $submission->attachment = 0; } // Store the updated values or re-save the new submission (re-saving needed because URLs are now rewritten). $DB->update_record('workshop_submissions', $submission); $event = \mod_workshop\event\submission_updated::create($params); $event->add_record_snapshot('workshop', $this->dbrecord); $event->trigger(); // Send submitted content for plagiarism detection. $fs = get_file_storage(); $files = $fs->get_area_files($this->context->id, 'mod_workshop', 'submission_attachment', $submission->id); $params['other']['content'] = $submission->content; $params['other']['pathnamehashes'] = array_keys($files); $event = \mod_workshop\event\assessable_uploaded::create($params); $event->trigger(); return $submission->id; } /** * Helper method for validating if the current user can view the given assessment. * * @param stdClass $assessment assessment object * @param stdClass $submission submission object * @return void * @throws moodle_exception * @since Moodle 3.4 */ public function check_view_assessment($assessment, $submission) { global $USER; $isauthor = $submission->authorid == $USER->id; $isreviewer = $assessment->reviewerid == $USER->id; $canviewallassessments = has_capability('mod/workshop:viewallassessments', $this->context); $canviewallsubmissions = has_capability('mod/workshop:viewallsubmissions', $this->context); $canviewallsubmissions = $canviewallsubmissions && $this->check_group_membership($submission->authorid); if (!$isreviewer and !$isauthor and !($canviewallassessments and $canviewallsubmissions)) { throw new \moodle_exception('nopermissions', 'error', $this->view_url(), 'view this assessment'); } if ($isauthor and !$isreviewer and !$canviewallassessments and $this->phase != self::PHASE_CLOSED) { // Authors can see assessments of their work at the end of workshop only. throw new \moodle_exception('nopermissions', 'error', $this->view_url(), 'view assessment of own work before workshop is closed'); } } /** * Helper method for validating if the current user can edit the given assessment. * * @param stdClass $assessment assessment object * @param stdClass $submission submission object * @return void * @throws moodle_exception * @since Moodle 3.4 */ public function check_edit_assessment($assessment, $submission) { global $USER; $this->check_view_assessment($assessment, $submission); // Further checks. $isreviewer = ($USER->id == $assessment->reviewerid); $assessmenteditable = $isreviewer && $this->assessing_allowed($USER->id); if (!$assessmenteditable) { throw new moodle_exception('nopermissions', 'error', '', 'edit assessments'); } list($assessed, $notice) = $this->check_examples_assessed_before_assessment($assessment->reviewerid); if (!$assessed) { throw new moodle_exception($notice, 'mod_workshop'); } } /** * Adds information to an allocated assessment (function used the first time a review is done or when updating an existing one). * * @param stdClass $assessment the assessment * @param stdClass $submission the submission * @param stdClass $data the assessment data to be added or Updated * @param stdClass $strategy the strategy instance * @return float|null Raw percentual grade (0.00000 to 100.00000) for submission * @since Moodle 3.4 */ public function edit_assessment($assessment, $submission, $data, $strategy) { global $DB; $cansetassessmentweight = has_capability('mod/workshop:allocate', $this->context); // Let the grading strategy subplugin save its data. $rawgrade = $strategy->save_assessment($assessment, $data); // Store the data managed by the workshop core. $coredata = (object)array('id' => $assessment->id); if (isset($data->feedbackauthor_editor)) { $coredata->feedbackauthor_editor = $data->feedbackauthor_editor; $coredata = file_postupdate_standard_editor($coredata, 'feedbackauthor', $this->overall_feedback_content_options(), $this->context, 'mod_workshop', 'overallfeedback_content', $assessment->id); unset($coredata->feedbackauthor_editor); } if (isset($data->feedbackauthorattachment_filemanager)) { $coredata->feedbackauthorattachment_filemanager = $data->feedbackauthorattachment_filemanager; $coredata = file_postupdate_standard_filemanager($coredata, 'feedbackauthorattachment', $this->overall_feedback_attachment_options(), $this->context, 'mod_workshop', 'overallfeedback_attachment', $assessment->id); unset($coredata->feedbackauthorattachment_filemanager); if (empty($coredata->feedbackauthorattachment)) { $coredata->feedbackauthorattachment = 0; } } if (isset($data->weight) and $cansetassessmentweight) { $coredata->weight = $data->weight; } // Update the assessment data if there is something other than just the 'id'. if (count((array)$coredata) > 1 ) { $DB->update_record('workshop_assessments', $coredata); $params = array( 'relateduserid' => $submission->authorid, 'objectid' => $assessment->id, 'context' => $this->context, 'other' => array( 'workshopid' => $this->id, 'submissionid' => $assessment->submissionid ) ); if (is_null($assessment->grade)) { // All workshop_assessments are created when allocations are made. The create event is of more use located here. $event = \mod_workshop\event\submission_assessed::create($params); $event->trigger(); } else { $params['other']['grade'] = $assessment->grade; $event = \mod_workshop\event\submission_reassessed::create($params); $event->trigger(); } } return $rawgrade; } /** * Evaluates an assessment. * * @param stdClass $assessment the assessment * @param stdClass $data the assessment data to be updated * @param bool $cansetassessmentweight whether the user can change the assessment weight * @param bool $canoverridegrades whether the user can override the assessment grades * @return void * @since Moodle 3.4 */ public function evaluate_assessment($assessment, $data, $cansetassessmentweight, $canoverridegrades) { global $DB, $USER; $data = file_postupdate_standard_editor($data, 'feedbackreviewer', array(), $this->context); $record = new stdclass(); $record->id = $assessment->id; if ($cansetassessmentweight) { $record->weight = $data->weight; } if ($canoverridegrades) { $record->gradinggradeover = $this->raw_grade_value($data->gradinggradeover, $this->gradinggrade); $record->gradinggradeoverby = $USER->id; $record->feedbackreviewer = $data->feedbackreviewer; $record->feedbackreviewerformat = $data->feedbackreviewerformat; } $DB->update_record('workshop_assessments', $record); } /** * Trigger submission viewed event. * * @param stdClass $submission submission object * @since Moodle 3.4 */ public function set_submission_viewed($submission) { $params = array( 'objectid' => $submission->id, 'context' => $this->context, 'courseid' => $this->course->id, 'relateduserid' => $submission->authorid, 'other' => array( 'workshopid' => $this->id ) ); $event = \mod_workshop\event\submission_viewed::create($params); $event->trigger(); } /** * Evaluates a submission. * * @param stdClass $submission the submission * @param stdClass $data the submission data to be updated * @param bool $canpublish whether the user can publish the submission * @param bool $canoverride whether the user can override the submission grade * @return void * @since Moodle 3.4 */ public function evaluate_submission($submission, $data, $canpublish, $canoverride) { global $DB, $USER; $data = file_postupdate_standard_editor($data, 'feedbackauthor', array(), $this->context); $record = new stdclass(); $record->id = $submission->id; if ($canoverride) { $record->gradeover = $this->raw_grade_value($data->gradeover, $this->grade); $record->gradeoverby = $USER->id; $record->feedbackauthor = $data->feedbackauthor; $record->feedbackauthorformat = $data->feedbackauthorformat; } if ($canpublish) { $record->published = !empty($data->published); } $DB->update_record('workshop_submissions', $record); } /** * Get the initial first name. * * @return string|null initial of first name we are currently filtering by. */ public function get_initial_first(): ?string { if (empty($this->initialbarprefs['i_first'])) { return null; } return $this->initialbarprefs['i_first']; } /** * Get the initial last name. * * @return string|null initial of last name we are currently filtering by. */ public function get_initial_last(): ?string { if (empty($this->initialbarprefs['i_last'])) { return null; } return $this->initialbarprefs['i_last']; } /** * Init method for initial bars. * @return void */ public function init_initial_bar(): void { global $SESSION; if ($this->phase === self::PHASE_SETUP) { return; } $ifirst = optional_param('ifirst', null, PARAM_NOTAGS); $ilast = optional_param('ilast', null, PARAM_NOTAGS); if (empty($SESSION->mod_workshop->initialbarprefs['id-'.$this->context->id])) { $SESSION->mod_workshop = new stdClass(); $SESSION->mod_workshop->initialbarprefs['id-'.$this->context->id] = []; } if (!empty($SESSION->mod_workshop->initialbarprefs['id-'.$this->context->id]['i_first'])) { $this->initialbarprefs['i_first'] = $SESSION->mod_workshop->initialbarprefs['id-'.$this->context->id]['i_first']; } if (!empty($SESSION->mod_workshop->initialbarprefs['id-'.$this->context->id]['i_last'])) { $this->initialbarprefs['i_last'] = $SESSION->mod_workshop->initialbarprefs['id-'.$this->context->id]['i_last']; } if (!is_null($ifirst)) { $this->initialbarprefs['i_first'] = $ifirst; $SESSION->mod_workshop->initialbarprefs['id-'.$this->context->id]['i_first'] = $ifirst; } if (!is_null($ilast)) { $this->initialbarprefs['i_last'] = $ilast; $SESSION->mod_workshop->initialbarprefs['id-'.$this->context->id]['i_last'] = $ilast; } } //////////////////////////////////////////////////////////////////////////////// // Internal methods (implementation details) // //////////////////////////////////////////////////////////////////////////////// /** * Given an array of all assessments of a single submission, calculates the final grade for this submission * * This calculates the weighted mean of the passed assessment grades. If, however, the submission grade * was overridden by a teacher, the gradeover value is returned and the rest of grades are ignored. * * @param array $assessments of stdclass(->submissionid ->submissiongrade ->gradeover ->weight ->grade) * @return void */ protected function aggregate_submission_grades_process(array $assessments) { global $DB; $submissionid = null; // the id of the submission being processed $current = null; // the grade currently saved in database $finalgrade = null; // the new grade to be calculated $sumgrades = 0; $sumweights = 0; foreach ($assessments as $assessment) { if (is_null($submissionid)) { // the id is the same in all records, fetch it during the first loop cycle $submissionid = $assessment->submissionid; } if (is_null($current)) { // the currently saved grade is the same in all records, fetch it during the first loop cycle $current = $assessment->submissiongrade; } if (is_null($assessment->grade)) { // this was not assessed yet continue; } if ($assessment->weight == 0) { // this does not influence the calculation continue; } $sumgrades += $assessment->grade * $assessment->weight; $sumweights += $assessment->weight; } if ($sumweights > 0 and is_null($finalgrade)) { $finalgrade = grade_floatval($sumgrades / $sumweights); } // check if the new final grade differs from the one stored in the database if (grade_floats_different($finalgrade, $current)) { // we need to save new calculation into the database $record = new stdclass(); $record->id = $submissionid; $record->grade = $finalgrade; $record->timegraded = time(); $DB->update_record('workshop_submissions', $record); } } /** * Given an array of all assessments done by a single reviewer, calculates the final grading grade * * This calculates the simple mean of the passed grading grades. If, however, the grading grade * was overridden by a teacher, the gradinggradeover value is returned and the rest of grades are ignored. * * @param array $assessments of stdclass(->reviewerid ->gradinggrade ->gradinggradeover ->aggregationid ->aggregatedgrade) * @param null|int $timegraded explicit timestamp of the aggregation, defaults to the current time * @return void */ protected function aggregate_grading_grades_process(array $assessments, $timegraded = null) { global $DB; $reviewerid = null; // the id of the reviewer being processed $current = null; // the gradinggrade currently saved in database $finalgrade = null; // the new grade to be calculated $agid = null; // aggregation id $sumgrades = 0; $count = 0; if (is_null($timegraded)) { $timegraded = time(); } foreach ($assessments as $assessment) { if (is_null($reviewerid)) { // the id is the same in all records, fetch it during the first loop cycle $reviewerid = $assessment->reviewerid; } if (is_null($agid)) { // the id is the same in all records, fetch it during the first loop cycle $agid = $assessment->aggregationid; } if (is_null($current)) { // the currently saved grade is the same in all records, fetch it during the first loop cycle $current = $assessment->aggregatedgrade; } if (!is_null($assessment->gradinggradeover)) { // the grading grade for this assessment is overridden by a teacher $sumgrades += $assessment->gradinggradeover; $count++; } else { if (!is_null($assessment->gradinggrade)) { $sumgrades += $assessment->gradinggrade; $count++; } } } if ($count > 0) { $finalgrade = grade_floatval($sumgrades / $count); } // Event information. $params = array( 'context' => $this->context, 'courseid' => $this->course->id, 'relateduserid' => $reviewerid ); // check if the new final grade differs from the one stored in the database if (grade_floats_different($finalgrade, $current)) { $params['other'] = array( 'currentgrade' => $current, 'finalgrade' => $finalgrade ); // we need to save new calculation into the database if (is_null($agid)) { // no aggregation record yet $record = new stdclass(); $record->workshopid = $this->id; $record->userid = $reviewerid; $record->gradinggrade = $finalgrade; $record->timegraded = $timegraded; $record->id = $DB->insert_record('workshop_aggregations', $record); $params['objectid'] = $record->id; $event = \mod_workshop\event\assessment_evaluated::create($params); $event->trigger(); } else { $record = new stdclass(); $record->id = $agid; $record->gradinggrade = $finalgrade; $record->timegraded = $timegraded; $DB->update_record('workshop_aggregations', $record); $params['objectid'] = $agid; $event = \mod_workshop\event\assessment_reevaluated::create($params); $event->trigger(); } } } /** * Returns SQL to fetch all enrolled users with the given capability in the current workshop * * The returned array consists of string $sql and the $params array. Note that the $sql can be * empty if a grouping is selected and it has no groups. * * The list is automatically restricted according to any availability restrictions * that apply to user lists (e.g. group, grouping restrictions). * * @param string $capability the name of the capability * @param bool $musthavesubmission ff true, return only users who have already submitted * @param int $groupid 0 means ignore groups, any other value limits the result by group id * @return array of (string)sql, (array)params */ protected function get_users_with_capability_sql($capability, $musthavesubmission, $groupid) { global $CFG; /** @var int static counter used to generate unique parameter holders */ static $inc = 0; $inc++; // If the caller requests all groups and we are using a selected grouping, // recursively call this function for each group in the grouping (this is // needed because get_enrolled_sql only supports a single group). if (empty($groupid) and $this->cm->groupingid) { $groupingid = $this->cm->groupingid; $groupinggroupids = array_keys(groups_get_all_groups($this->cm->course, 0, $this->cm->groupingid, 'g.id')); $sql = array(); $params = array(); foreach ($groupinggroupids as $groupinggroupid) { if ($groupinggroupid > 0) { // just in case in order not to fall into the endless loop list($gsql, $gparams) = $this->get_users_with_capability_sql($capability, $musthavesubmission, $groupinggroupid); $sql[] = $gsql; $params = array_merge($params, $gparams); } } $sql = implode(PHP_EOL." UNION ".PHP_EOL, $sql); return array($sql, $params); } list($esql, $params) = get_enrolled_sql($this->context, $capability, $groupid, true); $userfieldsapi = \core_user\fields::for_userpic(); $userfields = $userfieldsapi->get_sql('u', false, '', '', false)->selects; $sql = "SELECT $userfields FROM {user} u JOIN ($esql) je ON (je.id = u.id AND u.deleted = 0) "; if ($musthavesubmission) { $sql .= " JOIN {workshop_submissions} ws ON (ws.authorid = u.id AND ws.example = 0 AND ws.workshopid = :workshopid{$inc}) "; $params['workshopid'.$inc] = $this->id; } // If the activity is restricted so that only certain users should appear // in user lists, integrate this into the same SQL. $info = new \core_availability\info_module($this->cm); list ($listsql, $listparams) = $info->get_user_list_sql(false); if ($listsql) { $sql .= " JOIN ($listsql) restricted ON restricted.id = u.id "; $params = array_merge($params, $listparams); } return array($sql, $params); } /** * Returns SQL to fetch all enrolled users with the first name or last name. * * @return array */ protected function get_users_with_initial_filtering_sql_where(): array { global $DB; $conditions = []; $params = []; $ifirst = $this->get_initial_first(); $ilast = $this->get_initial_last(); if ($ifirst) { $conditions[] = $DB->sql_like('LOWER(tmp.firstname)', ':i_first' , false, false); $params['i_first'] = $DB->sql_like_escape($ifirst) . '%'; } if ($ilast) { $conditions[] = $DB->sql_like('LOWER(tmp.lastname)', ':i_last' , false, false); $params['i_last'] = $DB->sql_like_escape($ilast) . '%'; } return [implode(" AND ", $conditions), $params]; } /** * Returns SQL statement that can be used to fetch all actively enrolled participants in the workshop * * @param bool $musthavesubmission if true, return only users who have already submitted * @param int $groupid 0 means ignore groups, any other value limits the result by group id * @return array of (string)sql, (array)params */ protected function get_participants_sql($musthavesubmission=false, $groupid=0) { list($sql1, $params1) = $this->get_users_with_capability_sql('mod/workshop:submit', $musthavesubmission, $groupid); list($sql2, $params2) = $this->get_users_with_capability_sql('mod/workshop:peerassess', $musthavesubmission, $groupid); if (empty($sql1) or empty($sql2)) { if (empty($sql1) and empty($sql2)) { return array('', array()); } else if (empty($sql1)) { $sql = $sql2; $params = $params2; } else { $sql = $sql1; $params = $params1; } } else { $sql = $sql1.PHP_EOL." UNION ".PHP_EOL.$sql2; $params = array_merge($params1, $params2); } return array($sql, $params); } /** * @return array of available workshop phases */ protected function available_phases_list() { return array( self::PHASE_SETUP => true, self::PHASE_SUBMISSION => true, self::PHASE_ASSESSMENT => true, self::PHASE_EVALUATION => true, self::PHASE_CLOSED => true, ); } /** * Converts absolute URL to relative URL needed by {@see add_to_log()} * * @param moodle_url $url absolute URL * @return string */ protected function log_convert_url(moodle_url $fullurl) { static $baseurl; if (!isset($baseurl)) { $baseurl = new moodle_url('/mod/workshop/'); $baseurl = $baseurl->out(); } return substr($fullurl->out(), strlen($baseurl)); } /** * Removes all user data related to assessments (including allocations). * * This includes assessments of example submissions as long as they are not * referential assessments. * * @param stdClass $data The actual course reset settings. * @return bool|string True on success, error message otherwise. */ protected function reset_userdata_assessments(stdClass $data) { global $DB; $sql = "SELECT a.id FROM {workshop_assessments} a JOIN {workshop_submissions} s ON (a.submissionid = s.id) WHERE s.workshopid = :workshopid AND (s.example = 0 OR (s.example = 1 AND a.weight = 0))"; $assessments = $DB->get_records_sql($sql, array('workshopid' => $this->id)); $this->delete_assessment(array_keys($assessments)); $DB->delete_records('workshop_aggregations', array('workshopid' => $this->id)); return true; } /** * Removes all user data related to participants' submissions. * * @param stdClass $data The actual course reset settings. * @return bool|string True on success, error message otherwise. */ protected function reset_userdata_submissions(stdClass $data) { global $DB; $submissions = $this->get_submissions(); foreach ($submissions as $submission) { $this->delete_submission($submission); } return true; } /** * Hard set the workshop phase to the setup one. */ protected function reset_phase() { global $DB; $DB->set_field('workshop', 'phase', self::PHASE_SETUP, array('id' => $this->id)); $this->phase = self::PHASE_SETUP; } } //////////////////////////////////////////////////////////////////////////////// // Renderable components //////////////////////////////////////////////////////////////////////////////// /** * Represents the user planner tool * * Planner contains list of phases. Each phase contains list of tasks. Task is a simple object with * title, link and completed (true/false/null logic). */ class workshop_user_plan implements renderable { /** @var int id of the user this plan is for */ public $userid; /** @var workshop */ public $workshop; /** @var array of (stdclass)tasks */ public $phases = array(); /** @var null|array of example submissions to be assessed by the planner owner */ protected $examples = null; /** * Prepare an individual workshop plan for the given user. * * @param workshop $workshop instance * @param int $userid whom the plan is prepared for */ public function __construct(workshop $workshop, $userid) { global $DB; $this->workshop = $workshop; $this->userid = $userid; //--------------------------------------------------------- // * SETUP | submission | assessment | evaluation | closed //--------------------------------------------------------- $phase = new stdclass(); $phase->title = get_string('phasesetup', 'workshop'); $phase->tasks = array(); if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) { $task = new stdclass(); $task->title = get_string('taskintro', 'workshop'); $task->link = $workshop->updatemod_url(); $task->completed = !(trim($workshop->intro) == ''); $phase->tasks['intro'] = $task; } if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) { $task = new stdclass(); $task->title = get_string('taskinstructauthors', 'workshop'); $task->link = $workshop->updatemod_url(); $task->completed = !(trim($workshop->instructauthors) == ''); $phase->tasks['instructauthors'] = $task; } if (has_capability('mod/workshop:editdimensions', $workshop->context, $userid)) { $task = new stdclass(); $task->title = get_string('editassessmentform', 'workshop'); $task->link = $workshop->editform_url(); if ($workshop->grading_strategy_instance()->form_ready()) { $task->completed = true; } elseif ($workshop->phase > workshop::PHASE_SETUP) { $task->completed = false; } $phase->tasks['editform'] = $task; } if ($workshop->useexamples and has_capability('mod/workshop:manageexamples', $workshop->context, $userid)) { $task = new stdclass(); $task->title = get_string('prepareexamples', 'workshop'); if ($DB->count_records('workshop_submissions', array('example' => 1, 'workshopid' => $workshop->id)) > 0) { $task->completed = true; } elseif ($workshop->phase > workshop::PHASE_SETUP) { $task->completed = false; } $phase->tasks['prepareexamples'] = $task; } if (empty($phase->tasks) and $workshop->phase == workshop::PHASE_SETUP) { // if we are in the setup phase and there is no task (typical for students), let us // display some explanation what is going on $task = new stdclass(); $task->title = get_string('undersetup', 'workshop'); $task->completed = 'info'; $phase->tasks['setupinfo'] = $task; } $this->phases[workshop::PHASE_SETUP] = $phase; //--------------------------------------------------------- // setup | * SUBMISSION | assessment | evaluation | closed //--------------------------------------------------------- $phase = new stdclass(); $phase->title = get_string('phasesubmission', 'workshop'); $phase->tasks = array(); if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) { $task = new stdclass(); $task->title = get_string('taskinstructreviewers', 'workshop'); $task->link = $workshop->updatemod_url(); if (trim($workshop->instructreviewers)) { $task->completed = true; } elseif ($workshop->phase >= workshop::PHASE_ASSESSMENT) { $task->completed = false; } $phase->tasks['instructreviewers'] = $task; } if ($workshop->useexamples and $workshop->examplesmode == workshop::EXAMPLES_BEFORE_SUBMISSION and has_capability('mod/workshop:submit', $workshop->context, $userid, false) and !has_capability('mod/workshop:manageexamples', $workshop->context, $userid)) { $task = new stdclass(); $task->title = get_string('exampleassesstask', 'workshop'); $examples = $this->get_examples(); $a = new stdclass(); $a->expected = count($examples); $a->assessed = 0; foreach ($examples as $exampleid => $example) { if (!is_null($example->grade)) { $a->assessed++; } } $task->details = get_string('exampleassesstaskdetails', 'workshop', $a); if ($a->assessed == $a->expected) { $task->completed = true; } elseif ($workshop->phase >= workshop::PHASE_ASSESSMENT) { $task->completed = false; } $phase->tasks['examples'] = $task; } if (has_capability('mod/workshop:submit', $workshop->context, $userid, false)) { $task = new stdclass(); $task->title = get_string('tasksubmit', 'workshop'); $task->link = $workshop->submission_url(); if ($DB->record_exists('workshop_submissions', array('workshopid'=>$workshop->id, 'example'=>0, 'authorid'=>$userid))) { $task->completed = true; } elseif ($workshop->phase >= workshop::PHASE_ASSESSMENT) { $task->completed = false; } else { $task->completed = null; // still has a chance to submit } $phase->tasks['submit'] = $task; } if (has_capability('mod/workshop:allocate', $workshop->context, $userid)) { if ($workshop->phaseswitchassessment) { $task = new stdClass(); $allocator = $DB->get_record('workshopallocation_scheduled', array('workshopid' => $workshop->id)); if (empty($allocator)) { $task->completed = false; } else if ($allocator->enabled and is_null($allocator->resultstatus)) { $task->completed = true; } else if ($workshop->submissionend > time()) { $task->completed = null; } else { $task->completed = false; } $task->title = get_string('setup', 'workshopallocation_scheduled'); $task->link = $workshop->allocation_url('scheduled'); $phase->tasks['allocatescheduled'] = $task; } $task = new stdclass(); $task->title = get_string('allocate', 'workshop'); $task->link = $workshop->allocation_url(); $numofauthors = $workshop->count_potential_authors(false); $numofsubmissions = $DB->count_records('workshop_submissions', array('workshopid'=>$workshop->id, 'example'=>0)); $sql = 'SELECT COUNT(s.id) AS nonallocated FROM {workshop_submissions} s LEFT JOIN {workshop_assessments} a ON (a.submissionid=s.id) WHERE s.workshopid = :workshopid AND s.example=0 AND a.submissionid IS NULL'; $params['workshopid'] = $workshop->id; $numnonallocated = $DB->count_records_sql($sql, $params); if ($numofsubmissions == 0) { $task->completed = null; } elseif ($numnonallocated == 0) { $task->completed = true; } elseif ($workshop->phase > workshop::PHASE_SUBMISSION) { $task->completed = false; } else { $task->completed = null; // still has a chance to allocate } $a = new stdclass(); $a->expected = $numofauthors; $a->submitted = $numofsubmissions; $a->allocate = $numnonallocated; $task->details = get_string('allocatedetails', 'workshop', $a); unset($a); $phase->tasks['allocate'] = $task; if ($numofsubmissions < $numofauthors and $workshop->phase >= workshop::PHASE_SUBMISSION) { $task = new stdclass(); $task->title = get_string('someuserswosubmission', 'workshop'); $task->completed = 'info'; $phase->tasks['allocateinfo'] = $task; } } if ($workshop->submissionstart) { $task = new stdclass(); $task->title = get_string('submissionstartdatetime', 'workshop', workshop::timestamp_formats($workshop->submissionstart)); $task->completed = 'info'; $phase->tasks['submissionstartdatetime'] = $task; } if ($workshop->submissionend) { $task = new stdclass(); $task->title = get_string('submissionenddatetime', 'workshop', workshop::timestamp_formats($workshop->submissionend)); $task->completed = 'info'; $phase->tasks['submissionenddatetime'] = $task; } if (($workshop->submissionstart < time()) and $workshop->latesubmissions) { // If submission deadline has passed and late submissions are allowed, only display 'latesubmissionsallowed' text to // users (students) who have not submitted and users(teachers, admins) who can switch pahase.. if (has_capability('mod/workshop:switchphase', $workshop->context, $userid) || (!$workshop->get_submission_by_author($userid) && $workshop->submissionend < time())) { $task = new stdclass(); $task->title = get_string('latesubmissionsallowed', 'workshop'); $task->completed = 'info'; $phase->tasks['latesubmissionsallowed'] = $task; } } if (isset($phase->tasks['submissionstartdatetime']) or isset($phase->tasks['submissionenddatetime'])) { if (has_capability('mod/workshop:ignoredeadlines', $workshop->context, $userid)) { $task = new stdclass(); $task->title = get_string('deadlinesignored', 'workshop'); $task->completed = 'info'; $phase->tasks['deadlinesignored'] = $task; } } $this->phases[workshop::PHASE_SUBMISSION] = $phase; //--------------------------------------------------------- // setup | submission | * ASSESSMENT | evaluation | closed //--------------------------------------------------------- $phase = new stdclass(); $phase->title = get_string('phaseassessment', 'workshop'); $phase->tasks = array(); $phase->isreviewer = has_capability('mod/workshop:peerassess', $workshop->context, $userid); if ($workshop->phase == workshop::PHASE_SUBMISSION and $workshop->phaseswitchassessment and has_capability('mod/workshop:switchphase', $workshop->context, $userid)) { $task = new stdClass(); $task->title = get_string('switchphase30auto', 'mod_workshop', workshop::timestamp_formats($workshop->submissionend)); $task->completed = 'info'; $phase->tasks['autoswitchinfo'] = $task; } if ($workshop->useexamples and $workshop->examplesmode == workshop::EXAMPLES_BEFORE_ASSESSMENT and $phase->isreviewer and !has_capability('mod/workshop:manageexamples', $workshop->context, $userid)) { $task = new stdclass(); $task->title = get_string('exampleassesstask', 'workshop'); $examples = $workshop->get_examples_for_reviewer($userid); $a = new stdclass(); $a->expected = count($examples); $a->assessed = 0; foreach ($examples as $exampleid => $example) { if (!is_null($example->grade)) { $a->assessed++; } } $task->details = get_string('exampleassesstaskdetails', 'workshop', $a); if ($a->assessed == $a->expected) { $task->completed = true; } elseif ($workshop->phase > workshop::PHASE_ASSESSMENT) { $task->completed = false; } $phase->tasks['examples'] = $task; } if (empty($phase->tasks['examples']) or !empty($phase->tasks['examples']->completed)) { $phase->assessments = $workshop->get_assessments_by_reviewer($userid); $numofpeers = 0; // number of allocated peer-assessments $numofpeerstodo = 0; // number of peer-assessments to do $numofself = 0; // number of allocated self-assessments - should be 0 or 1 $numofselftodo = 0; // number of self-assessments to do - should be 0 or 1 foreach ($phase->assessments as $a) { if ($a->authorid == $userid) { $numofself++; if (is_null($a->grade)) { $numofselftodo++; } } else { $numofpeers++; if (is_null($a->grade)) { $numofpeerstodo++; } } } unset($a); if ($numofpeers) { $task = new stdclass(); if ($numofpeerstodo == 0) { $task->completed = true; } elseif ($workshop->phase > workshop::PHASE_ASSESSMENT) { $task->completed = false; } $a = new stdclass(); $a->total = $numofpeers; $a->todo = $numofpeerstodo; $task->title = get_string('taskassesspeers', 'workshop'); $task->details = get_string('taskassesspeersdetails', 'workshop', $a); unset($a); $phase->tasks['assesspeers'] = $task; } if ($workshop->useselfassessment and $numofself) { $task = new stdclass(); if ($numofselftodo == 0) { $task->completed = true; } elseif ($workshop->phase > workshop::PHASE_ASSESSMENT) { $task->completed = false; } $task->title = get_string('taskassessself', 'workshop'); $phase->tasks['assessself'] = $task; } } if ($workshop->assessmentstart) { $task = new stdclass(); $task->title = get_string('assessmentstartdatetime', 'workshop', workshop::timestamp_formats($workshop->assessmentstart)); $task->completed = 'info'; $phase->tasks['assessmentstartdatetime'] = $task; } if ($workshop->assessmentend) { $task = new stdclass(); $task->title = get_string('assessmentenddatetime', 'workshop', workshop::timestamp_formats($workshop->assessmentend)); $task->completed = 'info'; $phase->tasks['assessmentenddatetime'] = $task; } if (isset($phase->tasks['assessmentstartdatetime']) or isset($phase->tasks['assessmentenddatetime'])) { if (has_capability('mod/workshop:ignoredeadlines', $workshop->context, $userid)) { $task = new stdclass(); $task->title = get_string('deadlinesignored', 'workshop'); $task->completed = 'info'; $phase->tasks['deadlinesignored'] = $task; } } $this->phases[workshop::PHASE_ASSESSMENT] = $phase; //--------------------------------------------------------- // setup | submission | assessment | * EVALUATION | closed //--------------------------------------------------------- $phase = new stdclass(); $phase->title = get_string('phaseevaluation', 'workshop'); $phase->tasks = array(); if (has_capability('mod/workshop:overridegrades', $workshop->context)) { $expected = $workshop->count_potential_authors(false); $calculated = $DB->count_records_select('workshop_submissions', 'workshopid = ? AND (grade IS NOT NULL OR gradeover IS NOT NULL)', array($workshop->id)); $task = new stdclass(); $task->title = get_string('calculatesubmissiongrades', 'workshop'); $a = new stdclass(); $a->expected = $expected; $a->calculated = $calculated; $task->details = get_string('calculatesubmissiongradesdetails', 'workshop', $a); if ($calculated >= $expected) { $task->completed = true; } elseif ($workshop->phase > workshop::PHASE_EVALUATION) { $task->completed = false; } $phase->tasks['calculatesubmissiongrade'] = $task; $expected = $workshop->count_potential_reviewers(false); $calculated = $DB->count_records_select('workshop_aggregations', 'workshopid = ? AND gradinggrade IS NOT NULL', array($workshop->id)); $task = new stdclass(); $task->title = get_string('calculategradinggrades', 'workshop'); $a = new stdclass(); $a->expected = $expected; $a->calculated = $calculated; $task->details = get_string('calculategradinggradesdetails', 'workshop', $a); if ($calculated >= $expected) { $task->completed = true; } elseif ($workshop->phase > workshop::PHASE_EVALUATION) { $task->completed = false; } $phase->tasks['calculategradinggrade'] = $task; } elseif ($workshop->phase == workshop::PHASE_EVALUATION) { $task = new stdclass(); $task->title = get_string('evaluategradeswait', 'workshop'); $task->completed = 'info'; $phase->tasks['evaluateinfo'] = $task; } if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) { $task = new stdclass(); $task->title = get_string('taskconclusion', 'workshop'); $task->link = $workshop->updatemod_url(); if (trim($workshop->conclusion)) { $task->completed = true; } elseif ($workshop->phase >= workshop::PHASE_EVALUATION) { $task->completed = false; } $phase->tasks['conclusion'] = $task; } $this->phases[workshop::PHASE_EVALUATION] = $phase; //--------------------------------------------------------- // setup | submission | assessment | evaluation | * CLOSED //--------------------------------------------------------- $phase = new stdclass(); $phase->title = get_string('phaseclosed', 'workshop'); $phase->tasks = array(); $this->phases[workshop::PHASE_CLOSED] = $phase; // Polish data, set default values if not done explicitly foreach ($this->phases as $phasecode => $phase) { $phase->title = isset($phase->title) ? $phase->title : ''; $phase->tasks = isset($phase->tasks) ? $phase->tasks : array(); if ($phasecode == $workshop->phase) { $phase->active = true; } else { $phase->active = false; } if (!isset($phase->actions)) { $phase->actions = array(); } foreach ($phase->tasks as $taskcode => $task) { $task->title = isset($task->title) ? $task->title : ''; $task->link = isset($task->link) ? $task->link : null; $task->details = isset($task->details) ? $task->details : ''; $task->completed = isset($task->completed) ? $task->completed : null; } } // Add phase switching actions. if (has_capability('mod/workshop:switchphase', $workshop->context, $userid)) { $nextphases = array( workshop::PHASE_SETUP => workshop::PHASE_SUBMISSION, workshop::PHASE_SUBMISSION => workshop::PHASE_ASSESSMENT, workshop::PHASE_ASSESSMENT => workshop::PHASE_EVALUATION, workshop::PHASE_EVALUATION => workshop::PHASE_CLOSED, ); foreach ($this->phases as $phasecode => $phase) { if ($phase->active) { if (isset($nextphases[$workshop->phase])) { $task = new stdClass(); $task->title = get_string('switchphasenext', 'mod_workshop'); $task->link = $workshop->switchphase_url($nextphases[$workshop->phase]); $task->details = ''; $task->completed = null; $phase->tasks['switchtonextphase'] = $task; } } else { $action = new stdclass(); $action->type = 'switchphase'; $action->url = $workshop->switchphase_url($phasecode); $phase->actions[] = $action; } } } } /** * Returns example submissions to be assessed by the owner of the planner * * This is here to cache the DB query because the same list is needed later in view.php * * @see workshop::get_examples_for_reviewer() for the format of returned value * @return array */ public function get_examples() { if (is_null($this->examples)) { $this->examples = $this->workshop->get_examples_for_reviewer($this->userid); } return $this->examples; } } /** * Common base class for submissions and example submissions rendering * * Subclasses of this class convert raw submission record from * workshop_submissions table (as returned by {@see workshop::get_submission_by_id()} * for example) into renderable objects. */ abstract class workshop_submission_base { /** @var bool is the submission anonymous (i.e. contains author information) */ protected $anonymous; /* @var array of columns from workshop_submissions that are assigned as properties */ protected $fields = array(); /** @var workshop */ protected $workshop; /** * Copies the properties of the given database record into properties of $this instance * * @param workshop $workshop * @param stdClass $submission full record * @param bool $showauthor show the author-related information * @param array $options additional properties */ public function __construct(workshop $workshop, stdClass $submission, $showauthor = false) { $this->workshop = $workshop; foreach ($this->fields as $field) { if (!property_exists($submission, $field)) { throw new coding_exception('Submission record must provide public property ' . $field); } if (!property_exists($this, $field)) { throw new coding_exception('Renderable component must accept public property ' . $field); } $this->{$field} = $submission->{$field}; } if ($showauthor) { $this->anonymous = false; } else { $this->anonymize(); } } /** * Unsets all author-related properties so that the renderer does not have access to them * * Usually this is called by the contructor but can be called explicitely, too. */ public function anonymize() { $authorfields = explode(',', implode(',', \core_user\fields::get_picture_fields())); foreach ($authorfields as $field) { $prefixedusernamefield = 'author' . $field; unset($this->{$prefixedusernamefield}); } $this->anonymous = true; } /** * Does the submission object contain author-related information? * * @return null|boolean */ public function is_anonymous() { return $this->anonymous; } } /** * Renderable object containing a basic set of information needed to display the submission summary * * @see workshop_renderer::render_workshop_submission_summary */ class workshop_submission_summary extends workshop_submission_base implements renderable { /** @var int */ public $id; /** @var string */ public $title; /** @var string graded|notgraded */ public $status; /** @var int */ public $timecreated; /** @var int */ public $timemodified; /** @var int */ public $authorid; /** @var string */ public $authorfirstname; /** @var string */ public $authorlastname; /** @var string */ public $authorfirstnamephonetic; /** @var string */ public $authorlastnamephonetic; /** @var string */ public $authormiddlename; /** @var string */ public $authoralternatename; /** @var int */ public $authorpicture; /** @var string */ public $authorimagealt; /** @var string */ public $authoremail; /** @var moodle_url to display submission */ public $url; /** * @var array of columns from workshop_submissions that are assigned as properties * of instances of this class */ protected $fields = array( 'id', 'title', 'timecreated', 'timemodified', 'authorid', 'authorfirstname', 'authorlastname', 'authorfirstnamephonetic', 'authorlastnamephonetic', 'authormiddlename', 'authoralternatename', 'authorpicture', 'authorimagealt', 'authoremail'); } /** * Renderable object containing all the information needed to display the submission * * @see workshop_renderer::render_workshop_submission() */ class workshop_submission extends workshop_submission_summary implements renderable { /** @var string */ public $content; /** @var int */ public $contentformat; /** @var bool */ public $contenttrust; /** @var array */ public $attachment; /** * @var array of columns from workshop_submissions that are assigned as properties * of instances of this class */ protected $fields = array( 'id', 'title', 'timecreated', 'timemodified', 'content', 'contentformat', 'contenttrust', 'attachment', 'authorid', 'authorfirstname', 'authorlastname', 'authorfirstnamephonetic', 'authorlastnamephonetic', 'authormiddlename', 'authoralternatename', 'authorpicture', 'authorimagealt', 'authoremail'); } /** * Renderable object containing a basic set of information needed to display the example submission summary * * @see workshop::prepare_example_summary() * @see workshop_renderer::render_workshop_example_submission_summary() */ class workshop_example_submission_summary extends workshop_submission_base implements renderable { /** @var int */ public $id; /** @var string */ public $title; /** @var string graded|notgraded */ public $status; /** @var stdClass */ public $gradeinfo; /** @var moodle_url */ public $url; /** @var moodle_url */ public $editurl; /** @var string */ public $assesslabel; /** @var moodle_url */ public $assessurl; /** @var bool must be set explicitly by the caller */ public $editable = false; /** * @var array of columns from workshop_submissions that are assigned as properties * of instances of this class */ protected $fields = array('id', 'title'); /** * Example submissions are always anonymous * * @return true */ public function is_anonymous() { return true; } } /** * Renderable object containing all the information needed to display the example submission * * @see workshop_renderer::render_workshop_example_submission() */ class workshop_example_submission extends workshop_example_submission_summary implements renderable { /** @var string */ public $content; /** @var int */ public $contentformat; /** @var bool */ public $contenttrust; /** @var array */ public $attachment; /** * @var array of columns from workshop_submissions that are assigned as properties * of instances of this class */ protected $fields = array('id', 'title', 'content', 'contentformat', 'contenttrust', 'attachment'); } /** * Common base class for assessments rendering * * Subclasses of this class convert raw assessment record from * workshop_assessments table (as returned by {@see workshop::get_assessment_by_id()} * for example) into renderable objects. */ abstract class workshop_assessment_base { /** @var string the optional title of the assessment */ public $title = ''; /** @var workshop_assessment_form $form as returned by {@link workshop_strategy::get_assessment_form()} */ public $form; /** @var moodle_url */ public $url; /** @var float|null the real received grade */ public $realgrade = null; /** @var float the real maximum grade */ public $maxgrade; /** @var stdClass|null reviewer user info */ public $reviewer = null; /** @var stdClass|null assessed submission's author user info */ public $author = null; /** @var array of actions */ public $actions = array(); /* @var array of columns that are assigned as properties */ protected $fields = array(); /** @var workshop */ public $workshop; /** * Copies the properties of the given database record into properties of $this instance * * The $options keys are: showreviewer, showauthor * @param workshop $workshop * @param stdClass $assessment full record * @param array $options additional properties */ public function __construct(workshop $workshop, stdClass $record, array $options = array()) { $this->workshop = $workshop; $this->validate_raw_record($record); foreach ($this->fields as $field) { if (!property_exists($record, $field)) { throw new coding_exception('Assessment record must provide public property ' . $field); } if (!property_exists($this, $field)) { throw new coding_exception('Renderable component must accept public property ' . $field); } $this->{$field} = $record->{$field}; } if (!empty($options['showreviewer'])) { $this->reviewer = user_picture::unalias($record, null, 'revieweridx', 'reviewer'); } if (!empty($options['showauthor'])) { $this->author = user_picture::unalias($record, null, 'authorid', 'author'); } } /** * Adds a new action * * @param moodle_url $url action URL * @param string $label action label * @param string $method get|post */ public function add_action(moodle_url $url, $label, $method = 'get') { $action = new stdClass(); $action->url = $url; $action->label = $label; $action->method = $method; $this->actions[] = $action; } /** * Makes sure that we can cook the renderable component from the passed raw database record * * @param stdClass $assessment full assessment record * @throws coding_exception if the caller passed unexpected data */ protected function validate_raw_record(stdClass $record) { // nothing to do here } } /** * Represents a rendarable full assessment */ class workshop_assessment extends workshop_assessment_base implements renderable { /** @var int */ public $id; /** @var int */ public $submissionid; /** @var int */ public $weight; /** @var int */ public $timecreated; /** @var int */ public $timemodified; /** @var float */ public $grade; /** @var float */ public $gradinggrade; /** @var float */ public $gradinggradeover; /** @var string */ public $feedbackauthor; /** @var int */ public $feedbackauthorformat; /** @var int */ public $feedbackauthorattachment; /** @var array */ protected $fields = array('id', 'submissionid', 'weight', 'timecreated', 'timemodified', 'grade', 'gradinggrade', 'gradinggradeover', 'feedbackauthor', 'feedbackauthorformat', 'feedbackauthorattachment'); /** * Format the overall feedback text content * * False is returned if the overall feedback feature is disabled. Null is returned * if the overall feedback content has not been found. Otherwise, string with * formatted feedback text is returned. * * @return string|bool|null */ public function get_overall_feedback_content() { if ($this->workshop->overallfeedbackmode == 0) { return false; } if (trim($this->feedbackauthor) === '') { return null; } $content = file_rewrite_pluginfile_urls($this->feedbackauthor, 'pluginfile.php', $this->workshop->context->id, 'mod_workshop', 'overallfeedback_content', $this->id); $content = format_text($content, $this->feedbackauthorformat, array('overflowdiv' => true, 'context' => $this->workshop->context)); return $content; } /** * Prepares the list of overall feedback attachments * * Returns false if overall feedback attachments are not allowed. Otherwise returns * list of attachments (may be empty). * * @return bool|array of stdClass */ public function get_overall_feedback_attachments() { if ($this->workshop->overallfeedbackmode == 0) { return false; } if ($this->workshop->overallfeedbackfiles == 0) { return false; } if (empty($this->feedbackauthorattachment)) { return array(); } $attachments = array(); $fs = get_file_storage(); $files = $fs->get_area_files($this->workshop->context->id, 'mod_workshop', 'overallfeedback_attachment', $this->id); foreach ($files as $file) { if ($file->is_directory()) { continue; } $filepath = $file->get_filepath(); $filename = $file->get_filename(); $fileurl = moodle_url::make_pluginfile_url($this->workshop->context->id, 'mod_workshop', 'overallfeedback_attachment', $this->id, $filepath, $filename, true); $previewurl = new moodle_url(moodle_url::make_pluginfile_url($this->workshop->context->id, 'mod_workshop', 'overallfeedback_attachment', $this->id, $filepath, $filename, false), array('preview' => 'bigthumb')); $attachments[] = (object)array( 'filepath' => $filepath, 'filename' => $filename, 'fileurl' => $fileurl, 'previewurl' => $previewurl, 'mimetype' => $file->get_mimetype(), ); } return $attachments; } } /** * Represents a renderable training assessment of an example submission */ class workshop_example_assessment extends workshop_assessment implements renderable { /** * @see parent::validate_raw_record() */ protected function validate_raw_record(stdClass $record) { if ($record->weight != 0) { throw new coding_exception('Invalid weight of example submission assessment'); } parent::validate_raw_record($record); } } /** * Represents a renderable reference assessment of an example submission */ class workshop_example_reference_assessment extends workshop_assessment implements renderable { /** * @see parent::validate_raw_record() */ protected function validate_raw_record(stdClass $record) { if ($record->weight != 1) { throw new coding_exception('Invalid weight of the reference example submission assessment'); } parent::validate_raw_record($record); } } /** * Renderable message to be displayed to the user * * Message can contain an optional action link with a label that is supposed to be rendered * as a button or a link. * * @see workshop::renderer::render_workshop_message() */ class workshop_message implements renderable { const TYPE_INFO = 10; const TYPE_OK = 20; const TYPE_ERROR = 30; /** @var string */ protected $text = ''; /** @var int */ protected $type = self::TYPE_INFO; /** @var moodle_url */ protected $actionurl = null; /** @var string */ protected $actionlabel = ''; /** * @param string $text short text to be displayed * @param string $type optional message type info|ok|error */ public function __construct($text = null, $type = self::TYPE_INFO) { $this->set_text($text); $this->set_type($type); } /** * Sets the message text * * @param string $text short text to be displayed */ public function set_text($text) { $this->text = $text; } /** * Sets the message type * * @param int $type */ public function set_type($type = self::TYPE_INFO) { if (in_array($type, array(self::TYPE_OK, self::TYPE_ERROR, self::TYPE_INFO))) { $this->type = $type; } else { throw new coding_exception('Unknown message type.'); } } /** * Sets the optional message action * * @param moodle_url $url to follow on action * @param string $label action label */ public function set_action(moodle_url $url, $label) { $this->actionurl = $url; $this->actionlabel = $label; } /** * Returns message text with HTML tags quoted * * @return string */ public function get_message() { return s($this->text); } /** * Returns message type * * @return int */ public function get_type() { return $this->type; } /** * Returns action URL * * @return moodle_url|null */ public function get_action_url() { return $this->actionurl; } /** * Returns action label * * @return string */ public function get_action_label() { return $this->actionlabel; } } /** * Renderable component containing all the data needed to display the grading report */ class workshop_grading_report implements renderable { /** @var stdClass returned by {@see workshop::prepare_grading_report_data()} */ protected $data; /** @var stdClass rendering options */ protected $options; /** * Grades in $data must be already rounded to the set number of decimals or must be null * (in which later case, the [mod_workshop,nullgrade] string shall be displayed) * * @param stdClass $data prepared by {@link workshop::prepare_grading_report_data()} * @param stdClass $options display options (showauthornames, showreviewernames, sortby, sorthow, showsubmissiongrade, showgradinggrade) */ public function __construct(stdClass $data, stdClass $options) { $this->data = $data; $this->options = $options; } /** * @return stdClass grading report data */ public function get_data() { return $this->data; } /** * @return stdClass rendering options */ public function get_options() { return $this->options; } /** * Prepare the data to be exported to a external system via Web Services. * * This function applies extra capabilities checks. * @return stdClass the data ready for external systems */ public function export_data_for_external() { $data = $this->get_data(); $options = $this->get_options(); foreach ($data->grades as $reportdata) { // If we are in submission phase ignore the following data. if ($options->workshopphase == workshop::PHASE_SUBMISSION) { unset($reportdata->submissiongrade); unset($reportdata->gradinggrade); unset($reportdata->submissiongradeover); unset($reportdata->submissiongradeoverby); unset($reportdata->submissionpublished); unset($reportdata->reviewedby); unset($reportdata->reviewerof); continue; } if (!$options->showsubmissiongrade) { unset($reportdata->submissiongrade); unset($reportdata->submissiongradeover); } if (!$options->showgradinggrade and $tr == 0) { unset($reportdata->gradinggrade); } if (!$options->showreviewernames) { foreach ($reportdata->reviewedby as $reviewedby) { $reviewedby->userid = 0; } } if (!$options->showauthornames) { foreach ($reportdata->reviewerof as $reviewerof) { $reviewerof->userid = 0; } } } return $data; } } /** * Base class for renderable feedback for author and feedback for reviewer */ abstract class workshop_feedback { /** @var stdClass the user info */ protected $provider = null; /** @var string the feedback text */ protected $content = null; /** @var int format of the feedback text */ protected $format = null; /** * @return stdClass the user info */ public function get_provider() { if (is_null($this->provider)) { throw new coding_exception('Feedback provider not set'); } return $this->provider; } /** * @return string the feedback text */ public function get_content() { if (is_null($this->content)) { throw new coding_exception('Feedback content not set'); } return $this->content; } /** * @return int format of the feedback text */ public function get_format() { if (is_null($this->format)) { throw new coding_exception('Feedback text format not set'); } return $this->format; } } /** * Renderable feedback for the author of submission */ class workshop_feedback_author extends workshop_feedback implements renderable { /** * Extracts feedback from the given submission record * * @param stdClass $submission record as returned by {@see self::get_submission_by_id()} */ public function __construct(stdClass $submission) { $this->provider = user_picture::unalias($submission, null, 'gradeoverbyx', 'gradeoverby'); $this->content = $submission->feedbackauthor; $this->format = $submission->feedbackauthorformat; } } /** * Renderable feedback for the reviewer */ class workshop_feedback_reviewer extends workshop_feedback implements renderable { /** * Extracts feedback from the given assessment record * * @param stdClass $assessment record as returned by eg {@see self::get_assessment_by_id()} */ public function __construct(stdClass $assessment) { $this->provider = user_picture::unalias($assessment, null, 'gradinggradeoverbyx', 'overby'); $this->content = $assessment->feedbackreviewer; $this->format = $assessment->feedbackreviewerformat; } } /** * Holds the final grades for the activity as are stored in the gradebook */ class workshop_final_grades implements renderable { /** @var object the info from the gradebook about the grade for submission */ public $submissiongrade = null; /** @var object the infor from the gradebook about the grade for assessment */ public $assessmentgrade = null; } home/harasnat/www/learning/mod/imscp/locallib.php 0000604 00000033760 15062364250 0016114 0 ustar 00 <?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Private imscp module utility functions * * @package mod_imscp * @copyright 2009 Petr Skoda {@link http://skodak.org} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); require_once("$CFG->dirroot/mod/imscp/lib.php"); require_once("$CFG->libdir/filelib.php"); require_once("$CFG->libdir/resourcelib.php"); /** * Print IMSCP content to page. * * @param stdClass $imscp module instance. * @param stdClass $cm course module. * @param stdClass $course record. */ function imscp_print_content($imscp, $cm, $course) { global $PAGE, $CFG; $items = array_filter((array) unserialize_array($imscp->structure)); echo '<div id="imscp_layout">'; echo '<div id="imscp_toc">'; echo '<div id="imscp_tree"><ul>'; foreach ($items as $item) { echo imscp_htmllize_item($item, $imscp, $cm); } echo '</ul></div>'; echo '<div id="imscp_nav" style="display:none">'; echo '<button id="nav_skipprev"><<</button><button id="nav_prev"><</button><button id="nav_up">^</button>'; echo '<button id="nav_next">></button><button id="nav_skipnext">>></button>'; echo '</div>'; echo '</div>'; echo '</div>'; $PAGE->requires->js_init_call('M.mod_imscp.init'); } /** * Internal function - creates htmls structure suitable for YUI tree. */ function imscp_htmllize_item($item, $imscp, $cm) { global $CFG; if ($item['href']) { if (preg_match('|^https?://|', $item['href'])) { $url = $item['href']; } else { $context = context_module::instance($cm->id); $urlbase = "$CFG->wwwroot/pluginfile.php"; $path = '/'.$context->id.'/mod_imscp/content/'.$imscp->revision.'/'.$item['href']; $url = file_encode_url($urlbase, $path, false); } $result = "<li><a href=\"$url\">".$item['title'].'</a>'; } else { $result = '<li>'.$item['title']; } if ($item['subitems']) { $result .= '<ul>'; foreach ($item['subitems'] as $subitem) { $result .= imscp_htmllize_item($subitem, $imscp, $cm); } $result .= '</ul>'; } $result .= '</li>'; return $result; } /** * Parse an IMS content package's manifest file to determine its structure * @param object $imscp * @param object $context * @return array */ function imscp_parse_structure($imscp, $context) { $fs = get_file_storage(); if (!$manifestfile = $fs->get_file($context->id, 'mod_imscp', 'content', $imscp->revision, '/', 'imsmanifest.xml')) { return null; } return imscp_parse_manifestfile($manifestfile->get_content(), $imscp, $context); } /** * Parse the contents of a IMS package's manifest file. * @param string $manifestfilecontents the contents of the manifest file * @return array */ function imscp_parse_manifestfile($manifestfilecontents, $imscp, $context) { $doc = new DOMDocument(); if (!$doc->loadXML($manifestfilecontents, LIBXML_NONET)) { return null; } // We put this fake URL as base in order to detect path changes caused by xml:base attributes. $doc->documentURI = 'http://grrr/'; $xmlorganizations = $doc->getElementsByTagName('organizations'); if (empty($xmlorganizations->length)) { return null; } $default = null; if ($xmlorganizations->item(0)->attributes->getNamedItem('default')) { $default = $xmlorganizations->item(0)->attributes->getNamedItem('default')->nodeValue; } $xmlorganization = $doc->getElementsByTagName('organization'); if (empty($xmlorganization->length)) { return null; } $organization = null; foreach ($xmlorganization as $org) { if (is_null($organization)) { // Use first if default nor found. $organization = $org; } if (!$org->attributes->getNamedItem('identifier')) { continue; } if ($default === $org->attributes->getNamedItem('identifier')->nodeValue) { // Found default - use it. $organization = $org; break; } } // Load all resources. $resources = array(); $xmlresources = $doc->getElementsByTagName('resource'); foreach ($xmlresources as $res) { if (!$identifier = $res->attributes->getNamedItem('identifier')) { continue; } $identifier = $identifier->nodeValue; if ($xmlbase = $res->baseURI) { // Undo the fake URL, we are interested in relative links only. $xmlbase = str_replace('http://grrr/', '/', $xmlbase); $xmlbase = rtrim($xmlbase, '/').'/'; } else { $xmlbase = ''; } if (!$href = $res->attributes->getNamedItem('href')) { // If href not found look for <file href="help.htm"/>. $fileresources = $res->getElementsByTagName('file'); foreach ($fileresources as $file) { $href = $file->getAttribute('href'); } if (pathinfo($href, PATHINFO_EXTENSION) == 'xml') { $href = imscp_recursive_href($href, $imscp, $context); } if (empty($href)) { continue; } } else { $href = $href->nodeValue; } if (strpos($href, 'http://') !== 0) { $href = $xmlbase.$href; } // Item href cleanup - Some packages are poorly done and use \ in urls. $href = ltrim(strtr($href, "\\", '/'), '/'); $resources[$identifier] = $href; } $items = array(); foreach ($organization->childNodes as $child) { if ($child->nodeName === 'item') { if (!$item = imscp_recursive_item($child, 0, $resources)) { continue; } $items[] = $item; } } return $items; } function imscp_recursive_href($manifestfilename, $imscp, $context) { $fs = get_file_storage(); $dirname = dirname($manifestfilename); $filename = basename($manifestfilename); if ($dirname !== '/') { $dirname = "/$dirname/"; } if (!$manifestfile = $fs->get_file($context->id, 'mod_imscp', 'content', $imscp->revision, $dirname, $filename)) { return null; } $doc = new DOMDocument(); if (!$doc->loadXML($manifestfile->get_content(), LIBXML_NONET)) { return null; } $xmlresources = $doc->getElementsByTagName('resource'); foreach ($xmlresources as $res) { if (!$href = $res->attributes->getNamedItem('href')) { $fileresources = $res->getElementsByTagName('file'); foreach ($fileresources as $file) { $href = $file->getAttribute('href'); if (pathinfo($href, PATHINFO_EXTENSION) == 'xml') { $href = imscp_recursive_href($href, $imscp, $context); } if (pathinfo($href, PATHINFO_EXTENSION) == 'htm' || pathinfo($href, PATHINFO_EXTENSION) == 'html') { return $href; } } } } return $manifestfilename; } function imscp_recursive_item($xmlitem, $level, $resources) { $identifierref = ''; if ($identifierref = $xmlitem->attributes->getNamedItem('identifierref')) { $identifierref = $identifierref->nodeValue; } $title = '?'; $subitems = array(); foreach ($xmlitem->childNodes as $child) { if ($child->nodeName === 'title') { $title = $child->textContent; } else if ($child->nodeName === 'item') { if ($subitem = imscp_recursive_item($child, $level + 1, $resources)) { $subitems[] = $subitem; } } } return array('href' => isset($resources[$identifierref]) ? $resources[$identifierref] : '', 'title' => $title, 'level' => $level, 'subitems' => $subitems, ); } /** * Wrapper for function libxml_disable_entity_loader() deprecated in PHP 8 * * Method was deprecated in PHP 8 and it shows deprecation message. However it is still * required in the previous versions on PHP. While Moodle supports both PHP 7 and 8 we need to keep it. * @see https://php.watch/versions/8.0/libxml_disable_entity_loader-deprecation * * @param bool $value * @return bool * * @deprecated since Moodle 4.3 */ function imscp_libxml_disable_entity_loader(bool $value): bool { debugging(__FUNCTION__ . '() is deprecated, please do not use it any more', DEBUG_DEVELOPER); return true; } /** * File browsing support class * * @copyright 2009 Petr Skoda {@link http://skodak.org} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class imscp_file_info extends file_info { protected $course; protected $cm; protected $areas; protected $filearea; public function __construct($browser, $course, $cm, $context, $areas, $filearea) { parent::__construct($browser, $context); $this->course = $course; $this->cm = $cm; $this->areas = $areas; $this->filearea = $filearea; } /** * Returns list of standard virtual file/directory identification. * The difference from stored_file parameters is that null values * are allowed in all fields * @return array with keys contextid, filearea, itemid, filepath and filename */ public function get_params() { return array('contextid' => $this->context->id, 'component' => 'mod_imscp', 'filearea' => $this->filearea, 'itemid' => null, 'filepath' => null, 'filename' => null); } /** * Returns localised visible name. * @return string */ public function get_visible_name() { return $this->areas[$this->filearea]; } /** * Can I add new files or directories? * @return bool */ public function is_writable() { return false; } /** * Is directory? * @return bool */ public function is_directory() { return true; } /** * Returns list of children. * @return array of file_info instances */ public function get_children() { return $this->get_filtered_children('*', false, true); } /** * Help function to return files matching extensions or their count * * @param string|array $extensions, either '*' or array of lowercase extensions, i.e. array('.gif','.jpg') * @param bool|int $countonly if false returns the children, if an int returns just the * count of children but stops counting when $countonly number of children is reached * @param bool $returnemptyfolders if true returns items that don't have matching files inside * @return array|int array of file_info instances or the count */ private function get_filtered_children($extensions = '*', $countonly = false, $returnemptyfolders = false) { global $DB; $params = array('contextid' => $this->context->id, 'component' => 'mod_imscp', 'filearea' => $this->filearea); $sql = 'SELECT DISTINCT itemid FROM {files} WHERE contextid = :contextid AND component = :component AND filearea = :filearea'; if (!$returnemptyfolders) { $sql .= ' AND filename <> :emptyfilename'; $params['emptyfilename'] = '.'; } list($sql2, $params2) = $this->build_search_files_sql($extensions); $sql .= ' '.$sql2; $params = array_merge($params, $params2); if ($countonly !== false) { $sql .= ' ORDER BY itemid'; } $rs = $DB->get_recordset_sql($sql, $params); $children = array(); foreach ($rs as $record) { if ($child = $this->browser->get_file_info($this->context, 'mod_imscp', $this->filearea, $record->itemid)) { $children[] = $child; if ($countonly !== false && count($children) >= $countonly) { break; } } } $rs->close(); if ($countonly !== false) { return count($children); } return $children; } /** * Returns list of children which are either files matching the specified extensions * or folders that contain at least one such file. * * @param string|array $extensions, either '*' or array of lowercase extensions, i.e. array('.gif','.jpg') * @return array of file_info instances */ public function get_non_empty_children($extensions = '*') { return $this->get_filtered_children($extensions, false); } /** * Returns the number of children which are either files matching the specified extensions * or folders containing at least one such file. * * @param string|array $extensions, for example '*' or array('.gif','.jpg') * @param int $limit stop counting after at least $limit non-empty children are found * @return int */ public function count_non_empty_children($extensions = '*', $limit = 1) { return $this->get_filtered_children($extensions, $limit); } /** * Returns parent file_info instance * @return file_info or null for root */ public function get_parent() { return $this->browser->get_file_info($this->context); } } home/harasnat/www/learning/mod/assign/feedback/comments/locallib.php 0000604 00000061235 15062374464 0021644 0 ustar 00 <?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * This file contains the definition for the library class for comment feedback plugin * * @package assignfeedback_comments * @copyright 2012 NetSpot {@link http://www.netspot.com.au} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ use core_external\external_single_structure; use core_external\external_value; defined('MOODLE_INTERNAL') || die(); // File component for feedback comments. define('ASSIGNFEEDBACK_COMMENTS_COMPONENT', 'assignfeedback_comments'); // File area for feedback comments. define('ASSIGNFEEDBACK_COMMENTS_FILEAREA', 'feedback'); /** * Library class for comment feedback plugin extending feedback plugin base class. * * @package assignfeedback_comments * @copyright 2012 NetSpot {@link http://www.netspot.com.au} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class assign_feedback_comments extends assign_feedback_plugin { /** * Get the name of the online comment feedback plugin. * @return string */ public function get_name() { return get_string('pluginname', 'assignfeedback_comments'); } /** * Get the feedback comment from the database. * * @param int $gradeid * @return stdClass|false The feedback comments for the given grade if it exists. * False if it doesn't. */ public function get_feedback_comments($gradeid) { global $DB; return $DB->get_record('assignfeedback_comments', array('grade'=>$gradeid)); } /** * Get quickgrading form elements as html. * * @param int $userid The user id in the table this quickgrading element relates to * @param mixed $grade - The grade data - may be null if there are no grades for this user (yet) * @return mixed - A html string containing the html form elements required for quickgrading */ public function get_quickgrading_html($userid, $grade) { $commenttext = ''; if ($grade) { $feedbackcomments = $this->get_feedback_comments($grade->id); if ($feedbackcomments) { $commenttext = $feedbackcomments->commenttext; } } $pluginname = get_string('pluginname', 'assignfeedback_comments'); $labeloptions = array('for'=>'quickgrade_comments_' . $userid, 'class'=>'accesshide'); $textareaoptions = array('name'=>'quickgrade_comments_' . $userid, 'id'=>'quickgrade_comments_' . $userid, 'class'=>'quickgrade'); return html_writer::tag('label', $pluginname, $labeloptions) . html_writer::tag('textarea', $commenttext, $textareaoptions); } /** * Has the plugin quickgrading form element been modified in the current form submission? * * @param int $userid The user id in the table this quickgrading element relates to * @param stdClass $grade The grade * @return boolean - true if the quickgrading form element has been modified */ public function is_quickgrading_modified($userid, $grade) { $commenttext = ''; if ($grade) { $feedbackcomments = $this->get_feedback_comments($grade->id); if ($feedbackcomments) { $commenttext = $feedbackcomments->commenttext; } } // Note that this handles the difference between empty and not in the quickgrading // form at all (hidden column). $newvalue = optional_param('quickgrade_comments_' . $userid, false, PARAM_RAW); return ($newvalue !== false) && ($newvalue != $commenttext); } /** * Has the comment feedback been modified? * * @param stdClass $grade The grade object. * @param stdClass $data Data from the form submission. * @return boolean True if the comment feedback has been modified, else false. */ public function is_feedback_modified(stdClass $grade, stdClass $data) { $commenttext = ''; if ($grade) { $feedbackcomments = $this->get_feedback_comments($grade->id); if ($feedbackcomments) { $commenttext = $feedbackcomments->commenttext; } } $formtext = $data->assignfeedbackcomments_editor['text']; // Need to convert the form text to use @@PLUGINFILE@@ and format it so we can compare it with what is stored in the DB. if (isset($data->assignfeedbackcomments_editor['itemid'])) { $formtext = file_rewrite_urls_to_pluginfile($formtext, $data->assignfeedbackcomments_editor['itemid']); $formtext = format_text($formtext, FORMAT_HTML); } if ($commenttext == $formtext) { return false; } else { return true; } } /** * Override to indicate a plugin supports quickgrading. * * @return boolean - True if the plugin supports quickgrading */ public function supports_quickgrading() { return true; } /** * Return a list of the text fields that can be imported/exported by this plugin. * * @return array An array of field names and descriptions. (name=>description, ...) */ public function get_editor_fields() { return array('comments' => get_string('pluginname', 'assignfeedback_comments')); } /** * Get the saved text content from the editor. * * @param string $name * @param int $gradeid * @return string */ public function get_editor_text($name, $gradeid) { if ($name == 'comments') { $feedbackcomments = $this->get_feedback_comments($gradeid); if ($feedbackcomments) { return $feedbackcomments->commenttext; } } return ''; } /** * Get the saved text content from the editor. * * @param string $name * @param string $value * @param int $gradeid * @return string */ public function set_editor_text($name, $value, $gradeid) { global $DB; if ($name == 'comments') { $feedbackcomment = $this->get_feedback_comments($gradeid); if ($feedbackcomment) { $feedbackcomment->commenttext = $value; return $DB->update_record('assignfeedback_comments', $feedbackcomment); } else { $feedbackcomment = new stdClass(); $feedbackcomment->commenttext = $value; $feedbackcomment->commentformat = FORMAT_HTML; $feedbackcomment->grade = $gradeid; $feedbackcomment->assignment = $this->assignment->get_instance()->id; return $DB->insert_record('assignfeedback_comments', $feedbackcomment) > 0; } } return false; } /** * Save quickgrading changes. * * @param int $userid The user id in the table this quickgrading element relates to * @param stdClass $grade The grade * @return boolean - true if the grade changes were saved correctly */ public function save_quickgrading_changes($userid, $grade) { global $DB; $feedbackcomment = $this->get_feedback_comments($grade->id); $quickgradecomments = optional_param('quickgrade_comments_' . $userid, null, PARAM_RAW); if (!$quickgradecomments && $quickgradecomments !== '') { return true; } if ($feedbackcomment) { $feedbackcomment->commenttext = $quickgradecomments; return $DB->update_record('assignfeedback_comments', $feedbackcomment); } else { $feedbackcomment = new stdClass(); $feedbackcomment->commenttext = $quickgradecomments; $feedbackcomment->commentformat = FORMAT_HTML; $feedbackcomment->grade = $grade->id; $feedbackcomment->assignment = $this->assignment->get_instance()->id; return $DB->insert_record('assignfeedback_comments', $feedbackcomment) > 0; } } /** * Save the settings for feedback comments plugin * * @param stdClass $data * @return bool */ public function save_settings(stdClass $data) { $this->set_config('commentinline', !empty($data->assignfeedback_comments_commentinline)); return true; } /** * Get the default setting for feedback comments plugin * * @param MoodleQuickForm $mform The form to add elements to * @return void */ public function get_settings(MoodleQuickForm $mform) { $default = $this->get_config('commentinline'); if ($default === false) { // Apply the admin default if we don't have a value yet. $default = get_config('assignfeedback_comments', 'inline'); } $mform->addElement('selectyesno', 'assignfeedback_comments_commentinline', get_string('commentinline', 'assignfeedback_comments')); $mform->addHelpButton('assignfeedback_comments_commentinline', 'commentinline', 'assignfeedback_comments'); $mform->setDefault('assignfeedback_comments_commentinline', $default); // Disable comment online if comment feedback plugin is disabled. $mform->hideIf('assignfeedback_comments_commentinline', 'assignfeedback_comments_enabled', 'notchecked'); } /** * Convert the text from any submission plugin that has an editor field to * a format suitable for inserting in the feedback text field. * * @param stdClass $submission * @param stdClass $data - Form data to be filled with the converted submission text and format. * @param stdClass|null $grade * @return boolean - True if feedback text was set. */ protected function convert_submission_text_to_feedback($submission, $data, $grade) { global $DB; $format = false; $text = ''; foreach ($this->assignment->get_submission_plugins() as $plugin) { $fields = $plugin->get_editor_fields(); if ($plugin->is_enabled() && $plugin->is_visible() && !$plugin->is_empty($submission) && !empty($fields)) { $user = $DB->get_record('user', ['id' => $submission->userid]); // Copy the files to the feedback area. if ($files = $plugin->get_files($submission, $user)) { $fs = get_file_storage(); $component = 'assignfeedback_comments'; $filearea = ASSIGNFEEDBACK_COMMENTS_FILEAREA; $itemid = $grade->id; $fieldupdates = [ 'component' => $component, 'filearea' => $filearea, 'itemid' => $itemid ]; foreach ($files as $file) { if ($file instanceof stored_file) { // Before we create it, check that it doesn't already exist. if (!$fs->file_exists( $file->get_contextid(), $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename())) { $fs->create_file_from_storedfile($fieldupdates, $file); } } } } foreach ($fields as $key => $description) { $rawtext = clean_text($plugin->get_editor_text($key, $submission->id)); $newformat = $plugin->get_editor_format($key, $submission->id); if ($format !== false && $newformat != $format) { // There are 2 or more editor fields using different formats, set to plain as a fallback. $format = FORMAT_PLAIN; } else { $format = $newformat; } $text .= $rawtext; } } } if ($format === false) { $format = FORMAT_HTML; } $data->assignfeedbackcomments = $text; $data->assignfeedbackcommentsformat = $format; return true; } /** * Get form elements for the grading page * * @param stdClass|null $grade * @param MoodleQuickForm $mform * @param stdClass $data * @return bool true if elements were added to the form */ public function get_form_elements_for_user($grade, MoodleQuickForm $mform, stdClass $data, $userid) { $commentinlinenabled = $this->get_config('commentinline'); $submission = $this->assignment->get_user_submission($userid, false); $feedbackcomments = false; if ($grade) { $feedbackcomments = $this->get_feedback_comments($grade->id); } // Check first for data from last form submission in case grading validation failed. if (!empty($data->assignfeedbackcomments_editor['text'])) { $data->assignfeedbackcomments = $data->assignfeedbackcomments_editor['text']; $data->assignfeedbackcommentsformat = $data->assignfeedbackcomments_editor['format']; } else if ($feedbackcomments && !empty($feedbackcomments->commenttext)) { $data->assignfeedbackcomments = $feedbackcomments->commenttext; $data->assignfeedbackcommentsformat = $feedbackcomments->commentformat; } else { // No feedback given yet - maybe we need to copy the text from the submission? if (!empty($commentinlinenabled) && $submission) { $this->convert_submission_text_to_feedback($submission, $data, $grade); } else { // Set it to empty. $data->assignfeedbackcomments = ''; $data->assignfeedbackcommentsformat = FORMAT_HTML; } } file_prepare_standard_editor( $data, 'assignfeedbackcomments', $this->get_editor_options(), $this->assignment->get_context(), ASSIGNFEEDBACK_COMMENTS_COMPONENT, ASSIGNFEEDBACK_COMMENTS_FILEAREA, $grade->id ); $mform->addElement('editor', 'assignfeedbackcomments_editor', $this->get_name(), null, $this->get_editor_options()); return true; } /** * Saving the comment content into database. * * @param stdClass $grade * @param stdClass $data * @return bool */ public function save(stdClass $grade, stdClass $data) { global $DB; // Save the files. $data = file_postupdate_standard_editor( $data, 'assignfeedbackcomments', $this->get_editor_options(), $this->assignment->get_context(), ASSIGNFEEDBACK_COMMENTS_COMPONENT, ASSIGNFEEDBACK_COMMENTS_FILEAREA, $grade->id ); $feedbackcomment = $this->get_feedback_comments($grade->id); if ($feedbackcomment) { $feedbackcomment->commenttext = $data->assignfeedbackcomments; $feedbackcomment->commentformat = $data->assignfeedbackcommentsformat; return $DB->update_record('assignfeedback_comments', $feedbackcomment); } else { $feedbackcomment = new stdClass(); $feedbackcomment->commenttext = $data->assignfeedbackcomments; $feedbackcomment->commentformat = $data->assignfeedbackcommentsformat; $feedbackcomment->grade = $grade->id; $feedbackcomment->assignment = $this->assignment->get_instance()->id; return $DB->insert_record('assignfeedback_comments', $feedbackcomment) > 0; } } /** * Display the comment in the feedback table. * * @param stdClass $grade * @param bool $showviewlink Set to true to show a link to view the full feedback * @return string */ public function view_summary(stdClass $grade, & $showviewlink) { $feedbackcomments = $this->get_feedback_comments($grade->id); if ($feedbackcomments) { $text = $this->rewrite_feedback_comments_urls($feedbackcomments->commenttext, $grade->id); $text = format_text( $text, $feedbackcomments->commentformat, [ 'context' => $this->assignment->get_context() ] ); // Show the view all link if the text has been shortened. $short = shorten_text($text, 140); $showviewlink = $short != $text; return $short; } return ''; } /** * Display the comment in the feedback table. * * @param stdClass $grade * @return string */ public function view(stdClass $grade) { $feedbackcomments = $this->get_feedback_comments($grade->id); if ($feedbackcomments) { $text = $this->rewrite_feedback_comments_urls($feedbackcomments->commenttext, $grade->id); $text = format_text( $text, $feedbackcomments->commentformat, [ 'context' => $this->assignment->get_context() ] ); return $text; } return ''; } /** * Return true if this plugin can upgrade an old Moodle 2.2 assignment of this type * and version. * * @param string $type old assignment subtype * @param int $version old assignment version * @return bool True if upgrade is possible */ public function can_upgrade($type, $version) { if (($type == 'upload' || $type == 'uploadsingle' || $type == 'online' || $type == 'offline') && $version >= 2011112900) { return true; } return false; } /** * Upgrade the settings from the old assignment to the new plugin based one * * @param context $oldcontext - the context for the old assignment * @param stdClass $oldassignment - the data for the old assignment * @param string $log - can be appended to by the upgrade * @return bool was it a success? (false will trigger a rollback) */ public function upgrade_settings(context $oldcontext, stdClass $oldassignment, & $log) { if ($oldassignment->assignmenttype == 'online') { $this->set_config('commentinline', $oldassignment->var1); return true; } return true; } /** * Upgrade the feedback from the old assignment to the new one * * @param context $oldcontext - the database for the old assignment context * @param stdClass $oldassignment The data record for the old assignment * @param stdClass $oldsubmission The data record for the old submission * @param stdClass $grade The data record for the new grade * @param string $log Record upgrade messages in the log * @return bool true or false - false will trigger a rollback */ public function upgrade(context $oldcontext, stdClass $oldassignment, stdClass $oldsubmission, stdClass $grade, & $log) { global $DB; $feedbackcomments = new stdClass(); $feedbackcomments->commenttext = $oldsubmission->submissioncomment; $feedbackcomments->commentformat = FORMAT_HTML; $feedbackcomments->grade = $grade->id; $feedbackcomments->assignment = $this->assignment->get_instance()->id; if (!$DB->insert_record('assignfeedback_comments', $feedbackcomments) > 0) { $log .= get_string('couldnotconvertgrade', 'mod_assign', $grade->userid); return false; } return true; } /** * If this plugin adds to the gradebook comments field, it must specify the format of the text * of the comment * * Only one feedback plugin can push comments to the gradebook and that is chosen by the assignment * settings page. * * @param stdClass $grade The grade * @return int */ public function format_for_gradebook(stdClass $grade) { $feedbackcomments = $this->get_feedback_comments($grade->id); if ($feedbackcomments) { return $feedbackcomments->commentformat; } return FORMAT_MOODLE; } /** * If this plugin adds to the gradebook comments field, it must format the text * of the comment * * Only one feedback plugin can push comments to the gradebook and that is chosen by the assignment * settings page. * * @param stdClass $grade The grade * @return string */ public function text_for_gradebook(stdClass $grade) { $feedbackcomments = $this->get_feedback_comments($grade->id); if ($feedbackcomments) { return $feedbackcomments->commenttext; } return ''; } /** * Return any files this plugin wishes to save to the gradebook. * * @param stdClass $grade The assign_grades object from the db * @return array */ public function files_for_gradebook(stdClass $grade) : array { return [ 'contextid' => $this->assignment->get_context()->id, 'component' => ASSIGNFEEDBACK_COMMENTS_COMPONENT, 'filearea' => ASSIGNFEEDBACK_COMMENTS_FILEAREA, 'itemid' => $grade->id ]; } /** * The assignment has been deleted - cleanup * * @return bool */ public function delete_instance() { global $DB; // Will throw exception on failure. $DB->delete_records('assignfeedback_comments', array('assignment'=>$this->assignment->get_instance()->id)); return true; } /** * Returns true if there are no feedback comments for the given grade. * * @param stdClass $grade * @return bool */ public function is_empty(stdClass $grade) { return $this->view($grade) == ''; } /** * Get file areas returns a list of areas this plugin stores files * @return array - An array of fileareas (keys) and descriptions (values) */ public function get_file_areas() { return array(ASSIGNFEEDBACK_COMMENTS_FILEAREA => $this->get_name()); } /** * Return a description of external params suitable for uploading an feedback comment from a webservice. * * @return \core_external\external_description|null */ public function get_external_parameters() { $editorparams = array('text' => new external_value(PARAM_RAW, 'The text for this feedback.'), 'format' => new external_value(PARAM_INT, 'The format for this feedback')); $editorstructure = new external_single_structure($editorparams, 'Editor structure', VALUE_OPTIONAL); return array('assignfeedbackcomments_editor' => $editorstructure); } /** * Return the plugin configs for external functions. * * @return array the list of settings * @since Moodle 3.2 */ public function get_config_for_external() { return (array) $this->get_config(); } /** * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL. * * @param string $text the Text to check * @param int $gradeid The grade ID which refers to the id in the gradebook */ private function rewrite_feedback_comments_urls(string $text, int $gradeid) { return file_rewrite_pluginfile_urls( $text, 'pluginfile.php', $this->assignment->get_context()->id, ASSIGNFEEDBACK_COMMENTS_COMPONENT, ASSIGNFEEDBACK_COMMENTS_FILEAREA, $gradeid ); } /** * File format options. * * @return array */ private function get_editor_options() { global $COURSE; return [ 'subdirs' => 1, 'maxbytes' => $COURSE->maxbytes, 'accepted_types' => '*', 'context' => $this->assignment->get_context(), 'maxfiles' => EDITOR_UNLIMITED_FILES ]; } }
| ver. 1.4 |
Github
|
.
| PHP 8.1.33 | Генерация страницы: 0 |
proxy
|
phpinfo
|
Настройка