/mod/workshop/locallib.php
PHP | 4763 lines | 2755 code | 603 blank | 1405 comment | 409 complexity | 57809384207d00008d1ed586f87207a8 MD5 | raw file
Possible License(s): Apache-2.0, LGPL-2.1, BSD-3-Clause, MIT, GPL-3.0
Large files files are truncated, but you can click here to view the full file
- <?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;
- /**
- * 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, null, 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);
- 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 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)…
Large files files are truncated, but you can click here to view the full file