PageRenderTime 86ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 1ms

/mod/workshop/locallib.php

https://bitbucket.org/moodle/moodle
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
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * Library of internal classes and functions for module workshop
  18. *
  19. * All the workshop specific functions, needed to implement the module
  20. * logic, should go to here. Instead of having bunch of function named
  21. * workshop_something() taking the workshop instance as the first
  22. * parameter, we use a class workshop that provides all methods.
  23. *
  24. * @package mod_workshop
  25. * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
  26. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  27. */
  28. defined('MOODLE_INTERNAL') || die();
  29. require_once(__DIR__.'/lib.php'); // we extend this library here
  30. require_once($CFG->libdir . '/gradelib.php'); // we use some rounding and comparing routines here
  31. require_once($CFG->libdir . '/filelib.php');
  32. /**
  33. * Full-featured workshop API
  34. *
  35. * This wraps the workshop database record with a set of methods that are called
  36. * from the module itself. The class should be initialized right after you get
  37. * $workshop, $cm and $course records at the begining of the script.
  38. */
  39. class workshop {
  40. /** error status of the {@link self::add_allocation()} */
  41. const ALLOCATION_EXISTS = -9999;
  42. /** the internal code of the workshop phases as are stored in the database */
  43. const PHASE_SETUP = 10;
  44. const PHASE_SUBMISSION = 20;
  45. const PHASE_ASSESSMENT = 30;
  46. const PHASE_EVALUATION = 40;
  47. const PHASE_CLOSED = 50;
  48. /** the internal code of the examples modes as are stored in the database */
  49. const EXAMPLES_VOLUNTARY = 0;
  50. const EXAMPLES_BEFORE_SUBMISSION = 1;
  51. const EXAMPLES_BEFORE_ASSESSMENT = 2;
  52. /** @var stdclass workshop record from database */
  53. public $dbrecord;
  54. /** @var cm_info course module record */
  55. public $cm;
  56. /** @var stdclass course record */
  57. public $course;
  58. /** @var stdclass context object */
  59. public $context;
  60. /** @var int workshop instance identifier */
  61. public $id;
  62. /** @var string workshop activity name */
  63. public $name;
  64. /** @var string introduction or description of the activity */
  65. public $intro;
  66. /** @var int format of the {@link $intro} */
  67. public $introformat;
  68. /** @var string instructions for the submission phase */
  69. public $instructauthors;
  70. /** @var int format of the {@link $instructauthors} */
  71. public $instructauthorsformat;
  72. /** @var string instructions for the assessment phase */
  73. public $instructreviewers;
  74. /** @var int format of the {@link $instructreviewers} */
  75. public $instructreviewersformat;
  76. /** @var int timestamp of when the module was modified */
  77. public $timemodified;
  78. /** @var int current phase of workshop, for example {@link workshop::PHASE_SETUP} */
  79. public $phase;
  80. /** @var bool optional feature: students practise evaluating on example submissions from teacher */
  81. public $useexamples;
  82. /** @var bool optional feature: students perform peer assessment of others' work (deprecated, consider always enabled) */
  83. public $usepeerassessment;
  84. /** @var bool optional feature: students perform self assessment of their own work */
  85. public $useselfassessment;
  86. /** @var float number (10, 5) unsigned, the maximum grade for submission */
  87. public $grade;
  88. /** @var float number (10, 5) unsigned, the maximum grade for assessment */
  89. public $gradinggrade;
  90. /** @var string type of the current grading strategy used in this workshop, for example 'accumulative' */
  91. public $strategy;
  92. /** @var string the name of the evaluation plugin to use for grading grades calculation */
  93. public $evaluation;
  94. /** @var int number of digits that should be shown after the decimal point when displaying grades */
  95. public $gradedecimals;
  96. /** @var int number of allowed submission attachments and the files embedded into submission */
  97. public $nattachments;
  98. /** @var string list of allowed file types that are allowed to be embedded into submission */
  99. public $submissionfiletypes = null;
  100. /** @var bool allow submitting the work after the deadline */
  101. public $latesubmissions;
  102. /** @var int maximum size of the one attached file in bytes */
  103. public $maxbytes;
  104. /** @var int mode of example submissions support, for example {@link workshop::EXAMPLES_VOLUNTARY} */
  105. public $examplesmode;
  106. /** @var int if greater than 0 then the submission is not allowed before this timestamp */
  107. public $submissionstart;
  108. /** @var int if greater than 0 then the submission is not allowed after this timestamp */
  109. public $submissionend;
  110. /** @var int if greater than 0 then the peer assessment is not allowed before this timestamp */
  111. public $assessmentstart;
  112. /** @var int if greater than 0 then the peer assessment is not allowed after this timestamp */
  113. public $assessmentend;
  114. /** @var bool automatically switch to the assessment phase after the submissions deadline */
  115. public $phaseswitchassessment;
  116. /** @var string conclusion text to be displayed at the end of the activity */
  117. public $conclusion;
  118. /** @var int format of the conclusion text */
  119. public $conclusionformat;
  120. /** @var int the mode of the overall feedback */
  121. public $overallfeedbackmode;
  122. /** @var int maximum number of overall feedback attachments */
  123. public $overallfeedbackfiles;
  124. /** @var string list of allowed file types that can be attached to the overall feedback */
  125. public $overallfeedbackfiletypes = null;
  126. /** @var int maximum size of one file attached to the overall feedback */
  127. public $overallfeedbackmaxbytes;
  128. /** @var int Should the submission form show the text field? */
  129. public $submissiontypetext;
  130. /** @var int Should the submission form show the file attachment field? */
  131. public $submissiontypefile;
  132. /**
  133. * @var workshop_strategy grading strategy instance
  134. * Do not use directly, get the instance using {@link workshop::grading_strategy_instance()}
  135. */
  136. protected $strategyinstance = null;
  137. /**
  138. * @var workshop_evaluation grading evaluation instance
  139. * Do not use directly, get the instance using {@link workshop::grading_evaluation_instance()}
  140. */
  141. protected $evaluationinstance = null;
  142. /**
  143. * Initializes the workshop API instance using the data from DB
  144. *
  145. * Makes deep copy of all passed records properties.
  146. *
  147. * For unit testing only, $cm and $course may be set to null. This is so that
  148. * you can test without having any real database objects if you like. Not all
  149. * functions will work in this situation.
  150. *
  151. * @param stdClass $dbrecord Workshop instance data from {workshop} table
  152. * @param stdClass|cm_info $cm Course module record
  153. * @param stdClass $course Course record from {course} table
  154. * @param stdClass $context The context of the workshop instance
  155. */
  156. public function __construct(stdclass $dbrecord, $cm, $course, stdclass $context=null) {
  157. $this->dbrecord = $dbrecord;
  158. foreach ($this->dbrecord as $field => $value) {
  159. if (property_exists('workshop', $field)) {
  160. $this->{$field} = $value;
  161. }
  162. }
  163. if (is_null($cm) || is_null($course)) {
  164. throw new coding_exception('Must specify $cm and $course');
  165. }
  166. $this->course = $course;
  167. if ($cm instanceof cm_info) {
  168. $this->cm = $cm;
  169. } else {
  170. $modinfo = get_fast_modinfo($course);
  171. $this->cm = $modinfo->get_cm($cm->id);
  172. }
  173. if (is_null($context)) {
  174. $this->context = context_module::instance($this->cm->id);
  175. } else {
  176. $this->context = $context;
  177. }
  178. }
  179. ////////////////////////////////////////////////////////////////////////////////
  180. // Static methods //
  181. ////////////////////////////////////////////////////////////////////////////////
  182. /**
  183. * Return list of available allocation methods
  184. *
  185. * @return array Array ['string' => 'string'] of localized allocation method names
  186. */
  187. public static function installed_allocators() {
  188. $installed = core_component::get_plugin_list('workshopallocation');
  189. $forms = array();
  190. foreach ($installed as $allocation => $allocationpath) {
  191. if (file_exists($allocationpath . '/lib.php')) {
  192. $forms[$allocation] = get_string('pluginname', 'workshopallocation_' . $allocation);
  193. }
  194. }
  195. // usability - make sure that manual allocation appears the first
  196. if (isset($forms['manual'])) {
  197. $m = array('manual' => $forms['manual']);
  198. unset($forms['manual']);
  199. $forms = array_merge($m, $forms);
  200. }
  201. return $forms;
  202. }
  203. /**
  204. * Returns an array of options for the editors that are used for submitting and assessing instructions
  205. *
  206. * @param stdClass $context
  207. * @uses EDITOR_UNLIMITED_FILES hard-coded value for the 'maxfiles' option
  208. * @return array
  209. */
  210. public static function instruction_editors_options(stdclass $context) {
  211. return array('subdirs' => 1, 'maxbytes' => 0, 'maxfiles' => -1,
  212. 'changeformat' => 1, 'context' => $context, 'noclean' => 1, 'trusttext' => 0);
  213. }
  214. /**
  215. * Given the percent and the total, returns the number
  216. *
  217. * @param float $percent from 0 to 100
  218. * @param float $total the 100% value
  219. * @return float
  220. */
  221. public static function percent_to_value($percent, $total) {
  222. if ($percent < 0 or $percent > 100) {
  223. throw new coding_exception('The percent can not be less than 0 or higher than 100');
  224. }
  225. return $total * $percent / 100;
  226. }
  227. /**
  228. * Returns an array of numeric values that can be used as maximum grades
  229. *
  230. * @return array Array of integers
  231. */
  232. public static function available_maxgrades_list() {
  233. $grades = array();
  234. for ($i=100; $i>=0; $i--) {
  235. $grades[$i] = $i;
  236. }
  237. return $grades;
  238. }
  239. /**
  240. * Returns the localized list of supported examples modes
  241. *
  242. * @return array
  243. */
  244. public static function available_example_modes_list() {
  245. $options = array();
  246. $options[self::EXAMPLES_VOLUNTARY] = get_string('examplesvoluntary', 'workshop');
  247. $options[self::EXAMPLES_BEFORE_SUBMISSION] = get_string('examplesbeforesubmission', 'workshop');
  248. $options[self::EXAMPLES_BEFORE_ASSESSMENT] = get_string('examplesbeforeassessment', 'workshop');
  249. return $options;
  250. }
  251. /**
  252. * Returns the list of available grading strategy methods
  253. *
  254. * @return array ['string' => 'string']
  255. */
  256. public static function available_strategies_list() {
  257. $installed = core_component::get_plugin_list('workshopform');
  258. $forms = array();
  259. foreach ($installed as $strategy => $strategypath) {
  260. if (file_exists($strategypath . '/lib.php')) {
  261. $forms[$strategy] = get_string('pluginname', 'workshopform_' . $strategy);
  262. }
  263. }
  264. return $forms;
  265. }
  266. /**
  267. * Returns the list of available grading evaluation methods
  268. *
  269. * @return array of (string)name => (string)localized title
  270. */
  271. public static function available_evaluators_list() {
  272. $evals = array();
  273. foreach (core_component::get_plugin_list_with_file('workshopeval', 'lib.php', false) as $eval => $evalpath) {
  274. $evals[$eval] = get_string('pluginname', 'workshopeval_' . $eval);
  275. }
  276. return $evals;
  277. }
  278. /**
  279. * Return an array of possible values of assessment dimension weight
  280. *
  281. * @return array of integers 0, 1, 2, ..., 16
  282. */
  283. public static function available_dimension_weights_list() {
  284. $weights = array();
  285. for ($i=16; $i>=0; $i--) {
  286. $weights[$i] = $i;
  287. }
  288. return $weights;
  289. }
  290. /**
  291. * Return an array of possible values of assessment weight
  292. *
  293. * Note there is no real reason why the maximum value here is 16. It used to be 10 in
  294. * workshop 1.x and I just decided to use the same number as in the maximum weight of
  295. * a single assessment dimension.
  296. * The value looks reasonable, though. Teachers who would want to assign themselves
  297. * higher weight probably do not want peer assessment really...
  298. *
  299. * @return array of integers 0, 1, 2, ..., 16
  300. */
  301. public static function available_assessment_weights_list() {
  302. $weights = array();
  303. for ($i=16; $i>=0; $i--) {
  304. $weights[$i] = $i;
  305. }
  306. return $weights;
  307. }
  308. /**
  309. * Helper function returning the greatest common divisor
  310. *
  311. * @param int $a
  312. * @param int $b
  313. * @return int
  314. */
  315. public static function gcd($a, $b) {
  316. return ($b == 0) ? ($a):(self::gcd($b, $a % $b));
  317. }
  318. /**
  319. * Helper function returning the least common multiple
  320. *
  321. * @param int $a
  322. * @param int $b
  323. * @return int
  324. */
  325. public static function lcm($a, $b) {
  326. return ($a / self::gcd($a,$b)) * $b;
  327. }
  328. /**
  329. * Returns an object suitable for strings containing dates/times
  330. *
  331. * The returned object contains properties date, datefullshort, datetime, ... containing the given
  332. * timestamp formatted using strftimedate, strftimedatefullshort, strftimedatetime, ... from the
  333. * current lang's langconfig.php
  334. * This allows translators and administrators customize the date/time format.
  335. *
  336. * @param int $timestamp the timestamp in UTC
  337. * @return stdclass
  338. */
  339. public static function timestamp_formats($timestamp) {
  340. $formats = array('date', 'datefullshort', 'dateshort', 'datetime',
  341. 'datetimeshort', 'daydate', 'daydatetime', 'dayshort', 'daytime',
  342. 'monthyear', 'recent', 'recentfull', 'time');
  343. $a = new stdclass();
  344. foreach ($formats as $format) {
  345. $a->{$format} = userdate($timestamp, get_string('strftime'.$format, 'langconfig'));
  346. }
  347. $day = userdate($timestamp, '%Y%m%d', 99, false);
  348. $today = userdate(time(), '%Y%m%d', 99, false);
  349. $tomorrow = userdate(time() + DAYSECS, '%Y%m%d', 99, false);
  350. $yesterday = userdate(time() - DAYSECS, '%Y%m%d', 99, false);
  351. $distance = (int)round(abs(time() - $timestamp) / DAYSECS);
  352. if ($day == $today) {
  353. $a->distanceday = get_string('daystoday', 'workshop');
  354. } elseif ($day == $yesterday) {
  355. $a->distanceday = get_string('daysyesterday', 'workshop');
  356. } elseif ($day < $today) {
  357. $a->distanceday = get_string('daysago', 'workshop', $distance);
  358. } elseif ($day == $tomorrow) {
  359. $a->distanceday = get_string('daystomorrow', 'workshop');
  360. } elseif ($day > $today) {
  361. $a->distanceday = get_string('daysleft', 'workshop', $distance);
  362. }
  363. return $a;
  364. }
  365. /**
  366. * Converts the argument into an array (list) of file extensions.
  367. *
  368. * The list can be separated by whitespace, end of lines, commas colons and semicolons.
  369. * Empty values are not returned. Values are converted to lowercase.
  370. * Duplicates are removed. Glob evaluation is not supported.
  371. *
  372. * @deprecated since Moodle 3.4 MDL-56486 - please use the {@link core_form\filetypes_util}
  373. * @param string|array $extensions list of file extensions
  374. * @return array of strings
  375. */
  376. public static function normalize_file_extensions($extensions) {
  377. debugging('The method workshop::normalize_file_extensions() is deprecated.
  378. Please use the methods provided by the \core_form\filetypes_util class.', DEBUG_DEVELOPER);
  379. if ($extensions === '') {
  380. return array();
  381. }
  382. if (!is_array($extensions)) {
  383. $extensions = preg_split('/[\s,;:"\']+/', $extensions, null, PREG_SPLIT_NO_EMPTY);
  384. }
  385. foreach ($extensions as $i => $extension) {
  386. $extension = str_replace('*.', '', $extension);
  387. $extension = strtolower($extension);
  388. $extension = ltrim($extension, '.');
  389. $extension = trim($extension);
  390. $extensions[$i] = $extension;
  391. }
  392. foreach ($extensions as $i => $extension) {
  393. if (strpos($extension, '*') !== false or strpos($extension, '?') !== false) {
  394. unset($extensions[$i]);
  395. }
  396. }
  397. $extensions = array_filter($extensions, 'strlen');
  398. $extensions = array_keys(array_flip($extensions));
  399. foreach ($extensions as $i => $extension) {
  400. $extensions[$i] = '.'.$extension;
  401. }
  402. return $extensions;
  403. }
  404. /**
  405. * Cleans the user provided list of file extensions.
  406. *
  407. * @deprecated since Moodle 3.4 MDL-56486 - please use the {@link core_form\filetypes_util}
  408. * @param string $extensions
  409. * @return string
  410. */
  411. public static function clean_file_extensions($extensions) {
  412. debugging('The method workshop::clean_file_extensions() is deprecated.
  413. Please use the methods provided by the \core_form\filetypes_util class.', DEBUG_DEVELOPER);
  414. $extensions = self::normalize_file_extensions($extensions);
  415. foreach ($extensions as $i => $extension) {
  416. $extensions[$i] = ltrim($extension, '.');
  417. }
  418. return implode(', ', $extensions);
  419. }
  420. /**
  421. * Check given file types and return invalid/unknown ones.
  422. *
  423. * Empty allowlist is interpretted as "any extension is valid".
  424. *
  425. * @deprecated since Moodle 3.4 MDL-56486 - please use the {@link core_form\filetypes_util}
  426. * @param string|array $extensions list of file extensions
  427. * @param string|array $allowlist list of valid extensions
  428. * @return array list of invalid extensions not found in the allowlist
  429. */
  430. public static function invalid_file_extensions($extensions, $allowlist) {
  431. debugging('The method workshop::invalid_file_extensions() is deprecated.
  432. Please use the methods provided by the \core_form\filetypes_util class.', DEBUG_DEVELOPER);
  433. $extensions = self::normalize_file_extensions($extensions);
  434. $allowlist = self::normalize_file_extensions($allowlist);
  435. if (empty($extensions) or empty($allowlist)) {
  436. return array();
  437. }
  438. // Return those items from $extensions that are not present in $allowlist.
  439. return array_keys(array_diff_key(array_flip($extensions), array_flip($allowlist)));
  440. }
  441. /**
  442. * Is the file have allowed to be uploaded to the workshop?
  443. *
  444. * Empty allowlist is interpretted as "any file type is allowed" rather
  445. * than "no file can be uploaded".
  446. *
  447. * @deprecated since Moodle 3.4 MDL-56486 - please use the {@link core_form\filetypes_util}
  448. * @param string $filename the file name
  449. * @param string|array $allowlist list of allowed file extensions
  450. * @return false
  451. */
  452. public static function is_allowed_file_type($filename, $allowlist) {
  453. debugging('The method workshop::is_allowed_file_type() is deprecated.
  454. Please use the methods provided by the \core_form\filetypes_util class.', DEBUG_DEVELOPER);
  455. $allowlist = self::normalize_file_extensions($allowlist);
  456. if (empty($allowlist)) {
  457. return true;
  458. }
  459. $haystack = strrev(trim(strtolower($filename)));
  460. foreach ($allowlist as $extension) {
  461. if (strpos($haystack, strrev($extension)) === 0) {
  462. // The file name ends with the extension.
  463. return true;
  464. }
  465. }
  466. return false;
  467. }
  468. ////////////////////////////////////////////////////////////////////////////////
  469. // Workshop API //
  470. ////////////////////////////////////////////////////////////////////////////////
  471. /**
  472. * Fetches all enrolled users with the capability mod/workshop:submit in the current workshop
  473. *
  474. * The returned objects contain properties required by user_picture and are ordered by lastname, firstname.
  475. * Only users with the active enrolment are returned.
  476. *
  477. * @param bool $musthavesubmission if true, return only users who have already submitted
  478. * @param int $groupid 0 means ignore groups, any other value limits the result by group id
  479. * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
  480. * @param int $limitnum return a subset containing this number of records (optional, required if $limitfrom is set)
  481. * @return array array[userid] => stdClass
  482. */
  483. public function get_potential_authors($musthavesubmission=true, $groupid=0, $limitfrom=0, $limitnum=0) {
  484. global $DB;
  485. list($sql, $params) = $this->get_users_with_capability_sql('mod/workshop:submit', $musthavesubmission, $groupid);
  486. if (empty($sql)) {
  487. return array();
  488. }
  489. list($sort, $sortparams) = users_order_by_sql('tmp');
  490. $sql = "SELECT *
  491. FROM ($sql) tmp
  492. ORDER BY $sort";
  493. return $DB->get_records_sql($sql, array_merge($params, $sortparams), $limitfrom, $limitnum);
  494. }
  495. /**
  496. * Returns the total number of users that would be fetched by {@link self::get_potential_authors()}
  497. *
  498. * @param bool $musthavesubmission if true, count only users who have already submitted
  499. * @param int $groupid 0 means ignore groups, any other value limits the result by group id
  500. * @return int
  501. */
  502. public function count_potential_authors($musthavesubmission=true, $groupid=0) {
  503. global $DB;
  504. list($sql, $params) = $this->get_users_with_capability_sql('mod/workshop:submit', $musthavesubmission, $groupid);
  505. if (empty($sql)) {
  506. return 0;
  507. }
  508. $sql = "SELECT COUNT(*)
  509. FROM ($sql) tmp";
  510. return $DB->count_records_sql($sql, $params);
  511. }
  512. /**
  513. * Fetches all enrolled users with the capability mod/workshop:peerassess in the current workshop
  514. *
  515. * The returned objects contain properties required by user_picture and are ordered by lastname, firstname.
  516. * Only users with the active enrolment are returned.
  517. *
  518. * @param bool $musthavesubmission if true, return only users who have already submitted
  519. * @param int $groupid 0 means ignore groups, any other value limits the result by group id
  520. * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
  521. * @param int $limitnum return a subset containing this number of records (optional, required if $limitfrom is set)
  522. * @return array array[userid] => stdClass
  523. */
  524. public function get_potential_reviewers($musthavesubmission=false, $groupid=0, $limitfrom=0, $limitnum=0) {
  525. global $DB;
  526. list($sql, $params) = $this->get_users_with_capability_sql('mod/workshop:peerassess', $musthavesubmission, $groupid);
  527. if (empty($sql)) {
  528. return array();
  529. }
  530. list($sort, $sortparams) = users_order_by_sql('tmp');
  531. $sql = "SELECT *
  532. FROM ($sql) tmp
  533. ORDER BY $sort";
  534. return $DB->get_records_sql($sql, array_merge($params, $sortparams), $limitfrom, $limitnum);
  535. }
  536. /**
  537. * Returns the total number of users that would be fetched by {@link self::get_potential_reviewers()}
  538. *
  539. * @param bool $musthavesubmission if true, count only users who have already submitted
  540. * @param int $groupid 0 means ignore groups, any other value limits the result by group id
  541. * @return int
  542. */
  543. public function count_potential_reviewers($musthavesubmission=false, $groupid=0) {
  544. global $DB;
  545. list($sql, $params) = $this->get_users_with_capability_sql('mod/workshop:peerassess', $musthavesubmission, $groupid);
  546. if (empty($sql)) {
  547. return 0;
  548. }
  549. $sql = "SELECT COUNT(*)
  550. FROM ($sql) tmp";
  551. return $DB->count_records_sql($sql, $params);
  552. }
  553. /**
  554. * Fetches all enrolled users that are authors or reviewers (or both) in the current workshop
  555. *
  556. * The returned objects contain properties required by user_picture and are ordered by lastname, firstname.
  557. * Only users with the active enrolment are returned.
  558. *
  559. * @see self::get_potential_authors()
  560. * @see self::get_potential_reviewers()
  561. * @param bool $musthavesubmission if true, return only users who have already submitted
  562. * @param int $groupid 0 means ignore groups, any other value limits the result by group id
  563. * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
  564. * @param int $limitnum return a subset containing this number of records (optional, required if $limitfrom is set)
  565. * @return array array[userid] => stdClass
  566. */
  567. public function get_participants($musthavesubmission=false, $groupid=0, $limitfrom=0, $limitnum=0) {
  568. global $DB;
  569. list($sql, $params) = $this->get_participants_sql($musthavesubmission, $groupid);
  570. if (empty($sql)) {
  571. return array();
  572. }
  573. list($sort, $sortparams) = users_order_by_sql('tmp');
  574. $sql = "SELECT *
  575. FROM ($sql) tmp
  576. ORDER BY $sort";
  577. return $DB->get_records_sql($sql, array_merge($params, $sortparams), $limitfrom, $limitnum);
  578. }
  579. /**
  580. * Returns the total number of records that would be returned by {@link self::get_participants()}
  581. *
  582. * @param bool $musthavesubmission if true, return only users who have already submitted
  583. * @param int $groupid 0 means ignore groups, any other value limits the result by group id
  584. * @return int
  585. */
  586. public function count_participants($musthavesubmission=false, $groupid=0) {
  587. global $DB;
  588. list($sql, $params) = $this->get_participants_sql($musthavesubmission, $groupid);
  589. if (empty($sql)) {
  590. return 0;
  591. }
  592. $sql = "SELECT COUNT(*)
  593. FROM ($sql) tmp";
  594. return $DB->count_records_sql($sql, $params);
  595. }
  596. /**
  597. * Checks if the given user is an actively enrolled participant in the workshop
  598. *
  599. * @param int $userid, defaults to the current $USER
  600. * @return boolean
  601. */
  602. public function is_participant($userid=null) {
  603. global $USER, $DB;
  604. if (is_null($userid)) {
  605. $userid = $USER->id;
  606. }
  607. list($sql, $params) = $this->get_participants_sql();
  608. if (empty($sql)) {
  609. return false;
  610. }
  611. $sql = "SELECT COUNT(*)
  612. FROM {user} uxx
  613. JOIN ({$sql}) pxx ON uxx.id = pxx.id
  614. WHERE uxx.id = :uxxid";
  615. $params['uxxid'] = $userid;
  616. if ($DB->count_records_sql($sql, $params)) {
  617. return true;
  618. }
  619. return false;
  620. }
  621. /**
  622. * Groups the given users by the group membership
  623. *
  624. * This takes the module grouping settings into account. If a grouping is
  625. * set, returns only groups withing the course module grouping. Always
  626. * returns group [0] with all the given users.
  627. *
  628. * @param array $users array[userid] => stdclass{->id ->lastname ->firstname}
  629. * @return array array[groupid][userid] => stdclass{->id ->lastname ->firstname}
  630. */
  631. public function get_grouped($users) {
  632. global $DB;
  633. global $CFG;
  634. $grouped = array(); // grouped users to be returned
  635. if (empty($users)) {
  636. return $grouped;
  637. }
  638. if ($this->cm->groupingid) {
  639. // Group workshop set to specified grouping - only consider groups
  640. // within this grouping, and leave out users who aren't members of
  641. // this grouping.
  642. $groupingid = $this->cm->groupingid;
  643. // All users that are members of at least one group will be
  644. // added into a virtual group id 0
  645. $grouped[0] = array();
  646. } else {
  647. $groupingid = 0;
  648. // there is no need to be member of a group so $grouped[0] will contain
  649. // all users
  650. $grouped[0] = $users;
  651. }
  652. $gmemberships = groups_get_all_groups($this->cm->course, array_keys($users), $groupingid,
  653. 'gm.id,gm.groupid,gm.userid');
  654. foreach ($gmemberships as $gmembership) {
  655. if (!isset($grouped[$gmembership->groupid])) {
  656. $grouped[$gmembership->groupid] = array();
  657. }
  658. $grouped[$gmembership->groupid][$gmembership->userid] = $users[$gmembership->userid];
  659. $grouped[0][$gmembership->userid] = $users[$gmembership->userid];
  660. }
  661. return $grouped;
  662. }
  663. /**
  664. * Returns the list of all allocations (i.e. assigned assessments) in the workshop
  665. *
  666. * Assessments of example submissions are ignored
  667. *
  668. * @return array
  669. */
  670. public function get_allocations() {
  671. global $DB;
  672. $sql = 'SELECT a.id, a.submissionid, a.reviewerid, s.authorid
  673. FROM {workshop_assessments} a
  674. INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
  675. WHERE s.example = 0 AND s.workshopid = :workshopid';
  676. $params = array('workshopid' => $this->id);
  677. return $DB->get_records_sql($sql, $params);
  678. }
  679. /**
  680. * Returns the total number of records that would be returned by {@link self::get_submissions()}
  681. *
  682. * @param mixed $authorid int|array|'all' If set to [array of] integer, return submission[s] of the given user[s] only
  683. * @param int $groupid If non-zero, return only submissions by authors in the specified group
  684. * @return int number of records
  685. */
  686. public function count_submissions($authorid='all', $groupid=0) {
  687. global $DB;
  688. $params = array('workshopid' => $this->id);
  689. $sql = "SELECT COUNT(s.id)
  690. FROM {workshop_submissions} s
  691. JOIN {user} u ON (s.authorid = u.id)";
  692. if ($groupid) {
  693. $sql .= " JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = :groupid)";
  694. $params['groupid'] = $groupid;
  695. }
  696. $sql .= " WHERE s.example = 0 AND s.workshopid = :workshopid";
  697. if ('all' === $authorid) {
  698. // no additional conditions
  699. } elseif (!empty($authorid)) {
  700. list($usql, $uparams) = $DB->get_in_or_equal($authorid, SQL_PARAMS_NAMED);
  701. $sql .= " AND authorid $usql";
  702. $params = array_merge($params, $uparams);
  703. } else {
  704. // $authorid is empty
  705. return 0;
  706. }
  707. return $DB->count_records_sql($sql, $params);
  708. }
  709. /**
  710. * Returns submissions from this workshop
  711. *
  712. * Fetches data from {workshop_submissions} and adds some useful information from other
  713. * tables. Does not return textual fields to prevent possible memory lack issues.
  714. *
  715. * @see self::count_submissions()
  716. * @param mixed $authorid int|array|'all' If set to [array of] integer, return submission[s] of the given user[s] only
  717. * @param int $groupid If non-zero, return only submissions by authors in the specified group
  718. * @param int $limitfrom Return a subset of records, starting at this point (optional)
  719. * @param int $limitnum Return a subset containing this many records in total (optional, required if $limitfrom is set)
  720. * @return array of records or an empty array
  721. */
  722. public function get_submissions($authorid='all', $groupid=0, $limitfrom=0, $limitnum=0) {
  723. global $DB;
  724. $userfieldsapi = \core_user\fields::for_userpic();
  725. $authorfields = $userfieldsapi->get_sql('u', false, 'author', 'authoridx', false)->selects;
  726. $gradeoverbyfields = $userfieldsapi->get_sql('t', false, 'over', 'gradeoverbyx', false)->selects;
  727. $params = array('workshopid' => $this->id);
  728. $sql = "SELECT s.id, s.workshopid, s.example, s.authorid, s.timecreated, s.timemodified,
  729. s.title, s.grade, s.gradeover, s.gradeoverby, s.published,
  730. $authorfields, $gradeoverbyfields
  731. FROM {workshop_submissions} s
  732. JOIN {user} u ON (s.authorid = u.id)";
  733. if ($groupid) {
  734. $sql .= " JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = :groupid)";
  735. $params['groupid'] = $groupid;
  736. }
  737. $sql .= " LEFT JOIN {user} t ON (s.gradeoverby = t.id)
  738. WHERE s.example = 0 AND s.workshopid = :workshopid";
  739. if ('all' === $authorid) {
  740. // no additional conditions
  741. } elseif (!empty($authorid)) {
  742. list($usql, $uparams) = $DB->get_in_or_equal($authorid, SQL_PARAMS_NAMED);
  743. $sql .= " AND authorid $usql";
  744. $params = array_merge($params, $uparams);
  745. } else {
  746. // $authorid is empty
  747. return array();
  748. }
  749. list($sort, $sortparams) = users_order_by_sql('u');
  750. $sql .= " ORDER BY $sort";
  751. return $DB->get_records_sql($sql, array_merge($params, $sortparams), $limitfrom, $limitnum);
  752. }
  753. /**
  754. * Returns submissions from this workshop that are viewable by the current user (except example submissions).
  755. *
  756. * @param mixed $authorid int|array If set to [array of] integer, return submission[s] of the given user[s] only
  757. * @param int $groupid If non-zero, return only submissions by authors in the specified group. 0 for all groups.
  758. * @param int $limitfrom Return a subset of records, starting at this point (optional)
  759. * @param int $limitnum Return a subset containing this many records in total (optional, required if $limitfrom is set)
  760. * @return array of records and the total submissions count
  761. * @since Moodle 3.4
  762. */
  763. public function get_visible_submissions($authorid = 0, $groupid = 0, $limitfrom = 0, $limitnum = 0) {
  764. global $DB, $USER;
  765. $submissions = array();
  766. $select = "SELECT s.*";
  767. $selectcount = "SELECT COUNT(s.id)";
  768. $from = " FROM {workshop_submissions} s";
  769. $params = array('workshopid' => $this->id);
  770. // Check if the passed group (or all groups when groupid is 0) is visible by the current user.
  771. if (!groups_group_visible($groupid, $this->course, $this->cm)) {
  772. return array($submissions, 0);
  773. }
  774. if ($groupid) {
  775. $from .= " JOIN {groups_members} gm ON (gm.userid = s.authorid AND gm.groupid = :groupid)";
  776. $params['groupid'] = $groupid;
  777. }
  778. $where = " WHERE s.workshopid = :workshopid AND s.example = 0";
  779. if (!has_capability('mod/workshop:viewallsubmissions', $this->context)) {
  780. // Check published submissions.
  781. $workshopclosed = $this->phase == self::PHASE_CLOSED;
  782. $canviewpublished = has_capability('mod/workshop:viewpublishedsubmissions', $this->context);
  783. if ($workshopclosed && $canviewpublished) {
  784. $published = " OR s.published = 1";
  785. } else {
  786. $published = '';
  787. }
  788. // Always get submissions I did or I provided feedback to.
  789. $where .= " AND (s.authorid = :authorid OR s.gradeoverby = :graderid $published)";
  790. $params['authorid'] = $USER->id;
  791. $params['graderid'] = $USER->id;
  792. }
  793. // Now, user filtering.
  794. if (!empty($authorid)) {
  795. list($usql, $uparams) = $DB->get_in_or_equal($authorid, SQL_PARAMS_NAMED);
  796. $where .= " AND s.authorid $usql";
  797. $params = array_merge($params, $uparams);
  798. }
  799. $order = " ORDER BY s.timecreated";
  800. $totalcount = $DB->count_records_sql($selectcount.$from.$where, $params);
  801. if ($totalcount) {
  802. $submissions = $DB->get_records_sql($select.$from.$where.$order, $params, $limitfrom, $limitnum);
  803. }
  804. return array($submissions, $totalcount);
  805. }
  806. /**
  807. * Returns a submission record with the author's data
  808. *
  809. * @param int $id submission id
  810. * @return stdclass
  811. */
  812. public function get_submission_by_id($id) {
  813. global $DB;
  814. // we intentionally check the workshopid here, too, so the workshop can't touch submissions
  815. // from other instances
  816. $userfieldsapi = \core_user\fields::for_userpic();
  817. $authorfields = $userfieldsapi->get_sql('u', false, 'author', 'authoridx', false)->selects;
  818. $gradeoverbyfields = $userfieldsapi->get_sql('g', false, 'gradeoverby', 'gradeoverbyx', false)->selects;
  819. $sql = "SELECT s.*, $authorfields, $gradeoverbyfields
  820. FROM {workshop_submissions} s
  821. INNER JOIN {user} u ON (s.authorid = u.id)
  822. LEFT JOIN {user} g ON (s.gradeoverby = g.id)
  823. WHERE s.example = 0 AND s.workshopid = :workshopid AND s.id = :id";
  824. $params = array('workshopid' => $this->id, 'id' => $id);
  825. return $DB->get_record_sql($sql, $params, MUST_EXIST);
  826. }
  827. /**
  828. * Returns a submission submitted by the given author
  829. *
  830. * @param int $id author id
  831. * @return stdclass|false
  832. */
  833. public function get_submission_by_author($authorid) {
  834. global $DB;
  835. if (empty($authorid)) {
  836. return false;
  837. }
  838. $userfieldsapi = \core_user\fields::for_userpic();
  839. $authorfields = $userfieldsapi->get_sql('u', false, 'author', 'authoridx', false)->selects;
  840. $gradeoverbyfields = $userfieldsapi->get_sql('g', false, 'gradeoverby', 'gradeoverbyx', false)->selects;
  841. $sql = "SELECT s.*, $authorfields, $gradeoverbyfields
  842. FROM {workshop_submissions} s
  843. INNER JOIN {user} u ON (s.authorid = u.id)
  844. LEFT JOIN {user} g ON (s.gradeoverby = g.id)
  845. WHERE s.example = 0 AND s.workshopid = :workshopid AND s.authorid = :authorid";
  846. $params = array('workshopid' => $this->id, 'authorid' => $authorid);
  847. return $DB->get_record_sql($sql, $params);
  848. }
  849. /**
  850. * Returns published submissions with their authors data
  851. *
  852. * @return array of stdclass
  853. */
  854. public function get_published_submissions($orderby='finalgrade DESC') {
  855. global $DB;
  856. $userfieldsapi = \core_user\fields::for_userpic();
  857. $authorfields = $userfieldsapi->get_sql('u', false, 'author', 'authoridx', false)->selects;
  858. $sql = "SELECT s.id, s.authorid, s.timecreated, s.timemodified,
  859. s.title, s.grade, s.gradeover, COALESCE(s.gradeover,s.grade) AS finalgrade,
  860. $authorfields
  861. FROM {workshop_submissions} s
  862. INNER JOIN {user} u ON (s.authorid = u.id)
  863. WHERE s.example = 0 AND s.workshopid = :workshopid AND s.published = 1
  864. ORDER BY $orderby";
  865. $params = array('workshopid' => $this->id);
  866. return $DB->get_records_sql($sql, $params);
  867. }
  868. /**
  869. * Returns full record of the given example submission
  870. *
  871. * @param int $id example submission od
  872. * @return object
  873. */
  874. public function get_example_by_id($id) {
  875. global $DB;
  876. return $DB->get_record('workshop_submissions',
  877. array('id' => $id, 'workshopid' => $this->id, 'example' => 1), '*', MUST_EXIST);
  878. }
  879. /**
  880. * Returns the list of example submissions in this workshop with reference assessments attached
  881. *
  882. * @return array of objects or an empty array
  883. * @see workshop::prepare_example_summary()
  884. */
  885. public function get_examples_for_manager() {
  886. global $DB;
  887. $sql = 'SELECT s.id, s.title,
  888. a.id AS assessmentid, a.grade, a.gradinggrade
  889. FROM {workshop_submissions} s
  890. LEFT JOIN {workshop_assessments} a ON (a.submissionid = s.id AND a.weight = 1)
  891. WHERE s.example = 1 AND s.workshopid = :workshopid
  892. ORDER BY s.title';
  893. return $DB->get_records_sql($sql, array('workshopid' => $this->id));
  894. }
  895. /**
  896. * Returns the list of all example submissions in this workshop with the information of assessments done by the given user
  897. *
  898. * @param int $reviewerid user id
  899. * @return array of objects, indexed by example submission id
  900. * @see workshop::prepare_example_summary()
  901. */
  902. public function get_examples_for_reviewer($reviewerid) {
  903. global $DB;
  904. if (empty($reviewerid)) {
  905. return false;
  906. }
  907. $sql = 'SELECT s.id, s.title,
  908. a.id AS assessmentid, a.grade, a.gradinggrade
  909. FROM {workshop_submissions} s
  910. LEFT JOIN {workshop_assessments} a ON (a.submissionid = s.id AND a.reviewerid = :reviewerid AND a.weight = 0)
  911. WHERE s.example = 1 AND s.workshopid = :workshopid
  912. ORDER BY s.title';
  913. return $DB->get_records_sql($sql, array('workshopid' => $this->id, 'reviewerid' => $reviewerid));
  914. }
  915. /**
  916. * Prepares renderable submission component
  917. *
  918. * @param stdClass $record required by {@see workshop_submission}
  919. * @param bool $showauthor show the author-related information
  920. * @return workshop_submission
  921. */
  922. public function prepare_submission(stdClass $record, $showauthor = false) {
  923. $submission = new workshop_submission($this, $record, $showauthor);
  924. $submission->url = $this->submission_url($record->id);
  925. return $submission;
  926. }
  927. /**
  928. * Prepares renderable submission summary component
  929. *
  930. * @param stdClass $record required by {@see workshop_submission_summary}
  931. * @param bool $showauthor show the author-related information
  932. * @return workshop_submission_summary
  933. */
  934. public function prepare_submission_summary(stdClass $record, $showauthor = false) {
  935. $summary = new workshop_submission_summary($this, $record, $showauthor);
  936. $summary->url = $this->submission_url($record->id);
  937. return $summary;
  938. }
  939. /**
  940. * Prepares renderable example submission component
  941. *
  942. * @param stdClass $record required by {@see workshop_example_submission}
  943. * @return workshop_example_submission
  944. */
  945. public function prepare_example_submission(stdClass $record) {
  946. $example = new workshop_example_submission($this, $record);
  947. return $example;
  948. }
  949. /**
  950. * Prepares renderable example submission summary component
  951. *
  952. * If the example is editable, the caller must set the 'editable' flag explicitly.
  953. *
  954. * @param stdClass $example as returned by {@link workshop::get_examples_for_manager()} or {@link workshop::get_examples_for_reviewer()}
  955. * @return workshop_example_submission_summary to be rendered
  956. */
  957. public function prepare_example_summary(stdClass $example) {
  958. $summary = new workshop_example_submission_summary($this, $example);
  959. if (is_null($example->grade)) {
  960. $summary->status = 'notgraded';
  961. $summary->assesslabel = get_string('assess', 'workshop');
  962. } else {
  963. $summary->status = 'graded';
  964. $summary->assesslabel = get_string('reassess', 'workshop');
  965. }
  966. $summary->gradeinfo = new stdclass();
  967. $summary->gradeinfo->received = $this->real_grade($example->grade);
  968. $summary->gradeinfo->max = $this->real_grade(100);
  969. $summary->url = new moodle_url($this->exsubmission_url($example->id));
  970. $summary->editurl = new moodle_url($this->exsubmission_url($example->id), array('edit' => 'on'));
  971. $summary->assessurl = new moodle_url($this->exsubmission_url($example->id), array('assess' => 'on', 'sesskey' => sesskey()));
  972. return $summary;
  973. }
  974. /**
  975. * Prepares renderable assessment component
  976. *
  977. * The $options array supports the following keys:
  978. * showauthor - should the author user info be available for the renderer
  979. * showreviewer - should the reviewer user info be available for the renderer
  980. * showform - show the assessment form if it is available
  981. * showweight - should the assessment weight be available for the renderer
  982. *
  983. * @param stdClass $record as returned by eg {@link self::get_assessment_by_id()}
  984. * @param workshop_assessment_form|null $form as returned by {@link workshop_strategy::get_assessment_form()}
  985. * @param array $options
  986. * @return workshop_assessment
  987. */
  988. public function prepare_assessment(stdClass $record, $form, array $options = array()) {
  989. $assessment = new workshop_assessment($this, $record, $options);
  990. $assessment->url = $this->assess_url($record->id);
  991. $assessment->maxgrade = $this->real_grade(100);
  992. if (!empty($options['showform']) and !($form instanceof workshop_assessment_form)) {
  993. debugging('Not a valid instance of workshop_assessment_form supplied', DEBUG_DEVELOPER);
  994. }
  995. if (!empty($options['showform']) and ($form instanceof workshop_assessment_form)) {
  996. $assessment->form = $form;
  997. }
  998. if (empty($options['showweight'])) {
  999. $assessment->weight = null;
  1000. }
  1001. if (!is_null($record->grade)) {
  1002. $assessment->realgrade = $this->real_grade($record->grade);
  1003. }
  1004. return $assessment;
  1005. }
  1006. /**
  1007. * Prepares renderable example submission's assessment component
  1008. *
  1009. * The $options array supports the following keys:
  1010. * showauthor - should the author user info be available for the renderer
  1011. * showreviewer - should the reviewer user info be available for the renderer
  1012. * showform - show the assessment form if it is available
  1013. *
  1014. * @param stdClass $record as returned by eg {@link self::get_assessment_by_id()}
  1015. * @param workshop_assessment_form|null $form as returned by {@link workshop_strategy::get_assessment_form()}
  1016. * @param array $options
  1017. * @return workshop_example_assessment
  1018. */
  1019. public function prepare_example_assessment(stdClass $record, $form = null, array $options = array()) {
  1020. $assessment = new workshop_example_assessment($this, $record, $options);
  1021. $assessment->url = $this->exassess_url($record->id);
  1022. $assessment->maxgrade = $this->real_grade(100);
  1023. if (!empty($options['showform']) and !($form instanceof workshop_assessment_form)) {
  1024. debugging('Not a valid instance of workshop_assessment_form supplied', DEBUG_DEVELOPER);
  1025. }
  1026. if (!empty($options['showform']) and ($form instanceof workshop_assessment_form)) {
  1027. $assessment->form = $form;
  1028. }
  1029. if (!is_null($record->grade)) {
  1030. $assessment->realgrade = $this->real_grade($record->grade);
  1031. }
  1032. $assessment->weight = null;
  1033. return $assessment;
  1034. }
  1035. /**
  1036. * Prepares renderable example submission's reference assessment component
  1037. *
  1038. * The $options array supports the following keys:
  1039. * showauthor - should the author user info be available for the renderer
  1040. * showreviewer - should the reviewer user info be available for the renderer
  1041. * showform - show the assessment form if it is available
  1042. *
  1043. * @param stdClass $record as returned by eg {@link self::get_assessment_by_id()}
  1044. * @param workshop_assessment_form|null $form as returned by {@link workshop_strategy::get_assessment_form()}
  1045. * @param array $options
  1046. * @return workshop_example_reference_assessment
  1047. */
  1048. public function prepare_example_reference_assessment(stdClass $record, $form = null, array $options = array()) {
  1049. $assessment = new workshop_example_reference_assessment($this, $record, $options);
  1050. $assessment->maxgrade = $this->real_grade(100);
  1051. if (!empty($options['showform']) and !($form instanceof workshop_assessment_form)) {
  1052. debugging('Not a valid instance of workshop_assessment_form supplied', DEBUG_DEVELOPER);
  1053. }
  1054. if (!empty($options['showform']) and ($form instanceof workshop_assessment_form)) {
  1055. $assessment->form = $form;
  1056. }
  1057. if (!is_null($record->grade)) {
  1058. $assessment->realgrade = $this->real_grade($record->grade);
  1059. }
  1060. $assessment->weight = null;
  1061. return $assessment;
  1062. }
  1063. /**
  1064. * Removes the submission and all relevant data
  1065. *
  1066. * @param stdClass $submission record to delete
  1067. * @return void
  1068. */
  1069. public function delete_submission(stdclass $submission) {
  1070. global $DB;
  1071. $assessments = $DB->get_records('workshop_assessments', array('submissionid' => $submission->id), '', 'id');
  1072. $this->delete_assessment(array_keys($assessments));
  1073. $fs = get_file_storage();
  1074. $fs->delete_area_files($this->context->id, 'mod_workshop', 'submission_content', $submission->id);
  1075. $fs->delete_area_files($this->context->id, 'mod_workshop', 'submission_attachment', $submission->id);
  1076. $DB->delete_records('workshop_submissions', array('id' => $submission->id));
  1077. // Event information.
  1078. $params = array(
  1079. 'context' => $this->context,
  1080. 'courseid' => $this->course->id,
  1081. 'relateduserid' => $submission->authorid,
  1082. 'other' => array(
  1083. 'submissiontitle' => $submission->title
  1084. )
  1085. );
  1086. $params['objectid'] = $submission->id;
  1087. $event = \mod_workshop\event\submission_deleted::create($params);
  1088. $event->add_record_snapshot('workshop', $this->dbrecord);
  1089. $event->trigger();
  1090. }
  1091. /**
  1092. * Returns the list of all assessments in the workshop with some data added
  1093. *
  1094. * Fetches data from {workshop_assessments} and adds some useful information from other
  1095. * tables. The returned object does not contain textual fields (i.e. comments) to prevent memory
  1096. * lack issues.
  1097. *
  1098. * @return array [assessmentid] => assessment stdclass
  1099. */
  1100. public function get_all_assessments() {
  1101. global $DB;
  1102. $userfieldsapi = \core_user\fields::for_userpic();
  1103. $reviewerfields = $userfieldsapi->get_sql('reviewer', false, '', 'revieweridx', false)->selects;
  1104. $authorfields = $userfieldsapi->get_sql('author', false, 'author', 'authorid', false)->selects;
  1105. $overbyfields = $userfieldsapi->get_sql('overby', false, 'overby', 'gradinggradeoverbyx', false)->selects;
  1106. list($sort, $params) = users_order_by_sql('reviewer');
  1107. $sql = "SELECT a.id, a.submissionid, a.reviewerid, a.timecreated, a.timemodified,
  1108. a.grade, a.gradinggrade, a.gradinggradeover, a.gradinggradeoverby,
  1109. $reviewerfields, $authorfields, $overbyfields,
  1110. s.title
  1111. FROM {workshop_assessments} a
  1112. INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
  1113. INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
  1114. INNER JOIN {user} author ON (s.authorid = author.id)
  1115. LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
  1116. WHERE s.workshopid = :workshopid AND s.example = 0
  1117. ORDER BY $sort";
  1118. $params['workshopid'] = $this->id;
  1119. return $DB->get_records_sql($sql, $params);
  1120. }
  1121. /**
  1122. * Get the complete information about the given assessment
  1123. *
  1124. * @param int $id Assessment ID
  1125. * @return stdclass
  1126. */
  1127. public function get_assessment_by_id($id) {
  1128. global $DB;
  1129. $userfieldsapi = \core_user\fields::for_userpic();
  1130. $reviewerfields = $userfieldsapi->get_sql('reviewer', false, 'reviewer', 'revieweridx', false)->selects;
  1131. $authorfields = $userfieldsapi->get_sql('author', false, 'author', 'authorid', false)->selects;
  1132. $overbyfields = $userfieldsapi->get_sql('overby', false, 'overby', 'gradinggradeoverbyx', false)->selects;
  1133. $sql = "SELECT a.*, s.title, $reviewerfields, $authorfields, $overbyfields
  1134. FROM {workshop_assessments} a
  1135. INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
  1136. INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
  1137. INNER JOIN {user} author ON (s.authorid = author.id)
  1138. LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
  1139. WHERE a.id = :id AND s.workshopid = :workshopid";
  1140. $params = array('id' => $id, 'workshopid' => $this->id);
  1141. return $DB->get_record_sql($sql, $params, MUST_EXIST);
  1142. }
  1143. /**
  1144. * Get the complete information about the user's assessment of the given submission
  1145. *
  1146. * @param int $sid submission ID
  1147. * @param int $uid user ID of the reviewer
  1148. * @return false|stdclass false if not found, stdclass otherwise
  1149. */
  1150. public function get_assessment_of_submission_by_user($submissionid, $reviewerid) {
  1151. global $DB;
  1152. $userfieldsapi = \core_user\fields::for_userpic();
  1153. $reviewerfields = $userfieldsapi->get_sql('reviewer', false, 'reviewer', 'revieweridx', false)->selects;
  1154. $authorfields = $userfieldsapi->get_sql('author', false, 'author', 'authorid', false)->selects;
  1155. $overbyfields = $userfieldsapi->get_sql('overby', false, 'overby', 'gradinggradeoverbyx', false)->selects;
  1156. $sql = "SELECT a.*, s.title, $reviewerfields, $authorfields, $overbyfields
  1157. FROM {workshop_assessments} a
  1158. INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
  1159. INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id AND s.example = 0)
  1160. INNER JOIN {user} author ON (s.authorid = author.id)
  1161. LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
  1162. WHERE s.id = :sid AND reviewer.id = :rid AND s.workshopid = :workshopid";
  1163. $params = array('sid' => $submissionid, 'rid' => $reviewerid, 'workshopid' => $this->id);
  1164. return $DB->get_record_sql($sql, $params, IGNORE_MISSING);
  1165. }
  1166. /**
  1167. * Get the complete information about all assessments of the given submission
  1168. *
  1169. * @param int $submissionid
  1170. * @return array
  1171. */
  1172. public function get_assessments_of_submission($submissionid) {
  1173. global $DB;
  1174. $userfieldsapi = \core_user\fields::for_userpic();
  1175. $reviewerfields = $userfieldsapi->get_sql('reviewer', false, 'reviewer', 'revieweridx', false)->selects;
  1176. $overbyfields = $userfieldsapi->get_sql('overby', false, 'overby', 'gradinggradeoverbyx', false)->selects;
  1177. list($sort, $params) = users_order_by_sql('reviewer');
  1178. $sql = "SELECT a.*, s.title, $reviewerfields, $overbyfields
  1179. FROM {workshop_assessments} a
  1180. INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
  1181. INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
  1182. LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
  1183. WHERE s.example = 0 AND s.id = :submissionid AND s.workshopid = :workshopid
  1184. ORDER BY $sort";
  1185. $params['submissionid'] = $submissionid;
  1186. $params['workshopid'] = $this->id;
  1187. return $DB->get_records_sql($sql, $params);
  1188. }
  1189. /**
  1190. * Get the complete information about all assessments allocated to the given reviewer
  1191. *
  1192. * @param int $reviewerid
  1193. * @return array
  1194. */
  1195. public function get_assessments_by_reviewer($reviewerid) {
  1196. global $DB;
  1197. $userfieldsapi = \core_user\fields::for_userpic();
  1198. $reviewerfields = $userfieldsapi->get_sql('reviewer', false, 'reviewer', 'revieweridx', false)->selects;
  1199. $authorfields = $userfieldsapi->get_sql('author', false, 'author', 'authorid', false)->selects;
  1200. $overbyfields = $userfieldsapi->get_sql('overby', false, 'overby', 'gradinggradeoverbyx', false)->selects;
  1201. $sql = "SELECT a.*, $reviewerfields, $authorfields, $overbyfields,
  1202. s.id AS submissionid, s.title AS submissiontitle, s.timecreated AS submissioncreated,
  1203. s.timemodified AS submissionmodified
  1204. FROM {workshop_assessments} a
  1205. INNER JOIN {user} reviewer ON (a.reviewerid = reviewer.id)
  1206. INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
  1207. INNER JOIN {user} author ON (s.authorid = author.id)
  1208. LEFT JOIN {user} overby ON (a.gradinggradeoverby = overby.id)
  1209. WHERE s.example = 0 AND reviewer.id = :reviewerid AND s.workshopid = :workshopid";
  1210. $params = array('reviewerid' => $reviewerid, 'workshopid' => $this->id);
  1211. return $DB->get_records_sql($sql, $params);
  1212. }
  1213. /**
  1214. * Get allocated assessments not graded yet by the given reviewer
  1215. *
  1216. * @see self::get_assessments_by_reviewer()
  1217. * @param int $reviewerid the reviewer id
  1218. * @param null|int|array $exclude optional assessment id (or list of them) to be excluded
  1219. * @return array
  1220. */
  1221. public function get_pending_assessments_by_reviewer($reviewerid, $exclude = null) {
  1222. $assessments = $this->get_assessments_by_reviewer($reviewerid);
  1223. foreach ($assessments as $id => $assessment) {
  1224. if (!is_null($assessment->grade)) {
  1225. unset($assessments[$id]);
  1226. continue;
  1227. }
  1228. if (!empty($exclude)) {
  1229. if (is_array($exclude) and in_array($id, $exclude)) {
  1230. unset($assessments[$id]);
  1231. continue;
  1232. } else if ($id == $exclude) {
  1233. unset($assessments[$id]);
  1234. continue;
  1235. }
  1236. }
  1237. }
  1238. return $assessments;
  1239. }
  1240. /**
  1241. * Allocate a submission to a user for review
  1242. *
  1243. * @param stdClass $submission Submission object with at least id property
  1244. * @param int $reviewerid User ID
  1245. * @param int $weight of the new assessment, from 0 to 16
  1246. * @param bool $bulk repeated inserts into DB expected
  1247. * @return int ID of the new assessment or an error code {@link self::ALLOCATION_EXISTS} if the allocation already exists
  1248. */
  1249. public function add_allocation(stdclass $submission, $reviewerid, $weight=1, $bulk=false) {
  1250. global $DB;
  1251. if ($DB->record_exists('workshop_assessments', array('submissionid' => $submission->id, 'reviewerid' => $reviewerid))) {
  1252. return self::ALLOCATION_EXISTS;
  1253. }
  1254. $weight = (int)$weight;
  1255. if ($weight < 0) {
  1256. $weight = 0;
  1257. }
  1258. if ($weight > 16) {
  1259. $weight = 16;
  1260. }
  1261. $now = time();
  1262. $assessment = new stdclass();
  1263. $assessment->submissionid = $submission->id;
  1264. $assessment->reviewerid = $reviewerid;
  1265. $assessment->timecreated = $now; // do not set timemodified here
  1266. $assessment->weight = $weight;
  1267. $assessment->feedbackauthorformat = editors_get_preferred_format();
  1268. $assessment->feedbackreviewerformat = editors_get_preferred_format();
  1269. return $DB->insert_record('workshop_assessments', $assessment, true, $bulk);
  1270. }
  1271. /**
  1272. * Delete assessment record or records.
  1273. *
  1274. * Removes associated records from the workshop_grades table, too.
  1275. *
  1276. * @param int|array $id assessment id or array of assessments ids
  1277. * @todo Give grading strategy plugins a chance to clean up their data, too.
  1278. * @return bool true
  1279. */
  1280. public function delete_assessment($id) {
  1281. global $DB;
  1282. if (empty($id)) {
  1283. return true;
  1284. }
  1285. $fs = get_file_storage();
  1286. if (is_array($id)) {
  1287. $DB->delete_records_list('workshop_grades', 'assessmentid', $id);
  1288. foreach ($id as $itemid) {
  1289. $fs->delete_area_files($this->context->id, 'mod_workshop', 'overallfeedback_content', $itemid);
  1290. $fs->delete_area_files($this->context->id, 'mod_workshop', 'overallfeedback_attachment', $itemid);
  1291. }
  1292. $DB->delete_records_list('workshop_assessments', 'id', $id);
  1293. } else {
  1294. $DB->delete_records('workshop_grades', array('assessmentid' => $id));
  1295. $fs->delete_area_files($this->context->id, 'mod_workshop', 'overallfeedback_content', $id);
  1296. $fs->delete_area_files($this->context->id, 'mod_workshop', 'overallfeedback_attachment', $id);
  1297. $DB->delete_records('workshop_assessments', array('id' => $id));
  1298. }
  1299. return true;
  1300. }
  1301. /**
  1302. * Returns instance of grading strategy class
  1303. *
  1304. * @return stdclass Instance of a grading strategy
  1305. */
  1306. public function grading_strategy_instance() {
  1307. global $CFG; // because we require other libs here
  1308. if (is_null($this->strategyinstance)) {
  1309. $strategylib = __DIR__ . '/form/' . $this->strategy . '/lib.php';
  1310. if (is_readable($strategylib)) {
  1311. require_once($strategylib);
  1312. } else {
  1313. throw new coding_exception('the grading forms subplugin must contain library ' . $strategylib);
  1314. }
  1315. $classname = 'workshop_' . $this->strategy . '_strategy';
  1316. $this->strategyinstance = new $classname($this);
  1317. if (!in_array('workshop_strategy', class_implements($this->strategyinstance))) {
  1318. throw new coding_exception($classname . ' does not implement workshop_strategy interface');
  1319. }
  1320. }
  1321. return $this->strategyinstance;
  1322. }
  1323. /**
  1324. * Sets the current evaluation method to the given plugin.
  1325. *
  1326. * @param string $method the name of the workshopeval subplugin
  1327. * @return bool true if successfully set
  1328. * @throws coding_exception if attempting to set a non-installed evaluation method
  1329. */
  1330. public function set_grading_evaluation_method($method) {
  1331. global $DB;
  1332. $evaluationlib = __DIR__ . '/eval/' . $method . '/lib.php';
  1333. if (is_readable($evaluationlib)) {
  1334. $this->evaluationinstance = null;
  1335. $this->evaluation = $method;
  1336. $DB->set_field('workshop', 'evaluation', $method, array('id' => $this->id));
  1337. return true;
  1338. }
  1339. throw new coding_exception('Attempt to set a non-existing evaluation method.');
  1340. }
  1341. /**
  1342. * Returns instance of grading evaluation class
  1343. *
  1344. * @return stdclass Instance of a grading evaluation
  1345. */
  1346. public function grading_evaluation_instance() {
  1347. global $CFG; // because we require other libs here
  1348. if (is_null($this->evaluationinstance)) {
  1349. if (empty($this->evaluation)) {
  1350. $this->evaluation = 'best';
  1351. }
  1352. $evaluationlib = __DIR__ . '/eval/' . $this->evaluation . '/lib.php';
  1353. if (is_readable($evaluationlib)) {
  1354. require_once($evaluationlib);
  1355. } else {
  1356. // Fall back in case the subplugin is not available.
  1357. $this->evaluation = 'best';
  1358. $evaluationlib = __DIR__ . '/eval/' . $this->evaluation . '/lib.php';
  1359. if (is_readable($evaluationlib)) {
  1360. require_once($evaluationlib);
  1361. } else {
  1362. // Fall back in case the subplugin is not available any more.
  1363. throw new coding_exception('Missing default grading evaluation library ' . $evaluationlib);
  1364. }
  1365. }
  1366. $classname = 'workshop_' . $this->evaluation . '_evaluation';
  1367. $this->evaluationinstance = new $classname($this);
  1368. if (!in_array('workshop_evaluation', class_parents($this->evaluationinstance))) {
  1369. throw new coding_exception($classname . ' does not extend workshop_evaluation class');
  1370. }
  1371. }
  1372. return $this->evaluationinstance;
  1373. }
  1374. /**
  1375. * Returns instance of submissions allocator
  1376. *
  1377. * @param string $method The name of the allocation method, must be PARAM_ALPHA
  1378. * @return stdclass Instance of submissions allocator
  1379. */
  1380. public function allocator_instance($method) {
  1381. global $CFG; // because we require other libs here
  1382. $allocationlib = __DIR__ . '/allocation/' . $method . '/lib.php';
  1383. if (is_readable($allocationlib)) {
  1384. require_once($allocationlib);
  1385. } else {
  1386. throw new coding_exception('Unable to find the allocation library ' . $allocationlib);
  1387. }
  1388. $classname = 'workshop_' . $method . '_allocator';
  1389. return new $classname($this);
  1390. }
  1391. /**
  1392. * @return moodle_url of this workshop's view page
  1393. */
  1394. public function view_url() {
  1395. global $CFG;
  1396. return new moodle_url('/mod/workshop/view.php', array('id' => $this->cm->id));
  1397. }
  1398. /**
  1399. * @return moodle_url of the page for editing this workshop's grading form
  1400. */
  1401. public function editform_url() {
  1402. global $CFG;
  1403. return new moodle_url('/mod/workshop/editform.php', array('cmid' => $this->cm->id));
  1404. }
  1405. /**
  1406. * @return moodle_url of the page for previewing this workshop's grading form
  1407. */
  1408. public function previewform_url() {
  1409. global $CFG;
  1410. return new moodle_url('/mod/workshop/editformpreview.php', array('cmid' => $this->cm->id));
  1411. }
  1412. /**
  1413. * @param int $assessmentid The ID of assessment record
  1414. * @return moodle_url of the assessment page
  1415. */
  1416. public function assess_url($assessmentid) {
  1417. global $CFG;
  1418. $assessmentid = clean_param($assessmentid, PARAM_INT);
  1419. return new moodle_url('/mod/workshop/assessment.php', array('asid' => $assessmentid));
  1420. }
  1421. /**
  1422. * @param int $assessmentid The ID of assessment record
  1423. * @return moodle_url of the example assessment page
  1424. */
  1425. public function exassess_url($assessmentid) {
  1426. global $CFG;
  1427. $assessmentid = clean_param($assessmentid, PARAM_INT);
  1428. return new moodle_url('/mod/workshop/exassessment.php', array('asid' => $assessmentid));
  1429. }
  1430. /**
  1431. * @return moodle_url of the page to view a submission, defaults to the own one
  1432. */
  1433. public function submission_url($id=null) {
  1434. global $CFG;
  1435. return new moodle_url('/mod/workshop/submission.php', array('cmid' => $this->cm->id, 'id' => $id));
  1436. }
  1437. /**
  1438. * @param int $id example submission id
  1439. * @return moodle_url of the page to view an example submission
  1440. */
  1441. public function exsubmission_url($id) {
  1442. global $CFG;
  1443. return new moodle_url('/mod/workshop/exsubmission.php', array('cmid' => $this->cm->id, 'id' => $id));
  1444. }
  1445. /**
  1446. * @param int $sid submission id
  1447. * @param array $aid of int assessment ids
  1448. * @return moodle_url of the page to compare assessments of the given submission
  1449. */
  1450. public function compare_url($sid, array $aids) {
  1451. global $CFG;
  1452. $url = new moodle_url('/mod/workshop/compare.php', array('cmid' => $this->cm->id, 'sid' => $sid));
  1453. $i = 0;
  1454. foreach ($aids as $aid) {
  1455. $url->param("aid{$i}", $aid);
  1456. $i++;
  1457. }
  1458. return $url;
  1459. }
  1460. /**
  1461. * @param int $sid submission id
  1462. * @param int $aid assessment id
  1463. * @return moodle_url of the page to compare the reference assessments of the given example submission
  1464. */
  1465. public function excompare_url($sid, $aid) {
  1466. global $CFG;
  1467. return new moodle_url('/mod/workshop/excompare.php', array('cmid' => $this->cm->id, 'sid' => $sid, 'aid' => $aid));
  1468. }
  1469. /**
  1470. * @return moodle_url of the mod_edit form
  1471. */
  1472. public function updatemod_url() {
  1473. global $CFG;
  1474. return new moodle_url('/course/modedit.php', array('update' => $this->cm->id, 'return' => 1));
  1475. }
  1476. /**
  1477. * @param string $method allocation method
  1478. * @return moodle_url to the allocation page
  1479. */
  1480. public function allocation_url($method=null) {
  1481. global $CFG;
  1482. $params = array('cmid' => $this->cm->id);
  1483. if (!empty($method)) {
  1484. $params['method'] = $method;
  1485. }
  1486. return new moodle_url('/mod/workshop/allocation.php', $params);
  1487. }
  1488. /**
  1489. * @param int $phasecode The internal phase code
  1490. * @return moodle_url of the script to change the current phase to $phasecode
  1491. */
  1492. public function switchphase_url($phasecode) {
  1493. global $CFG;
  1494. $phasecode = clean_param($phasecode, PARAM_INT);
  1495. return new moodle_url('/mod/workshop/switchphase.php', array('cmid' => $this->cm->id, 'phase' => $phasecode));
  1496. }
  1497. /**
  1498. * @return moodle_url to the aggregation page
  1499. */
  1500. public function aggregate_url() {
  1501. global $CFG;
  1502. return new moodle_url('/mod/workshop/aggregate.php', array('cmid' => $this->cm->id));
  1503. }
  1504. /**
  1505. * @return moodle_url of this workshop's toolbox page
  1506. */
  1507. public function toolbox_url($tool) {
  1508. global $CFG;
  1509. return new moodle_url('/mod/workshop/toolbox.php', array('id' => $this->cm->id, 'tool' => $tool));
  1510. }
  1511. /**
  1512. * Workshop wrapper around {@see add_to_log()}
  1513. * @deprecated since 2.7 Please use the provided event classes for logging actions.
  1514. *
  1515. * @param string $action to be logged
  1516. * @param moodle_url $url absolute url as returned by {@see workshop::submission_url()} and friends
  1517. * @param mixed $info additional info, usually id in a table
  1518. * @param bool $return true to return the arguments for add_to_log.
  1519. * @return void|array array of arguments for add_to_log if $return is true
  1520. */
  1521. public function log($action, moodle_url $url = null, $info = null, $return = false) {
  1522. debugging('The log method is now deprecated, please use event classes instead', DEBUG_DEVELOPER);
  1523. if (is_null($url)) {
  1524. $url = $this->view_url();
  1525. }
  1526. if (is_null($info)) {
  1527. $info = $this->id;
  1528. }
  1529. $logurl = $this->log_convert_url($url);
  1530. $args = array($this->course->id, 'workshop', $action, $logurl, $info, $this->cm->id);
  1531. if ($return) {
  1532. return $args;
  1533. }
  1534. call_user_func_array('add_to_log', $args);
  1535. }
  1536. /**
  1537. * Is the given user allowed to create their submission?
  1538. *
  1539. * @param int $userid
  1540. * @return bool
  1541. */
  1542. public function creating_submission_allowed($userid) {
  1543. $now = time();
  1544. $ignoredeadlines = has_capability('mod/workshop:ignoredeadlines', $this->context, $userid);
  1545. if ($this->latesubmissions) {
  1546. if ($this->phase != self::PHASE_SUBMISSION and $this->phase != self::PHASE_ASSESSMENT) {
  1547. // late submissions are allowed in the submission and assessment phase only
  1548. return false;
  1549. }
  1550. if (!$ignoredeadlines and !empty($this->submissionstart) and $this->submissionstart > $now) {
  1551. // late submissions are not allowed before the submission start
  1552. return false;
  1553. }
  1554. return true;
  1555. } else {
  1556. if ($this->phase != self::PHASE_SUBMISSION) {
  1557. // submissions are allowed during the submission phase only
  1558. return false;
  1559. }
  1560. if (!$ignoredeadlines and !empty($this->submissionstart) and $this->submissionstart > $now) {
  1561. // if enabled, submitting is not allowed before the date/time defined in the mod_form
  1562. return false;
  1563. }
  1564. if (!$ignoredeadlines and !empty($this->submissionend) and $now > $this->submissionend ) {
  1565. // if enabled, submitting is not allowed after the date/time defined in the mod_form unless late submission is allowed
  1566. return false;
  1567. }
  1568. return true;
  1569. }
  1570. }
  1571. /**
  1572. * Is the given user allowed to modify their existing submission?
  1573. *
  1574. * @param int $userid
  1575. * @return bool
  1576. */
  1577. public function modifying_submission_allowed($userid) {
  1578. $now = time();
  1579. $ignoredeadlines = has_capability('mod/workshop:ignoredeadlines', $this->context, $userid);
  1580. if ($this->phase != self::PHASE_SUBMISSION) {
  1581. // submissions can be edited during the submission phase only
  1582. return false;
  1583. }
  1584. if (!$ignoredeadlines and !empty($this->submissionstart) and $this->submissionstart > $now) {
  1585. // if enabled, re-submitting is not allowed before the date/time defined in the mod_form
  1586. return false;
  1587. }
  1588. if (!$ignoredeadlines and !empty($this->submissionend) and $now > $this->submissionend) {
  1589. // if enabled, re-submitting is not allowed after the date/time defined in the mod_form even if late submission is allowed
  1590. return false;
  1591. }
  1592. return true;
  1593. }
  1594. /**
  1595. * Is the given reviewer allowed to create/edit their assessments?
  1596. *
  1597. * @param int $userid
  1598. * @return bool
  1599. */
  1600. public function assessing_allowed($userid) {
  1601. if ($this->phase != self::PHASE_ASSESSMENT) {
  1602. // assessing is allowed in the assessment phase only, unless the user is a teacher
  1603. // providing additional assessment during the evaluation phase
  1604. if ($this->phase != self::PHASE_EVALUATION or !has_capability('mod/workshop:overridegrades', $this->context, $userid)) {
  1605. return false;
  1606. }
  1607. }
  1608. $now = time();
  1609. $ignoredeadlines = has_capability('mod/workshop:ignoredeadlines', $this->context, $userid);
  1610. if (!$ignoredeadlines and !empty($this->assessmentstart) and $this->assessmentstart > $now) {
  1611. // if enabled, assessing is not allowed before the date/time defined in the mod_form
  1612. return false;
  1613. }
  1614. if (!$ignoredeadlines and !empty($this->assessmentend) and $now > $this->assessmentend) {
  1615. // if enabled, assessing is not allowed after the date/time defined in the mod_form
  1616. return false;
  1617. }
  1618. // here we go, assessing is allowed
  1619. return true;
  1620. }
  1621. /**
  1622. * Are reviewers allowed to create/edit their assessments of the example submissions?
  1623. *
  1624. * Returns null if example submissions are not enabled in this workshop. Otherwise returns
  1625. * true or false. Note this does not check other conditions like the number of already
  1626. * assessed examples, examples mode etc.
  1627. *
  1628. * @return null|bool
  1629. */
  1630. public function assessing_examples_allowed() {
  1631. if (empty($this->useexamples)) {
  1632. return null;
  1633. }
  1634. if (self::EXAMPLES_VOLUNTARY == $this->examplesmode) {
  1635. return true;
  1636. }
  1637. if (self::EXAMPLES_BEFORE_SUBMISSION == $this->examplesmode and self::PHASE_SUBMISSION == $this->phase) {
  1638. return true;
  1639. }
  1640. if (self::EXAMPLES_BEFORE_ASSESSMENT == $this->examplesmode and self::PHASE_ASSESSMENT == $this->phase) {
  1641. return true;
  1642. }
  1643. return false;
  1644. }
  1645. /**
  1646. * Are the peer-reviews available to the authors?
  1647. *
  1648. * @return bool
  1649. */
  1650. public function assessments_available() {
  1651. return $this->phase == self::PHASE_CLOSED;
  1652. }
  1653. /**
  1654. * Switch to a new workshop phase
  1655. *
  1656. * Modifies the underlying database record. You should terminate the script shortly after calling this.
  1657. *
  1658. * @param int $newphase new phase code
  1659. * @return bool true if success, false otherwise
  1660. */
  1661. public function switch_phase($newphase) {
  1662. global $DB;
  1663. $known = $this->available_phases_list();
  1664. if (!isset($known[$newphase])) {
  1665. return false;
  1666. }
  1667. if (self::PHASE_CLOSED == $newphase) {
  1668. // push the grades into the gradebook
  1669. $workshop = new stdclass();
  1670. foreach ($this as $property => $value) {
  1671. $workshop->{$property} = $value;
  1672. }
  1673. $workshop->course = $this->course->id;
  1674. $workshop->cmidnumber = $this->cm->id;
  1675. $workshop->modname = 'workshop';
  1676. workshop_update_grades($workshop);
  1677. }
  1678. $DB->set_field('workshop', 'phase', $newphase, array('id' => $this->id));
  1679. $this->phase = $newphase;
  1680. $eventdata = array(
  1681. 'objectid' => $this->id,
  1682. 'context' => $this->context,
  1683. 'other' => array(
  1684. 'workshopphase' => $this->phase
  1685. )
  1686. );
  1687. $event = \mod_workshop\event\phase_switched::create($eventdata);
  1688. $event->trigger();
  1689. return true;
  1690. }
  1691. /**
  1692. * Saves a raw grade for submission as calculated from the assessment form fields
  1693. *
  1694. * @param array $assessmentid assessment record id, must exists
  1695. * @param mixed $grade raw percentual grade from 0.00000 to 100.00000
  1696. * @return false|float the saved grade
  1697. */
  1698. public function set_peer_grade($assessmentid, $grade) {
  1699. global $DB;
  1700. if (is_null($grade)) {
  1701. return false;
  1702. }
  1703. $data = new stdclass();
  1704. $data->id = $assessmentid;
  1705. $data->grade = $grade;
  1706. $data->timemodified = time();
  1707. $DB->update_record('workshop_assessments', $data);
  1708. return $grade;
  1709. }
  1710. /**
  1711. * Prepares data object with all workshop grades to be rendered
  1712. *
  1713. * @param int $userid the user we are preparing the report for
  1714. * @param int $groupid if non-zero, prepare the report for the given group only
  1715. * @param int $page the current page (for the pagination)
  1716. * @param int $perpage participants per page (for the pagination)
  1717. * @param string $sortby lastname|firstname|submissiontitle|submissiongrade|gradinggrade
  1718. * @param string $sorthow ASC|DESC
  1719. * @return stdclass data for the renderer
  1720. */
  1721. public function prepare_grading_report_data($userid, $groupid, $page, $perpage, $sortby, $sorthow) {
  1722. global $DB;
  1723. $canviewall = has_capability('mod/workshop:viewallassessments', $this->context, $userid);
  1724. $isparticipant = $this->is_participant($userid);
  1725. if (!$canviewall and !$isparticipant) {
  1726. // who the hell is this?
  1727. return array();
  1728. }
  1729. if (!in_array($sortby, array('lastname', 'firstname', 'submissiontitle', 'submissionmodified',
  1730. 'submissiongrade', 'gradinggrade'))) {
  1731. $sortby = 'lastname';
  1732. }
  1733. if (!($sorthow === 'ASC' or $sorthow === 'DESC')) {
  1734. $sorthow = 'ASC';
  1735. }
  1736. // get the list of user ids to be displayed
  1737. if ($canviewall) {
  1738. $participants = $this->get_participants(false, $groupid);
  1739. } else {
  1740. // this is an ordinary workshop participant (aka student) - display the report just for him/her
  1741. $participants = array($userid => (object)array('id' => $userid));
  1742. }
  1743. // we will need to know the number of all records later for the pagination purposes
  1744. $numofparticipants = count($participants);
  1745. if ($numofparticipants > 0) {
  1746. // load all fields which can be used for sorting and paginate the records
  1747. list($participantids, $params) = $DB->get_in_or_equal(array_keys($participants), SQL_PARAMS_NAMED);
  1748. $params['workshopid1'] = $this->id;
  1749. $params['workshopid2'] = $this->id;
  1750. $sqlsort = array();
  1751. $sqlsortfields = array($sortby => $sorthow) + array('lastname' => 'ASC', 'firstname' => 'ASC', 'u.id' => 'ASC');
  1752. foreach ($sqlsortfields as $sqlsortfieldname => $sqlsortfieldhow) {
  1753. $sqlsort[] = $sqlsortfieldname . ' ' . $sqlsortfieldhow;
  1754. }
  1755. $sqlsort = implode(',', $sqlsort);
  1756. $userfieldsapi = \core_user\fields::for_userpic();
  1757. $picturefields = $userfieldsapi->get_sql('u', false, '', 'userid', false)->selects;
  1758. $sql = "SELECT $picturefields, s.title AS submissiontitle, s.timemodified AS submissionmodified,
  1759. s.grade AS submissiongrade, ag.gradinggrade
  1760. FROM {user} u
  1761. LEFT JOIN {workshop_submissions} s ON (s.authorid = u.id AND s.workshopid = :workshopid1 AND s.example = 0)
  1762. LEFT JOIN {workshop_aggregations} ag ON (ag.userid = u.id AND ag.workshopid = :workshopid2)
  1763. WHERE u.id $participantids
  1764. ORDER BY $sqlsort";
  1765. $participants = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
  1766. } else {
  1767. $participants = array();
  1768. }
  1769. // this will hold the information needed to display user names and pictures
  1770. $userinfo = array();
  1771. // get the user details for all participants to display
  1772. $additionalnames = \core_user\fields::get_name_fields();
  1773. foreach ($participants as $participant) {
  1774. if (!isset($userinfo[$participant->userid])) {
  1775. $userinfo[$participant->userid] = new stdclass();
  1776. $userinfo[$participant->userid]->id = $participant->userid;
  1777. $userinfo[$participant->userid]->picture = $participant->picture;
  1778. $userinfo[$participant->userid]->imagealt = $participant->imagealt;
  1779. $userinfo[$participant->userid]->email = $participant->email;
  1780. foreach ($additionalnames as $addname) {
  1781. $userinfo[$participant->userid]->$addname = $participant->$addname;
  1782. }
  1783. }
  1784. }
  1785. // load the submissions details
  1786. $submissions = $this->get_submissions(array_keys($participants));
  1787. // get the user details for all moderators (teachers) that have overridden a submission grade
  1788. foreach ($submissions as $submission) {
  1789. if (!isset($userinfo[$submission->gradeoverby])) {
  1790. $userinfo[$submission->gradeoverby] = new stdclass();
  1791. $userinfo[$submission->gradeoverby]->id = $submission->gradeoverby;
  1792. $userinfo[$submission->gradeoverby]->picture = $submission->overpicture;
  1793. $userinfo[$submission->gradeoverby]->imagealt = $submission->overimagealt;
  1794. $userinfo[$submission->gradeoverby]->email = $submission->overemail;
  1795. foreach ($additionalnames as $addname) {
  1796. $temp = 'over' . $addname;
  1797. $userinfo[$submission->gradeoverby]->$addname = $submission->$temp;
  1798. }
  1799. }
  1800. }
  1801. // get the user details for all reviewers of the displayed participants
  1802. $reviewers = array();
  1803. if ($submissions) {
  1804. list($submissionids, $params) = $DB->get_in_or_equal(array_keys($submissions), SQL_PARAMS_NAMED);
  1805. list($sort, $sortparams) = users_order_by_sql('r');
  1806. $userfieldsapi = \core_user\fields::for_userpic();
  1807. $picturefields = $userfieldsapi->get_sql('r', false, '', 'reviewerid', false)->selects;
  1808. $sql = "SELECT a.id AS assessmentid, a.submissionid, a.grade, a.gradinggrade, a.gradinggradeover, a.weight,
  1809. $picturefields, s.id AS submissionid, s.authorid
  1810. FROM {workshop_assessments} a
  1811. JOIN {user} r ON (a.reviewerid = r.id)
  1812. JOIN {workshop_submissions} s ON (a.submissionid = s.id AND s.example = 0)
  1813. WHERE a.submissionid $submissionids
  1814. ORDER BY a.weight DESC, $sort";
  1815. $reviewers = $DB->get_records_sql($sql, array_merge($params, $sortparams));
  1816. foreach ($reviewers as $reviewer) {
  1817. if (!isset($userinfo[$reviewer->reviewerid])) {
  1818. $userinfo[$reviewer->reviewerid] = new stdclass();
  1819. $userinfo[$reviewer->reviewerid]->id = $reviewer->reviewerid;
  1820. $userinfo[$reviewer->reviewerid]->picture = $reviewer->picture;
  1821. $userinfo[$reviewer->reviewerid]->imagealt = $reviewer->imagealt;
  1822. $userinfo[$reviewer->reviewerid]->email = $reviewer->email;
  1823. foreach ($additionalnames as $addname) {
  1824. $userinfo[$reviewer->reviewerid]->$addname = $reviewer->$addname;
  1825. }
  1826. }
  1827. }
  1828. }
  1829. // get the user details for all reviewees of the displayed participants
  1830. $reviewees = array();
  1831. if ($participants) {
  1832. list($participantids, $params) = $DB->get_in_or_equal(array_keys($participants), SQL_PARAMS_NAMED);
  1833. list($sort, $sortparams) = users_order_by_sql('e');
  1834. $params['workshopid'] = $this->id;
  1835. $userfieldsapi = \core_user\fields::for_userpic();
  1836. $picturefields = $userfieldsapi->get_sql('e', false, '', 'authorid', false)->selects;
  1837. $sql = "SELECT a.id AS assessmentid, a.submissionid, a.grade, a.gradinggrade, a.gradinggradeover, a.reviewerid, a.weight,
  1838. s.id AS submissionid, $picturefields
  1839. FROM {user} u
  1840. JOIN {workshop_assessments} a ON (a.reviewerid = u.id)
  1841. JOIN {workshop_submissions} s ON (a.submissionid = s.id AND s.example = 0)
  1842. JOIN {user} e ON (s.authorid = e.id)
  1843. WHERE u.id $participantids AND s.workshopid = :workshopid
  1844. ORDER BY a.weight DESC, $sort";
  1845. $reviewees = $DB->get_records_sql($sql, array_merge($params, $sortparams));
  1846. foreach ($reviewees as $reviewee) {
  1847. if (!isset($userinfo[$reviewee->authorid])) {
  1848. $userinfo[$reviewee->authorid] = new stdclass();
  1849. $userinfo[$reviewee->authorid]->id = $reviewee->authorid;
  1850. $userinfo[$reviewee->authorid]->picture = $reviewee->picture;
  1851. $userinfo[$reviewee->authorid]->imagealt = $reviewee->imagealt;
  1852. $userinfo[$reviewee->authorid]->email = $reviewee->email;
  1853. foreach ($additionalnames as $addname) {
  1854. $userinfo[$reviewee->authorid]->$addname = $reviewee->$addname;
  1855. }
  1856. }
  1857. }
  1858. }
  1859. // finally populate the object to be rendered
  1860. $grades = $participants;
  1861. foreach ($participants as $participant) {
  1862. // set up default (null) values
  1863. $grades[$participant->userid]->submissionid = null;
  1864. $grades[$participant->userid]->submissiontitle = null;
  1865. $grades[$participant->userid]->submissiongrade = null;
  1866. $grades[$participant->userid]->submissiongradeover = null;
  1867. $grades[$participant->userid]->submissiongradeoverby = null;
  1868. $grades[$participant->userid]->submissionpublished = null;
  1869. $grades[$participant->userid]->reviewedby = array();
  1870. $grades[$participant->userid]->reviewerof = array();
  1871. }
  1872. unset($participants);
  1873. unset($participant);
  1874. foreach ($submissions as $submission) {
  1875. $grades[$submission->authorid]->submissionid = $submission->id;
  1876. $grades[$submission->authorid]->submissiontitle = $submission->title;
  1877. $grades[$submission->authorid]->submissiongrade = $this->real_grade($submission->grade);
  1878. $grades[$submission->authorid]->submissiongradeover = $this->real_grade($submission->gradeover);
  1879. $grades[$submission->authorid]->submissiongradeoverby = $submission->gradeoverby;
  1880. $grades[$submission->authorid]->submissionpublished = $submission->published;
  1881. }
  1882. unset($submissions);
  1883. unset($submission);
  1884. foreach($reviewers as $reviewer) {
  1885. $info = new stdclass();
  1886. $info->userid = $reviewer->reviewerid;
  1887. $info->assessmentid = $reviewer->assessmentid;
  1888. $info->submissionid = $reviewer->submissionid;
  1889. $info->grade = $this->real_grade($reviewer->grade);
  1890. $info->gradinggrade = $this->real_grading_grade($reviewer->gradinggrade);
  1891. $info->gradinggradeover = $this->real_grading_grade($reviewer->gradinggradeover);
  1892. $info->weight = $reviewer->weight;
  1893. $grades[$reviewer->authorid]->reviewedby[$reviewer->reviewerid] = $info;
  1894. }
  1895. unset($reviewers);
  1896. unset($reviewer);
  1897. foreach($reviewees as $reviewee) {
  1898. $info = new stdclass();
  1899. $info->userid = $reviewee->authorid;
  1900. $info->assessmentid = $reviewee->assessmentid;
  1901. $info->submissionid = $reviewee->submissionid;
  1902. $info->grade = $this->real_grade($reviewee->grade);
  1903. $info->gradinggrade = $this->real_grading_grade($reviewee->gradinggrade);
  1904. $info->gradinggradeover = $this->real_grading_grade($reviewee->gradinggradeover);
  1905. $info->weight = $reviewee->weight;
  1906. $grades[$reviewee->reviewerid]->reviewerof[$reviewee->authorid] = $info;
  1907. }
  1908. unset($reviewees);
  1909. unset($reviewee);
  1910. foreach ($grades as $grade) {
  1911. $grade->gradinggrade = $this->real_grading_grade($grade->gradinggrade);
  1912. }
  1913. $data = new stdclass();
  1914. $data->grades = $grades;
  1915. $data->userinfo = $userinfo;
  1916. $data->totalcount = $numofparticipants;
  1917. $data->maxgrade = $this->real_grade(100);
  1918. $data->maxgradinggrade = $this->real_grading_grade(100);
  1919. return $data;
  1920. }
  1921. /**
  1922. * Calculates the real value of a grade
  1923. *
  1924. * @param float $value percentual value from 0 to 100
  1925. * @param float $max the maximal grade
  1926. * @return string
  1927. */
  1928. public function real_grade_value($value, $max) {
  1929. $localized = true;
  1930. if (is_null($value) or $value === '') {
  1931. return null;
  1932. } elseif ($max == 0) {
  1933. return 0;
  1934. } else {
  1935. return format_float($max * $value / 100, $this->gradedecimals, $localized);
  1936. }
  1937. }
  1938. /**
  1939. * Calculates the raw (percentual) value from a real grade
  1940. *
  1941. * This is used in cases when a user wants to give a grade such as 12 of 20 and we need to save
  1942. * this value in a raw percentual form into DB
  1943. * @param float $value given grade
  1944. * @param float $max the maximal grade
  1945. * @return float suitable to be stored as numeric(10,5)
  1946. */
  1947. public function raw_grade_value($value, $max) {
  1948. if (is_null($value) or $value === '') {
  1949. return null;
  1950. }
  1951. if ($max == 0 or $value < 0) {
  1952. return 0;
  1953. }
  1954. $p = $value / $max * 100;
  1955. if ($p > 100) {
  1956. return $max;
  1957. }
  1958. return grade_floatval($p);
  1959. }
  1960. /**
  1961. * Calculates the real value of grade for submission
  1962. *
  1963. * @param float $value percentual value from 0 to 100
  1964. * @return string
  1965. */
  1966. public function real_grade($value) {
  1967. return $this->real_grade_value($value, $this->grade);
  1968. }
  1969. /**
  1970. * Calculates the real value of grade for assessment
  1971. *
  1972. * @param float $value percentual value from 0 to 100
  1973. * @return string
  1974. */
  1975. public function real_grading_grade($value) {
  1976. return $this->real_grade_value($value, $this->gradinggrade);
  1977. }
  1978. /**
  1979. * Sets the given grades and received grading grades to null
  1980. *
  1981. * This does not clear the information about how the peers filled the assessment forms, but
  1982. * clears the calculated grades in workshop_assessments. Therefore reviewers have to re-assess
  1983. * the allocated submissions.
  1984. *
  1985. * @return void
  1986. */
  1987. public function clear_assessments() {
  1988. global $DB;
  1989. $submissions = $this->get_submissions();
  1990. if (empty($submissions)) {
  1991. // no money, no love
  1992. return;
  1993. }
  1994. $submissions = array_keys($submissions);
  1995. list($sql, $params) = $DB->get_in_or_equal($submissions, SQL_PARAMS_NAMED);
  1996. $sql = "submissionid $sql";
  1997. $DB->set_field_select('workshop_assessments', 'grade', null, $sql, $params);
  1998. $DB->set_field_select('workshop_assessments', 'gradinggrade', null, $sql, $params);
  1999. }
  2000. /**
  2001. * Sets the grades for submission to null
  2002. *
  2003. * @param null|int|array $restrict If null, update all authors, otherwise update just grades for the given author(s)
  2004. * @return void
  2005. */
  2006. public function clear_submission_grades($restrict=null) {
  2007. global $DB;
  2008. $sql = "workshopid = :workshopid AND example = 0";
  2009. $params = array('workshopid' => $this->id);
  2010. if (is_null($restrict)) {
  2011. // update all users - no more conditions
  2012. } elseif (!empty($restrict)) {
  2013. list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
  2014. $sql .= " AND authorid $usql";
  2015. $params = array_merge($params, $uparams);
  2016. } else {
  2017. throw new coding_exception('Empty value is not a valid parameter here');
  2018. }
  2019. $DB->set_field_select('workshop_submissions', 'grade', null, $sql, $params);
  2020. }
  2021. /**
  2022. * Calculates grades for submission for the given participant(s) and updates it in the database
  2023. *
  2024. * @param null|int|array $restrict If null, update all authors, otherwise update just grades for the given author(s)
  2025. * @return void
  2026. */
  2027. public function aggregate_submission_grades($restrict=null) {
  2028. global $DB;
  2029. // fetch a recordset with all assessments to process
  2030. $sql = 'SELECT s.id AS submissionid, s.grade AS submissiongrade,
  2031. a.weight, a.grade
  2032. FROM {workshop_submissions} s
  2033. LEFT JOIN {workshop_assessments} a ON (a.submissionid = s.id)
  2034. WHERE s.example=0 AND s.workshopid=:workshopid'; // to be cont.
  2035. $params = array('workshopid' => $this->id);
  2036. if (is_null($restrict)) {
  2037. // update all users - no more conditions
  2038. } elseif (!empty($restrict)) {
  2039. list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
  2040. $sql .= " AND s.authorid $usql";
  2041. $params = array_merge($params, $uparams);
  2042. } else {
  2043. throw new coding_exception('Empty value is not a valid parameter here');
  2044. }
  2045. $sql .= ' ORDER BY s.id'; // this is important for bulk processing
  2046. $rs = $DB->get_recordset_sql($sql, $params);
  2047. $batch = array(); // will contain a set of all assessments of a single submission
  2048. $previous = null; // a previous record in the recordset
  2049. foreach ($rs as $current) {
  2050. if (is_null($previous)) {
  2051. // we are processing the very first record in the recordset
  2052. $previous = $current;
  2053. }
  2054. if ($current->submissionid == $previous->submissionid) {
  2055. // we are still processing the current submission
  2056. $batch[] = $current;
  2057. } else {
  2058. // process all the assessments of a sigle submission
  2059. $this->aggregate_submission_grades_process($batch);
  2060. // and then start to process another submission
  2061. $batch = array($current);
  2062. $previous = $current;
  2063. }
  2064. }
  2065. // do not forget to process the last batch!
  2066. $this->aggregate_submission_grades_process($batch);
  2067. $rs->close();
  2068. }
  2069. /**
  2070. * Sets the aggregated grades for assessment to null
  2071. *
  2072. * @param null|int|array $restrict If null, update all reviewers, otherwise update just grades for the given reviewer(s)
  2073. * @return void
  2074. */
  2075. public function clear_grading_grades($restrict=null) {
  2076. global $DB;
  2077. $sql = "workshopid = :workshopid";
  2078. $params = array('workshopid' => $this->id);
  2079. if (is_null($restrict)) {
  2080. // update all users - no more conditions
  2081. } elseif (!empty($restrict)) {
  2082. list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
  2083. $sql .= " AND userid $usql";
  2084. $params = array_merge($params, $uparams);
  2085. } else {
  2086. throw new coding_exception('Empty value is not a valid parameter here');
  2087. }
  2088. $DB->set_field_select('workshop_aggregations', 'gradinggrade', null, $sql, $params);
  2089. }
  2090. /**
  2091. * Calculates grades for assessment for the given participant(s)
  2092. *
  2093. * Grade for assessment is calculated as a simple mean of all grading grades calculated by the grading evaluator.
  2094. * The assessment weight is not taken into account here.
  2095. *
  2096. * @param null|int|array $restrict If null, update all reviewers, otherwise update just grades for the given reviewer(s)
  2097. * @return void
  2098. */
  2099. public function aggregate_grading_grades($restrict=null) {
  2100. global $DB;
  2101. // fetch a recordset with all assessments to process
  2102. $sql = 'SELECT a.reviewerid, a.gradinggrade, a.gradinggradeover,
  2103. ag.id AS aggregationid, ag.gradinggrade AS aggregatedgrade
  2104. FROM {workshop_assessments} a
  2105. INNER JOIN {workshop_submissions} s ON (a.submissionid = s.id)
  2106. LEFT JOIN {workshop_aggregations} ag ON (ag.userid = a.reviewerid AND ag.workshopid = s.workshopid)
  2107. WHERE s.example=0 AND s.workshopid=:workshopid'; // to be cont.
  2108. $params = array('workshopid' => $this->id);
  2109. if (is_null($restrict)) {
  2110. // update all users - no more conditions
  2111. } elseif (!empty($restrict)) {
  2112. list($usql, $uparams) = $DB->get_in_or_equal($restrict, SQL_PARAMS_NAMED);
  2113. $sql .= " AND a.reviewerid $usql";
  2114. $params = array_merge($params, $uparams);
  2115. } else {
  2116. throw new coding_exception('Empty value is not a valid parameter here');
  2117. }
  2118. $sql .= ' ORDER BY a.reviewerid'; // this is important for bulk processing
  2119. $rs = $DB->get_recordset_sql($sql, $params);
  2120. $batch = array(); // will contain a set of all assessments of a single submission
  2121. $previous = null; // a previous record in the recordset
  2122. foreach ($rs as $current) {
  2123. if (is_null($previous)) {
  2124. // we are processing the very first record in the recordset
  2125. $previous = $current;
  2126. }
  2127. if ($current->reviewerid == $previous->reviewerid) {
  2128. // we are still processing the current reviewer
  2129. $batch[] = $current;
  2130. } else {
  2131. // process all the assessments of a sigle submission
  2132. $this->aggregate_grading_grades_process($batch);
  2133. // and then start to process another reviewer
  2134. $batch = array($current);
  2135. $previous = $current;
  2136. }
  2137. }
  2138. // do not forget to process the last batch!
  2139. $this->aggregate_grading_grades_process($batch);
  2140. $rs->close();
  2141. }
  2142. /**
  2143. * Returns the mform the teachers use to put a feedback for the reviewer
  2144. *
  2145. * @param mixed moodle_url|null $actionurl
  2146. * @param stdClass $assessment
  2147. * @param array $options editable, editableweight, overridablegradinggrade
  2148. * @return workshop_feedbackreviewer_form
  2149. */
  2150. public function get_feedbackreviewer_form($actionurl, stdclass $assessment, $options=array()) {
  2151. global $CFG;
  2152. require_once(__DIR__ . '/feedbackreviewer_form.php');
  2153. $current = new stdclass();
  2154. $current->asid = $assessment->id;
  2155. $current->weight = $assessment->weight;
  2156. $current->gradinggrade = $this->real_grading_grade($assessment->gradinggrade);
  2157. $current->gradinggradeover = $this->real_grading_grade($assessment->gradinggradeover);
  2158. $current->feedbackreviewer = $assessment->feedbackreviewer;
  2159. $current->feedbackreviewerformat = $assessment->feedbackreviewerformat;
  2160. if (is_null($current->gradinggrade)) {
  2161. $current->gradinggrade = get_string('nullgrade', 'workshop');
  2162. }
  2163. if (!isset($options['editable'])) {
  2164. $editable = true; // by default
  2165. } else {
  2166. $editable = (bool)$options['editable'];
  2167. }
  2168. // prepare wysiwyg editor
  2169. $current = file_prepare_standard_editor($current, 'feedbackreviewer', array());
  2170. return new workshop_feedbackreviewer_form($actionurl,
  2171. array('workshop' => $this, 'current' => $current, 'editoropts' => array(), 'options' => $options),
  2172. 'post', '', null, $editable);
  2173. }
  2174. /**
  2175. * Returns the mform the teachers use to put a feedback for the author on their submission
  2176. *
  2177. * @mixed moodle_url|null $actionurl
  2178. * @param stdClass $submission
  2179. * @param array $options editable
  2180. * @return workshop_feedbackauthor_form
  2181. */
  2182. public function get_feedbackauthor_form($actionurl, stdclass $submission, $options=array()) {
  2183. global $CFG;
  2184. require_once(__DIR__ . '/feedbackauthor_form.php');
  2185. $current = new stdclass();
  2186. $current->submissionid = $submission->id;
  2187. $current->published = $submission->published;
  2188. $current->grade = $this->real_grade($submission->grade);
  2189. $current->gradeover = $this->real_grade($submission->gradeover);
  2190. $current->feedbackauthor = $submission->feedbackauthor;
  2191. $current->feedbackauthorformat = $submission->feedbackauthorformat;
  2192. if (is_null($current->grade)) {
  2193. $current->grade = get_string('nullgrade', 'workshop');
  2194. }
  2195. if (!isset($options['editable'])) {
  2196. $editable = true; // by default
  2197. } else {
  2198. $editable = (bool)$options['editable'];
  2199. }
  2200. // prepare wysiwyg editor
  2201. $current = file_prepare_standard_editor($current, 'feedbackauthor', array());
  2202. return new workshop_feedbackauthor_form($actionurl,
  2203. array('workshop' => $this, 'current' => $current, 'editoropts' => array(), 'options' => $options),
  2204. 'post', '', null, $editable);
  2205. }
  2206. /**
  2207. * Returns the information about the user's grades as they are stored in the gradebook
  2208. *
  2209. * The submission grade is returned for users with the capability mod/workshop:submit and the
  2210. * assessment grade is returned for users with the capability mod/workshop:peerassess. Unless the
  2211. * user has the capability to view hidden grades, grades must be visible to be returned. Null
  2212. * grades are not returned. If none grade is to be returned, this method returns false.
  2213. *
  2214. * @param int $userid the user's id
  2215. * @return workshop_final_grades|false
  2216. */
  2217. public function get_gradebook_grades($userid) {
  2218. global $CFG;
  2219. require_once($CFG->libdir.'/gradelib.php');
  2220. if (empty($userid)) {
  2221. throw new coding_exception('User id expected, empty value given.');
  2222. }
  2223. // Read data via the Gradebook API
  2224. $gradebook = grade_get_grades($this->course->id, 'mod', 'workshop', $this->id, $userid);
  2225. $grades = new workshop_final_grades();
  2226. if (has_capability('mod/workshop:submit', $this->context, $userid)) {
  2227. if (!empty($gradebook->items[0]->grades)) {
  2228. $submissiongrade = reset($gradebook->items[0]->grades);
  2229. if (!is_null($submissiongrade->grade)) {
  2230. if (!$submissiongrade->hidden or has_capability('moodle/grade:viewhidden', $this->context, $userid)) {
  2231. $grades->submissiongrade = $submissiongrade;
  2232. }
  2233. }
  2234. }
  2235. }
  2236. if (has_capability('mod/workshop:peerassess', $this->context, $userid)) {
  2237. if (!empty($gradebook->items[1]->grades)) {
  2238. $assessmentgrade = reset($gradebook->items[1]->grades);
  2239. if (!is_null($assessmentgrade->grade)) {
  2240. if (!$assessmentgrade->hidden or has_capability('moodle/grade:viewhidden', $this->context, $userid)) {
  2241. $grades->assessmentgrade = $assessmentgrade;
  2242. }
  2243. }
  2244. }
  2245. }
  2246. if (!is_null($grades->submissiongrade) or !is_null($grades->assessmentgrade)) {
  2247. return $grades;
  2248. }
  2249. return false;
  2250. }
  2251. /**
  2252. * Return the editor options for the submission content field.
  2253. *
  2254. * @return array
  2255. */
  2256. public function submission_content_options() {
  2257. global $CFG;
  2258. require_once($CFG->dirroot.'/repository/lib.php');
  2259. return array(
  2260. 'trusttext' => true,
  2261. 'subdirs' => false,
  2262. 'maxfiles' => $this->nattachments,
  2263. 'maxbytes' => $this->maxbytes,
  2264. 'context' => $this->context,
  2265. 'return_types' => FILE_INTERNAL | FILE_EXTERNAL,
  2266. );
  2267. }
  2268. /**
  2269. * Return the filemanager options for the submission attachments field.
  2270. *
  2271. * @return array
  2272. */
  2273. public function submission_attachment_options() {
  2274. global $CFG;
  2275. require_once($CFG->dirroot.'/repository/lib.php');
  2276. $options = array(
  2277. 'subdirs' => true,
  2278. 'maxfiles' => $this->nattachments,
  2279. 'maxbytes' => $this->maxbytes,
  2280. 'return_types' => FILE_INTERNAL | FILE_CONTROLLED_LINK,
  2281. );
  2282. $filetypesutil = new \core_form\filetypes_util();
  2283. $options['accepted_types'] = $filetypesutil->normalize_file_types($this->submissionfiletypes);
  2284. return $options;
  2285. }
  2286. /**
  2287. * Return the editor options for the overall feedback for the author.
  2288. *
  2289. * @return array
  2290. */
  2291. public function overall_feedback_content_options() {
  2292. global $CFG;
  2293. require_once($CFG->dirroot.'/repository/lib.php');
  2294. return array(
  2295. 'subdirs' => 0,
  2296. 'maxbytes' => $this->overallfeedbackmaxbytes,
  2297. 'maxfiles' => $this->overallfeedbackfiles,
  2298. 'changeformat' => 1,
  2299. 'context' => $this->context,
  2300. 'return_types' => FILE_INTERNAL,
  2301. );
  2302. }
  2303. /**
  2304. * Return the filemanager options for the overall feedback for the author.
  2305. *
  2306. * @return array
  2307. */
  2308. public function overall_feedback_attachment_options() {
  2309. global $CFG;
  2310. require_once($CFG->dirroot.'/repository/lib.php');
  2311. $options = array(
  2312. 'subdirs' => 1,
  2313. 'maxbytes' => $this->overallfeedbackmaxbytes,
  2314. 'maxfiles' => $this->overallfeedbackfiles,
  2315. 'return_types' => FILE_INTERNAL | FILE_CONTROLLED_LINK,
  2316. );
  2317. $filetypesutil = new \core_form\filetypes_util();
  2318. $options['accepted_types'] = $filetypesutil->normalize_file_types($this->overallfeedbackfiletypes);
  2319. return $options;
  2320. }
  2321. /**
  2322. * Performs the reset of this workshop instance.
  2323. *
  2324. * @param stdClass $data The actual course reset settings.
  2325. * @return array List of results, each being array[(string)component, (string)item, (string)error]
  2326. */
  2327. public function reset_userdata(stdClass $data) {
  2328. $componentstr = get_string('pluginname', 'workshop').': '.format_string($this->name);
  2329. $status = array();
  2330. if (!empty($data->reset_workshop_assessments) or !empty($data->reset_workshop_submissions)) {
  2331. // Reset all data related to assessments, including assessments of
  2332. // example submissions.
  2333. $result = $this->reset_userdata_assessments($data);
  2334. if ($result === true) {
  2335. $status[] = array(
  2336. 'component' => $componentstr,
  2337. 'item' => get_string('resetassessments', 'mod_workshop'),
  2338. 'error' => false,
  2339. );
  2340. } else {
  2341. $status[] = array(
  2342. 'component' => $componentstr,
  2343. 'item' => get_string('resetassessments', 'mod_workshop'),
  2344. 'error' => $result,
  2345. );
  2346. }
  2347. }
  2348. if (!empty($data->reset_workshop_submissions)) {
  2349. // Reset all remaining data related to submissions.
  2350. $result = $this->reset_userdata_submissions($data);
  2351. if ($result === true) {
  2352. $status[] = array(
  2353. 'component' => $componentstr,
  2354. 'item' => get_string('resetsubmissions', 'mod_workshop'),
  2355. 'error' => false,
  2356. );
  2357. } else {
  2358. $status[] = array(
  2359. 'component' => $componentstr,
  2360. 'item' => get_string('resetsubmissions', 'mod_workshop'),
  2361. 'error' => $result,
  2362. );
  2363. }
  2364. }
  2365. if (!empty($data->reset_workshop_phase)) {
  2366. // Do not use the {@link workshop::switch_phase()} here, we do not
  2367. // want to trigger events.
  2368. $this->reset_phase();
  2369. $status[] = array(
  2370. 'component' => $componentstr,
  2371. 'item' => get_string('resetsubmissions', 'mod_workshop'),
  2372. 'error' => false,
  2373. );
  2374. }
  2375. return $status;
  2376. }
  2377. /**
  2378. * Check if the current user can access the other user's group.
  2379. *
  2380. * This is typically used for teacher roles that have permissions like
  2381. * 'view all submissions'. Even with such a permission granted, we have to
  2382. * check the workshop activity group mode.
  2383. *
  2384. * If the workshop is not in a group mode, or if it is in the visible group
  2385. * mode, this method returns true. This is consistent with how the
  2386. * {@link groups_get_activity_allowed_groups()} behaves.
  2387. *
  2388. * If the workshop is in a separate group mode, the current user has to
  2389. * have the 'access all groups' permission, or share at least one
  2390. * accessible group with the other user.
  2391. *
  2392. * @param int $otheruserid The ID of the other user, e.g. the author of a submission.
  2393. * @return bool False if the current user cannot access the other user's group.
  2394. */
  2395. public function check_group_membership($otheruserid) {
  2396. global $USER;
  2397. if (groups_get_activity_groupmode($this->cm) != SEPARATEGROUPS) {
  2398. // The workshop is not in a group mode, or it is in a visible group mode.
  2399. return true;
  2400. } else if (has_capability('moodle/site:accessallgroups', $this->context)) {
  2401. // The current user can access all groups.
  2402. return true;
  2403. } else {
  2404. $thisusersgroups = groups_get_all_groups($this->course->id, $USER->id, $this->cm->groupingid, 'g.id');
  2405. $otherusersgroups = groups_get_all_groups($this->course->id, $otheruserid, $this->cm->groupingid, 'g.id');
  2406. $commongroups = array_intersect_key($thisusersgroups, $otherusersgroups);
  2407. if (empty($commongroups)) {
  2408. // The current user has no group common with the other user.
  2409. return false;
  2410. } else {
  2411. // The current user has a group common with the other user.
  2412. return true;
  2413. }
  2414. }
  2415. }
  2416. /**
  2417. * Check whether the given user has assessed all his required examples before submission.
  2418. *
  2419. * @param int $userid the user to check
  2420. * @return bool false if there are examples missing assessment, true otherwise.
  2421. * @since Moodle 3.4
  2422. */
  2423. public function check_examples_assessed_before_submission($userid) {
  2424. if ($this->useexamples and $this->examplesmode == self::EXAMPLES_BEFORE_SUBMISSION
  2425. and !has_capability('mod/workshop:manageexamples', $this->context)) {
  2426. // Check that all required examples have been assessed by the user.
  2427. $examples = $this->get_examples_for_reviewer($userid);
  2428. foreach ($examples as $exampleid => $example) {
  2429. if (is_null($example->assessmentid)) {
  2430. $examples[$exampleid]->assessmentid = $this->add_allocation($example, $userid, 0);
  2431. }
  2432. if (is_null($example->grade)) {
  2433. return false;
  2434. }
  2435. }
  2436. }
  2437. return true;
  2438. }
  2439. /**
  2440. * Check that all required examples have been assessed by the given user.
  2441. *
  2442. * @param stdClass $userid the user (reviewer) to check
  2443. * @return mixed bool|state false and notice code if there are examples missing assessment, true otherwise.
  2444. * @since Moodle 3.4
  2445. */
  2446. public function check_examples_assessed_before_assessment($userid) {
  2447. if ($this->useexamples and $this->examplesmode == self::EXAMPLES_BEFORE_ASSESSMENT
  2448. and !has_capability('mod/workshop:manageexamples', $this->context)) {
  2449. // The reviewer must have submitted their own submission.
  2450. $reviewersubmission = $this->get_submission_by_author($userid);
  2451. if (!$reviewersubmission) {
  2452. // No money, no love.
  2453. return array(false, 'exampleneedsubmission');
  2454. } else {
  2455. $examples = $this->get_examples_for_reviewer($userid);
  2456. foreach ($examples as $exampleid => $example) {
  2457. if (is_null($example->grade)) {
  2458. return array(false, 'exampleneedassessed');
  2459. }
  2460. }
  2461. }
  2462. }
  2463. return array(true, null);
  2464. }
  2465. /**
  2466. * Trigger module viewed event and set the module viewed for completion.
  2467. *
  2468. * @since Moodle 3.4
  2469. */
  2470. public function set_module_viewed() {
  2471. global $CFG;
  2472. require_once($CFG->libdir . '/completionlib.php');
  2473. // Mark viewed.
  2474. $completion = new completion_info($this->course);
  2475. $completion->set_module_viewed($this->cm);
  2476. $eventdata = array();
  2477. $eventdata['objectid'] = $this->id;
  2478. $eventdata['context'] = $this->context;
  2479. // Trigger module viewed event.
  2480. $event = \mod_workshop\event\course_module_viewed::create($eventdata);
  2481. $event->add_record_snapshot('course', $this->course);
  2482. $event->add_record_snapshot('workshop', $this->dbrecord);
  2483. $event->add_record_snapshot('course_modules', $this->cm);
  2484. $event->trigger();
  2485. }
  2486. /**
  2487. * Validates the submission form or WS data.
  2488. *
  2489. * @param array $data the data to be validated
  2490. * @return array the validation errors (if any)
  2491. * @since Moodle 3.4
  2492. */
  2493. public function validate_submission_data($data) {
  2494. global $DB, $USER;
  2495. $errors = array();
  2496. if (empty($data['id']) and empty($data['example'])) {
  2497. // Make sure there is no submission saved meanwhile from another browser window.
  2498. $sql = "SELECT COUNT(s.id)
  2499. FROM {workshop_submissions} s
  2500. JOIN {workshop} w ON (s.workshopid = w.id)
  2501. JOIN {course_modules} cm ON (w.id = cm.instance)
  2502. JOIN {modules} m ON (m.name = 'workshop' AND m.id = cm.module)
  2503. WHERE cm.id = ? AND s.authorid = ? AND s.example = 0";
  2504. if ($DB->count_records_sql($sql, array($data['cmid'], $USER->id))) {
  2505. $errors['title'] = get_string('err_multiplesubmissions', 'mod_workshop');
  2506. }
  2507. }
  2508. // Get the workshop record by id or cmid, depending on whether we're creating or editing a submission.
  2509. if (empty($data['workshopid'])) {
  2510. $workshop = $DB->get_record_select('workshop', 'id = (SELECT instance FROM {course_modules} WHERE id = ?)',
  2511. [$data['cmid']]);
  2512. } else {
  2513. $workshop = $DB->get_record('workshop', ['id' => $data['workshopid']]);
  2514. }
  2515. if (isset($data['attachment_filemanager'])) {
  2516. $getfiles = file_get_drafarea_files($data['attachment_filemanager']);
  2517. $attachments = $getfiles->list;
  2518. } else {
  2519. $attachments = array();
  2520. }
  2521. if ($workshop->submissiontypefile == WORKSHOP_SUBMISSION_TYPE_REQUIRED) {
  2522. if (empty($attachments)) {
  2523. $errors['attachment_filemanager'] = get_string('err_required', 'form');
  2524. }
  2525. } else if ($workshop->submissiontypefile == WORKSHOP_SUBMISSION_TYPE_DISABLED && !empty($data['attachment_filemanager'])) {
  2526. $errors['attachment_filemanager'] = get_string('submissiontypedisabled', 'mod_workshop');
  2527. }
  2528. if ($workshop->submissiontypetext == WORKSHOP_SUBMISSION_TYPE_REQUIRED && html_is_blank($data['content_editor']['text'])) {
  2529. $errors['content_editor'] = get_string('err_required', 'form');
  2530. } else if ($workshop->submissiontypetext == WORKSHOP_SUBMISSION_TYPE_DISABLED && !empty($data['content_editor']['text'])) {
  2531. $errors['content_editor'] = get_string('submissiontypedisabled', 'mod_workshop');
  2532. }
  2533. // If neither type is explicitly required, one or the other must be submitted.
  2534. if ($workshop->submissiontypetext != WORKSHOP_SUBMISSION_TYPE_REQUIRED
  2535. && $workshop->submissiontypefile != WORKSHOP_SUBMISSION_TYPE_REQUIRED
  2536. && empty($attachments) && html_is_blank($data['content_editor']['text'])) {
  2537. $errors['content_editor'] = get_string('submissionrequiredcontent', 'mod_workshop');
  2538. $errors['attachment_filemanager'] = get_string('submissionrequiredfile', 'mod_workshop');
  2539. }
  2540. return $errors;
  2541. }
  2542. /**
  2543. * Adds or updates a submission.
  2544. *
  2545. * @param stdClass $submission The submissin data (via form or via WS).
  2546. * @return the new or updated submission id.
  2547. * @since Moodle 3.4
  2548. */
  2549. public function edit_submission($submission) {
  2550. global $USER, $DB;
  2551. if ($submission->example == 0) {
  2552. // This was used just for validation, it must be set to zero when dealing with normal submissions.
  2553. unset($submission->example);
  2554. } else {
  2555. throw new coding_exception('Invalid submission form data value: example');
  2556. }
  2557. $timenow = time();
  2558. if (is_null($submission->id)) {
  2559. $submission->workshopid = $this->id;
  2560. $submission->example = 0;
  2561. $submission->authorid = $USER->id;
  2562. $submission->timecreated = $timenow;
  2563. $submission->feedbackauthorformat = editors_get_preferred_format();
  2564. }
  2565. $submission->timemodified = $timenow;
  2566. $submission->title = trim($submission->title);
  2567. $submission->content = ''; // Updated later.
  2568. $submission->contentformat = FORMAT_HTML; // Updated later.
  2569. $submission->contenttrust = 0; // Updated later.
  2570. $submission->late = 0x0; // Bit mask.
  2571. if (!empty($this->submissionend) and ($this->submissionend < time())) {
  2572. $submission->late = $submission->late | 0x1;
  2573. }
  2574. if ($this->phase == self::PHASE_ASSESSMENT) {
  2575. $submission->late = $submission->late | 0x2;
  2576. }
  2577. // Event information.
  2578. $params = array(
  2579. 'context' => $this->context,
  2580. 'courseid' => $this->course->id,
  2581. 'other' => array(
  2582. 'submissiontitle' => $submission->title
  2583. )
  2584. );
  2585. $logdata = null;
  2586. if (is_null($submission->id)) {
  2587. $submission->id = $DB->insert_record('workshop_submissions', $submission);
  2588. $params['objectid'] = $submission->id;
  2589. $event = \mod_workshop\event\submission_created::create($params);
  2590. $event->trigger();
  2591. } else {
  2592. if (empty($submission->id) or empty($submission->id) or ($submission->id != $submission->id)) {
  2593. throw new moodle_exception('err_submissionid', 'workshop');
  2594. }
  2595. }
  2596. $params['objectid'] = $submission->id;
  2597. // Save and relink embedded images and save attachments.
  2598. if ($this->submissiontypetext != WORKSHOP_SUBMISSION_TYPE_DISABLED) {
  2599. $submission = file_postupdate_standard_editor($submission, 'content', $this->submission_content_options(),
  2600. $this->context, 'mod_workshop', 'submission_content', $submission->id);
  2601. }
  2602. $submission = file_postupdate_standard_filemanager($submission, 'attachment', $this->submission_attachment_options(),
  2603. $this->context, 'mod_workshop', 'submission_attachment', $submission->id);
  2604. if (empty($submission->attachment)) {
  2605. // Explicit cast to zero integer.
  2606. $submission->attachment = 0;
  2607. }
  2608. // Store the updated values or re-save the new submission (re-saving needed because URLs are now rewritten).
  2609. $DB->update_record('workshop_submissions', $submission);
  2610. $event = \mod_workshop\event\submission_updated::create($params);
  2611. $event->add_record_snapshot('workshop', $this->dbrecord);
  2612. $event->trigger();
  2613. // Send submitted content for plagiarism detection.
  2614. $fs = get_file_storage();
  2615. $files = $fs->get_area_files($this->context->id, 'mod_workshop', 'submission_attachment', $submission->id);
  2616. $params['other']['content'] = $submission->content;
  2617. $params['other']['pathnamehashes'] = array_keys($files);
  2618. $event = \mod_workshop\event\assessable_uploaded::create($params);
  2619. $event->set_legacy_logdata($logdata);
  2620. $event->trigger();
  2621. return $submission->id;
  2622. }
  2623. /**
  2624. * Helper method for validating if the current user can view the given assessment.
  2625. *
  2626. * @param stdClass $assessment assessment object
  2627. * @param stdClass $submission submission object
  2628. * @return void
  2629. * @throws moodle_exception
  2630. * @since Moodle 3.4
  2631. */
  2632. public function check_view_assessment($assessment, $submission) {
  2633. global $USER;
  2634. $isauthor = $submission->authorid == $USER->id;
  2635. $isreviewer = $assessment->reviewerid == $USER->id;
  2636. $canviewallassessments = has_capability('mod/workshop:viewallassessments', $this->context);
  2637. $canviewallsubmissions = has_capability('mod/workshop:viewallsubmissions', $this->context);
  2638. $canviewallsubmissions = $canviewallsubmissions && $this->check_group_membership($submission->authorid);
  2639. if (!$isreviewer and !$isauthor and !($canviewallassessments and $canviewallsubmissions)) {
  2640. print_error('nopermissions', 'error', $this->view_url(), 'view this assessment');
  2641. }
  2642. if ($isauthor and !$isreviewer and !$canviewallassessments and $this->phase != self::PHASE_CLOSED) {
  2643. // Authors can see assessments of their work at the end of workshop only.
  2644. print_error('nopermissions', 'error', $this->view_url(), 'view assessment of own work before workshop is closed');
  2645. }
  2646. }
  2647. /**
  2648. * Helper method for validating if the current user can edit the given assessment.
  2649. *
  2650. * @param stdClass $assessment assessment object
  2651. * @param stdClass $submission submission object
  2652. * @return void
  2653. * @throws moodle_exception
  2654. * @since Moodle 3.4
  2655. */
  2656. public function check_edit_assessment($assessment, $submission) {
  2657. global $USER;
  2658. $this->check_view_assessment($assessment, $submission);
  2659. // Further checks.
  2660. $isreviewer = ($USER->id == $assessment->reviewerid);
  2661. $assessmenteditable = $isreviewer && $this->assessing_allowed($USER->id);
  2662. if (!$assessmenteditable) {
  2663. throw new moodle_exception('nopermissions', 'error', '', 'edit assessments');
  2664. }
  2665. list($assessed, $notice) = $this->check_examples_assessed_before_assessment($assessment->reviewerid);
  2666. if (!$assessed) {
  2667. throw new moodle_exception($notice, 'mod_workshop');
  2668. }
  2669. }
  2670. /**
  2671. * Adds information to an allocated assessment (function used the first time a review is done or when updating an existing one).
  2672. *
  2673. * @param stdClass $assessment the assessment
  2674. * @param stdClass $submission the submission
  2675. * @param stdClass $data the assessment data to be added or Updated
  2676. * @param stdClass $strategy the strategy instance
  2677. * @return float|null Raw percentual grade (0.00000 to 100.00000) for submission
  2678. * @since Moodle 3.4
  2679. */
  2680. public function edit_assessment($assessment, $submission, $data, $strategy) {
  2681. global $DB;
  2682. $cansetassessmentweight = has_capability('mod/workshop:allocate', $this->context);
  2683. // Let the grading strategy subplugin save its data.
  2684. $rawgrade = $strategy->save_assessment($assessment, $data);
  2685. // Store the data managed by the workshop core.
  2686. $coredata = (object)array('id' => $assessment->id);
  2687. if (isset($data->feedbackauthor_editor)) {
  2688. $coredata->feedbackauthor_editor = $data->feedbackauthor_editor;
  2689. $coredata = file_postupdate_standard_editor($coredata, 'feedbackauthor', $this->overall_feedback_content_options(),
  2690. $this->context, 'mod_workshop', 'overallfeedback_content', $assessment->id);
  2691. unset($coredata->feedbackauthor_editor);
  2692. }
  2693. if (isset($data->feedbackauthorattachment_filemanager)) {
  2694. $coredata->feedbackauthorattachment_filemanager = $data->feedbackauthorattachment_filemanager;
  2695. $coredata = file_postupdate_standard_filemanager($coredata, 'feedbackauthorattachment',
  2696. $this->overall_feedback_attachment_options(), $this->context, 'mod_workshop', 'overallfeedback_attachment',
  2697. $assessment->id);
  2698. unset($coredata->feedbackauthorattachment_filemanager);
  2699. if (empty($coredata->feedbackauthorattachment)) {
  2700. $coredata->feedbackauthorattachment = 0;
  2701. }
  2702. }
  2703. if (isset($data->weight) and $cansetassessmentweight) {
  2704. $coredata->weight = $data->weight;
  2705. }
  2706. // Update the assessment data if there is something other than just the 'id'.
  2707. if (count((array)$coredata) > 1 ) {
  2708. $DB->update_record('workshop_assessments', $coredata);
  2709. $params = array(
  2710. 'relateduserid' => $submission->authorid,
  2711. 'objectid' => $assessment->id,
  2712. 'context' => $this->context,
  2713. 'other' => array(
  2714. 'workshopid' => $this->id,
  2715. 'submissionid' => $assessment->submissionid
  2716. )
  2717. );
  2718. if (is_null($assessment->grade)) {
  2719. // All workshop_assessments are created when allocations are made. The create event is of more use located here.
  2720. $event = \mod_workshop\event\submission_assessed::create($params);
  2721. $event->trigger();
  2722. } else {
  2723. $params['other']['grade'] = $assessment->grade;
  2724. $event = \mod_workshop\event\submission_reassessed::create($params);
  2725. $event->trigger();
  2726. }
  2727. }
  2728. return $rawgrade;
  2729. }
  2730. /**
  2731. * Evaluates an assessment.
  2732. *
  2733. * @param stdClass $assessment the assessment
  2734. * @param stdClass $data the assessment data to be updated
  2735. * @param bool $cansetassessmentweight whether the user can change the assessment weight
  2736. * @param bool $canoverridegrades whether the user can override the assessment grades
  2737. * @return void
  2738. * @since Moodle 3.4
  2739. */
  2740. public function evaluate_assessment($assessment, $data, $cansetassessmentweight, $canoverridegrades) {
  2741. global $DB, $USER;
  2742. $data = file_postupdate_standard_editor($data, 'feedbackreviewer', array(), $this->context);
  2743. $record = new stdclass();
  2744. $record->id = $assessment->id;
  2745. if ($cansetassessmentweight) {
  2746. $record->weight = $data->weight;
  2747. }
  2748. if ($canoverridegrades) {
  2749. $record->gradinggradeover = $this->raw_grade_value($data->gradinggradeover, $this->gradinggrade);
  2750. $record->gradinggradeoverby = $USER->id;
  2751. $record->feedbackreviewer = $data->feedbackreviewer;
  2752. $record->feedbackreviewerformat = $data->feedbackreviewerformat;
  2753. }
  2754. $DB->update_record('workshop_assessments', $record);
  2755. }
  2756. /**
  2757. * Trigger submission viewed event.
  2758. *
  2759. * @param stdClass $submission submission object
  2760. * @since Moodle 3.4
  2761. */
  2762. public function set_submission_viewed($submission) {
  2763. $params = array(
  2764. 'objectid' => $submission->id,
  2765. 'context' => $this->context,
  2766. 'courseid' => $this->course->id,
  2767. 'relateduserid' => $submission->authorid,
  2768. 'other' => array(
  2769. 'workshopid' => $this->id
  2770. )
  2771. );
  2772. $event = \mod_workshop\event\submission_viewed::create($params);
  2773. $event->trigger();
  2774. }
  2775. /**
  2776. * Evaluates a submission.
  2777. *
  2778. * @param stdClass $submission the submission
  2779. * @param stdClass $data the submission data to be updated
  2780. * @param bool $canpublish whether the user can publish the submission
  2781. * @param bool $canoverride whether the user can override the submission grade
  2782. * @return void
  2783. * @since Moodle 3.4
  2784. */
  2785. public function evaluate_submission($submission, $data, $canpublish, $canoverride) {
  2786. global $DB, $USER;
  2787. $data = file_postupdate_standard_editor($data, 'feedbackauthor', array(), $this->context);
  2788. $record = new stdclass();
  2789. $record->id = $submission->id;
  2790. if ($canoverride) {
  2791. $record->gradeover = $this->raw_grade_value($data->gradeover, $this->grade);
  2792. $record->gradeoverby = $USER->id;
  2793. $record->feedbackauthor = $data->feedbackauthor;
  2794. $record->feedbackauthorformat = $data->feedbackauthorformat;
  2795. }
  2796. if ($canpublish) {
  2797. $record->published = !empty($data->published);
  2798. }
  2799. $DB->update_record('workshop_submissions', $record);
  2800. }
  2801. ////////////////////////////////////////////////////////////////////////////////
  2802. // Internal methods (implementation details) //
  2803. ////////////////////////////////////////////////////////////////////////////////
  2804. /**
  2805. * Given an array of all assessments of a single submission, calculates the final grade for this submission
  2806. *
  2807. * This calculates the weighted mean of the passed assessment grades. If, however, the submission grade
  2808. * was overridden by a teacher, the gradeover value is returned and the rest of grades are ignored.
  2809. *
  2810. * @param array $assessments of stdclass(->submissionid ->submissiongrade ->gradeover ->weight ->grade)
  2811. * @return void
  2812. */
  2813. protected function aggregate_submission_grades_process(array $assessments) {
  2814. global $DB;
  2815. $submissionid = null; // the id of the submission being processed
  2816. $current = null; // the grade currently saved in database
  2817. $finalgrade = null; // the new grade to be calculated
  2818. $sumgrades = 0;
  2819. $sumweights = 0;
  2820. foreach ($assessments as $assessment) {
  2821. if (is_null($submissionid)) {
  2822. // the id is the same in all records, fetch it during the first loop cycle
  2823. $submissionid = $assessment->submissionid;
  2824. }
  2825. if (is_null($current)) {
  2826. // the currently saved grade is the same in all records, fetch it during the first loop cycle
  2827. $current = $assessment->submissiongrade;
  2828. }
  2829. if (is_null($assessment->grade)) {
  2830. // this was not assessed yet
  2831. continue;
  2832. }
  2833. if ($assessment->weight == 0) {
  2834. // this does not influence the calculation
  2835. continue;
  2836. }
  2837. $sumgrades += $assessment->grade * $assessment->weight;
  2838. $sumweights += $assessment->weight;
  2839. }
  2840. if ($sumweights > 0 and is_null($finalgrade)) {
  2841. $finalgrade = grade_floatval($sumgrades / $sumweights);
  2842. }
  2843. // check if the new final grade differs from the one stored in the database
  2844. if (grade_floats_different($finalgrade, $current)) {
  2845. // we need to save new calculation into the database
  2846. $record = new stdclass();
  2847. $record->id = $submissionid;
  2848. $record->grade = $finalgrade;
  2849. $record->timegraded = time();
  2850. $DB->update_record('workshop_submissions', $record);
  2851. }
  2852. }
  2853. /**
  2854. * Given an array of all assessments done by a single reviewer, calculates the final grading grade
  2855. *
  2856. * This calculates the simple mean of the passed grading grades. If, however, the grading grade
  2857. * was overridden by a teacher, the gradinggradeover value is returned and the rest of grades are ignored.
  2858. *
  2859. * @param array $assessments of stdclass(->reviewerid ->gradinggrade ->gradinggradeover ->aggregationid ->aggregatedgrade)
  2860. * @param null|int $timegraded explicit timestamp of the aggregation, defaults to the current time
  2861. * @return void
  2862. */
  2863. protected function aggregate_grading_grades_process(array $assessments, $timegraded = null) {
  2864. global $DB;
  2865. $reviewerid = null; // the id of the reviewer being processed
  2866. $current = null; // the gradinggrade currently saved in database
  2867. $finalgrade = null; // the new grade to be calculated
  2868. $agid = null; // aggregation id
  2869. $sumgrades = 0;
  2870. $count = 0;
  2871. if (is_null($timegraded)) {
  2872. $timegraded = time();
  2873. }
  2874. foreach ($assessments as $assessment) {
  2875. if (is_null($reviewerid)) {
  2876. // the id is the same in all records, fetch it during the first loop cycle
  2877. $reviewerid = $assessment->reviewerid;
  2878. }
  2879. if (is_null($agid)) {
  2880. // the id is the same in all records, fetch it during the first loop cycle
  2881. $agid = $assessment->aggregationid;
  2882. }
  2883. if (is_null($current)) {
  2884. // the currently saved grade is the same in all records, fetch it during the first loop cycle
  2885. $current = $assessment->aggregatedgrade;
  2886. }
  2887. if (!is_null($assessment->gradinggradeover)) {
  2888. // the grading grade for this assessment is overridden by a teacher
  2889. $sumgrades += $assessment->gradinggradeover;
  2890. $count++;
  2891. } else {
  2892. if (!is_null($assessment->gradinggrade)) {
  2893. $sumgrades += $assessment->gradinggrade;
  2894. $count++;
  2895. }
  2896. }
  2897. }
  2898. if ($count > 0) {
  2899. $finalgrade = grade_floatval($sumgrades / $count);
  2900. }
  2901. // Event information.
  2902. $params = array(
  2903. 'context' => $this->context,
  2904. 'courseid' => $this->course->id,
  2905. 'relateduserid' => $reviewerid
  2906. );
  2907. // check if the new final grade differs from the one stored in the database
  2908. if (grade_floats_different($finalgrade, $current)) {
  2909. $params['other'] = array(
  2910. 'currentgrade' => $current,
  2911. 'finalgrade' => $finalgrade
  2912. );
  2913. // we need to save new calculation into the database
  2914. if (is_null($agid)) {
  2915. // no aggregation record yet
  2916. $record = new stdclass();
  2917. $record->workshopid = $this->id;
  2918. $record->userid = $reviewerid;
  2919. $record->gradinggrade = $finalgrade;
  2920. $record->timegraded = $timegraded;
  2921. $record->id = $DB->insert_record('workshop_aggregations', $record);
  2922. $params['objectid'] = $record->id;
  2923. $event = \mod_workshop\event\assessment_evaluated::create($params);
  2924. $event->trigger();
  2925. } else {
  2926. $record = new stdclass();
  2927. $record->id = $agid;
  2928. $record->gradinggrade = $finalgrade;
  2929. $record->timegraded = $timegraded;
  2930. $DB->update_record('workshop_aggregations', $record);
  2931. $params['objectid'] = $agid;
  2932. $event = \mod_workshop\event\assessment_reevaluated::create($params);
  2933. $event->trigger();
  2934. }
  2935. }
  2936. }
  2937. /**
  2938. * Returns SQL to fetch all enrolled users with the given capability in the current workshop
  2939. *
  2940. * The returned array consists of string $sql and the $params array. Note that the $sql can be
  2941. * empty if a grouping is selected and it has no groups.
  2942. *
  2943. * The list is automatically restricted according to any availability restrictions
  2944. * that apply to user lists (e.g. group, grouping restrictions).
  2945. *
  2946. * @param string $capability the name of the capability
  2947. * @param bool $musthavesubmission ff true, return only users who have already submitted
  2948. * @param int $groupid 0 means ignore groups, any other value limits the result by group id
  2949. * @return array of (string)sql, (array)params
  2950. */
  2951. protected function get_users_with_capability_sql($capability, $musthavesubmission, $groupid) {
  2952. global $CFG;
  2953. /** @var int static counter used to generate unique parameter holders */
  2954. static $inc = 0;
  2955. $inc++;
  2956. // If the caller requests all groups and we are using a selected grouping,
  2957. // recursively call this function for each group in the grouping (this is
  2958. // needed because get_enrolled_sql only supports a single group).
  2959. if (empty($groupid) and $this->cm->groupingid) {
  2960. $groupingid = $this->cm->groupingid;
  2961. $groupinggroupids = array_keys(groups_get_all_groups($this->cm->course, 0, $this->cm->groupingid, 'g.id'));
  2962. $sql = array();
  2963. $params = array();
  2964. foreach ($groupinggroupids as $groupinggroupid) {
  2965. if ($groupinggroupid > 0) { // just in case in order not to fall into the endless loop
  2966. list($gsql, $gparams) = $this->get_users_with_capability_sql($capability, $musthavesubmission, $groupinggroupid);
  2967. $sql[] = $gsql;
  2968. $params = array_merge($params, $gparams);
  2969. }
  2970. }
  2971. $sql = implode(PHP_EOL." UNION ".PHP_EOL, $sql);
  2972. return array($sql, $params);
  2973. }
  2974. list($esql, $params) = get_enrolled_sql($this->context, $capability, $groupid, true);
  2975. $userfieldsapi = \core_user\fields::for_userpic();
  2976. $userfields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
  2977. $sql = "SELECT $userfields
  2978. FROM {user} u
  2979. JOIN ($esql) je ON (je.id = u.id AND u.deleted = 0) ";
  2980. if ($musthavesubmission) {
  2981. $sql .= " JOIN {workshop_submissions} ws ON (ws.authorid = u.id AND ws.example = 0 AND ws.workshopid = :workshopid{$inc}) ";
  2982. $params['workshopid'.$inc] = $this->id;
  2983. }
  2984. // If the activity is restricted so that only certain users should appear
  2985. // in user lists, integrate this into the same SQL.
  2986. $info = new \core_availability\info_module($this->cm);
  2987. list ($listsql, $listparams) = $info->get_user_list_sql(false);
  2988. if ($listsql) {
  2989. $sql .= " JOIN ($listsql) restricted ON restricted.id = u.id ";
  2990. $params = array_merge($params, $listparams);
  2991. }
  2992. return array($sql, $params);
  2993. }
  2994. /**
  2995. * Returns SQL statement that can be used to fetch all actively enrolled participants in the workshop
  2996. *
  2997. * @param bool $musthavesubmission if true, return only users who have already submitted
  2998. * @param int $groupid 0 means ignore groups, any other value limits the result by group id
  2999. * @return array of (string)sql, (array)params
  3000. */
  3001. protected function get_participants_sql($musthavesubmission=false, $groupid=0) {
  3002. list($sql1, $params1) = $this->get_users_with_capability_sql('mod/workshop:submit', $musthavesubmission, $groupid);
  3003. list($sql2, $params2) = $this->get_users_with_capability_sql('mod/workshop:peerassess', $musthavesubmission, $groupid);
  3004. if (empty($sql1) or empty($sql2)) {
  3005. if (empty($sql1) and empty($sql2)) {
  3006. return array('', array());
  3007. } else if (empty($sql1)) {
  3008. $sql = $sql2;
  3009. $params = $params2;
  3010. } else {
  3011. $sql = $sql1;
  3012. $params = $params1;
  3013. }
  3014. } else {
  3015. $sql = $sql1.PHP_EOL." UNION ".PHP_EOL.$sql2;
  3016. $params = array_merge($params1, $params2);
  3017. }
  3018. return array($sql, $params);
  3019. }
  3020. /**
  3021. * @return array of available workshop phases
  3022. */
  3023. protected function available_phases_list() {
  3024. return array(
  3025. self::PHASE_SETUP => true,
  3026. self::PHASE_SUBMISSION => true,
  3027. self::PHASE_ASSESSMENT => true,
  3028. self::PHASE_EVALUATION => true,
  3029. self::PHASE_CLOSED => true,
  3030. );
  3031. }
  3032. /**
  3033. * Converts absolute URL to relative URL needed by {@see add_to_log()}
  3034. *
  3035. * @param moodle_url $url absolute URL
  3036. * @return string
  3037. */
  3038. protected function log_convert_url(moodle_url $fullurl) {
  3039. static $baseurl;
  3040. if (!isset($baseurl)) {
  3041. $baseurl = new moodle_url('/mod/workshop/');
  3042. $baseurl = $baseurl->out();
  3043. }
  3044. return substr($fullurl->out(), strlen($baseurl));
  3045. }
  3046. /**
  3047. * Removes all user data related to assessments (including allocations).
  3048. *
  3049. * This includes assessments of example submissions as long as they are not
  3050. * referential assessments.
  3051. *
  3052. * @param stdClass $data The actual course reset settings.
  3053. * @return bool|string True on success, error message otherwise.
  3054. */
  3055. protected function reset_userdata_assessments(stdClass $data) {
  3056. global $DB;
  3057. $sql = "SELECT a.id
  3058. FROM {workshop_assessments} a
  3059. JOIN {workshop_submissions} s ON (a.submissionid = s.id)
  3060. WHERE s.workshopid = :workshopid
  3061. AND (s.example = 0 OR (s.example = 1 AND a.weight = 0))";
  3062. $assessments = $DB->get_records_sql($sql, array('workshopid' => $this->id));
  3063. $this->delete_assessment(array_keys($assessments));
  3064. $DB->delete_records('workshop_aggregations', array('workshopid' => $this->id));
  3065. return true;
  3066. }
  3067. /**
  3068. * Removes all user data related to participants' submissions.
  3069. *
  3070. * @param stdClass $data The actual course reset settings.
  3071. * @return bool|string True on success, error message otherwise.
  3072. */
  3073. protected function reset_userdata_submissions(stdClass $data) {
  3074. global $DB;
  3075. $submissions = $this->get_submissions();
  3076. foreach ($submissions as $submission) {
  3077. $this->delete_submission($submission);
  3078. }
  3079. return true;
  3080. }
  3081. /**
  3082. * Hard set the workshop phase to the setup one.
  3083. */
  3084. protected function reset_phase() {
  3085. global $DB;
  3086. $DB->set_field('workshop', 'phase', self::PHASE_SETUP, array('id' => $this->id));
  3087. $this->phase = self::PHASE_SETUP;
  3088. }
  3089. }
  3090. ////////////////////////////////////////////////////////////////////////////////
  3091. // Renderable components
  3092. ////////////////////////////////////////////////////////////////////////////////
  3093. /**
  3094. * Represents the user planner tool
  3095. *
  3096. * Planner contains list of phases. Each phase contains list of tasks. Task is a simple object with
  3097. * title, link and completed (true/false/null logic).
  3098. */
  3099. class workshop_user_plan implements renderable {
  3100. /** @var int id of the user this plan is for */
  3101. public $userid;
  3102. /** @var workshop */
  3103. public $workshop;
  3104. /** @var array of (stdclass)tasks */
  3105. public $phases = array();
  3106. /** @var null|array of example submissions to be assessed by the planner owner */
  3107. protected $examples = null;
  3108. /**
  3109. * Prepare an individual workshop plan for the given user.
  3110. *
  3111. * @param workshop $workshop instance
  3112. * @param int $userid whom the plan is prepared for
  3113. */
  3114. public function __construct(workshop $workshop, $userid) {
  3115. global $DB;
  3116. $this->workshop = $workshop;
  3117. $this->userid = $userid;
  3118. //---------------------------------------------------------
  3119. // * SETUP | submission | assessment | evaluation | closed
  3120. //---------------------------------------------------------
  3121. $phase = new stdclass();
  3122. $phase->title = get_string('phasesetup', 'workshop');
  3123. $phase->tasks = array();
  3124. if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) {
  3125. $task = new stdclass();
  3126. $task->title = get_string('taskintro', 'workshop');
  3127. $task->link = $workshop->updatemod_url();
  3128. $task->completed = !(trim($workshop->intro) == '');
  3129. $phase->tasks['intro'] = $task;
  3130. }
  3131. if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) {
  3132. $task = new stdclass();
  3133. $task->title = get_string('taskinstructauthors', 'workshop');
  3134. $task->link = $workshop->updatemod_url();
  3135. $task->completed = !(trim($workshop->instructauthors) == '');
  3136. $phase->tasks['instructauthors'] = $task;
  3137. }
  3138. if (has_capability('mod/workshop:editdimensions', $workshop->context, $userid)) {
  3139. $task = new stdclass();
  3140. $task->title = get_string('editassessmentform', 'workshop');
  3141. $task->link = $workshop->editform_url();
  3142. if ($workshop->grading_strategy_instance()->form_ready()) {
  3143. $task->completed = true;
  3144. } elseif ($workshop->phase > workshop::PHASE_SETUP) {
  3145. $task->completed = false;
  3146. }
  3147. $phase->tasks['editform'] = $task;
  3148. }
  3149. if ($workshop->useexamples and has_capability('mod/workshop:manageexamples', $workshop->context, $userid)) {
  3150. $task = new stdclass();
  3151. $task->title = get_string('prepareexamples', 'workshop');
  3152. if ($DB->count_records('workshop_submissions', array('example' => 1, 'workshopid' => $workshop->id)) > 0) {
  3153. $task->completed = true;
  3154. } elseif ($workshop->phase > workshop::PHASE_SETUP) {
  3155. $task->completed = false;
  3156. }
  3157. $phase->tasks['prepareexamples'] = $task;
  3158. }
  3159. if (empty($phase->tasks) and $workshop->phase == workshop::PHASE_SETUP) {
  3160. // if we are in the setup phase and there is no task (typical for students), let us
  3161. // display some explanation what is going on
  3162. $task = new stdclass();
  3163. $task->title = get_string('undersetup', 'workshop');
  3164. $task->completed = 'info';
  3165. $phase->tasks['setupinfo'] = $task;
  3166. }
  3167. $this->phases[workshop::PHASE_SETUP] = $phase;
  3168. //---------------------------------------------------------
  3169. // setup | * SUBMISSION | assessment | evaluation | closed
  3170. //---------------------------------------------------------
  3171. $phase = new stdclass();
  3172. $phase->title = get_string('phasesubmission', 'workshop');
  3173. $phase->tasks = array();
  3174. if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) {
  3175. $task = new stdclass();
  3176. $task->title = get_string('taskinstructreviewers', 'workshop');
  3177. $task->link = $workshop->updatemod_url();
  3178. if (trim($workshop->instructreviewers)) {
  3179. $task->completed = true;
  3180. } elseif ($workshop->phase >= workshop::PHASE_ASSESSMENT) {
  3181. $task->completed = false;
  3182. }
  3183. $phase->tasks['instructreviewers'] = $task;
  3184. }
  3185. if ($workshop->useexamples and $workshop->examplesmode == workshop::EXAMPLES_BEFORE_SUBMISSION
  3186. and has_capability('mod/workshop:submit', $workshop->context, $userid, false)
  3187. and !has_capability('mod/workshop:manageexamples', $workshop->context, $userid)) {
  3188. $task = new stdclass();
  3189. $task->title = get_string('exampleassesstask', 'workshop');
  3190. $examples = $this->get_examples();
  3191. $a = new stdclass();
  3192. $a->expected = count($examples);
  3193. $a->assessed = 0;
  3194. foreach ($examples as $exampleid => $example) {
  3195. if (!is_null($example->grade)) {
  3196. $a->assessed++;
  3197. }
  3198. }
  3199. $task->details = get_string('exampleassesstaskdetails', 'workshop', $a);
  3200. if ($a->assessed == $a->expected) {
  3201. $task->completed = true;
  3202. } elseif ($workshop->phase >= workshop::PHASE_ASSESSMENT) {
  3203. $task->completed = false;
  3204. }
  3205. $phase->tasks['examples'] = $task;
  3206. }
  3207. if (has_capability('mod/workshop:submit', $workshop->context, $userid, false)) {
  3208. $task = new stdclass();
  3209. $task->title = get_string('tasksubmit', 'workshop');
  3210. $task->link = $workshop->submission_url();
  3211. if ($DB->record_exists('workshop_submissions', array('workshopid'=>$workshop->id, 'example'=>0, 'authorid'=>$userid))) {
  3212. $task->completed = true;
  3213. } elseif ($workshop->phase >= workshop::PHASE_ASSESSMENT) {
  3214. $task->completed = false;
  3215. } else {
  3216. $task->completed = null; // still has a chance to submit
  3217. }
  3218. $phase->tasks['submit'] = $task;
  3219. }
  3220. if (has_capability('mod/workshop:allocate', $workshop->context, $userid)) {
  3221. if ($workshop->phaseswitchassessment) {
  3222. $task = new stdClass();
  3223. $allocator = $DB->get_record('workshopallocation_scheduled', array('workshopid' => $workshop->id));
  3224. if (empty($allocator)) {
  3225. $task->completed = false;
  3226. } else if ($allocator->enabled and is_null($allocator->resultstatus)) {
  3227. $task->completed = true;
  3228. } else if ($workshop->submissionend > time()) {
  3229. $task->completed = null;
  3230. } else {
  3231. $task->completed = false;
  3232. }
  3233. $task->title = get_string('setup', 'workshopallocation_scheduled');
  3234. $task->link = $workshop->allocation_url('scheduled');
  3235. $phase->tasks['allocatescheduled'] = $task;
  3236. }
  3237. $task = new stdclass();
  3238. $task->title = get_string('allocate', 'workshop');
  3239. $task->link = $workshop->allocation_url();
  3240. $numofauthors = $workshop->count_potential_authors(false);
  3241. $numofsubmissions = $DB->count_records('workshop_submissions', array('workshopid'=>$workshop->id, 'example'=>0));
  3242. $sql = 'SELECT COUNT(s.id) AS nonallocated
  3243. FROM {workshop_submissions} s
  3244. LEFT JOIN {workshop_assessments} a ON (a.submissionid=s.id)
  3245. WHERE s.workshopid = :workshopid AND s.example=0 AND a.submissionid IS NULL';
  3246. $params['workshopid'] = $workshop->id;
  3247. $numnonallocated = $DB->count_records_sql($sql, $params);
  3248. if ($numofsubmissions == 0) {
  3249. $task->completed = null;
  3250. } elseif ($numnonallocated == 0) {
  3251. $task->completed = true;
  3252. } elseif ($workshop->phase > workshop::PHASE_SUBMISSION) {
  3253. $task->completed = false;
  3254. } else {
  3255. $task->completed = null; // still has a chance to allocate
  3256. }
  3257. $a = new stdclass();
  3258. $a->expected = $numofauthors;
  3259. $a->submitted = $numofsubmissions;
  3260. $a->allocate = $numnonallocated;
  3261. $task->details = get_string('allocatedetails', 'workshop', $a);
  3262. unset($a);
  3263. $phase->tasks['allocate'] = $task;
  3264. if ($numofsubmissions < $numofauthors and $workshop->phase >= workshop::PHASE_SUBMISSION) {
  3265. $task = new stdclass();
  3266. $task->title = get_string('someuserswosubmission', 'workshop');
  3267. $task->completed = 'info';
  3268. $phase->tasks['allocateinfo'] = $task;
  3269. }
  3270. }
  3271. if ($workshop->submissionstart) {
  3272. $task = new stdclass();
  3273. $task->title = get_string('submissionstartdatetime', 'workshop', workshop::timestamp_formats($workshop->submissionstart));
  3274. $task->completed = 'info';
  3275. $phase->tasks['submissionstartdatetime'] = $task;
  3276. }
  3277. if ($workshop->submissionend) {
  3278. $task = new stdclass();
  3279. $task->title = get_string('submissionenddatetime', 'workshop', workshop::timestamp_formats($workshop->submissionend));
  3280. $task->completed = 'info';
  3281. $phase->tasks['submissionenddatetime'] = $task;
  3282. }
  3283. if (($workshop->submissionstart < time()) and $workshop->latesubmissions) {
  3284. // If submission deadline has passed and late submissions are allowed, only display 'latesubmissionsallowed' text to
  3285. // users (students) who have not submitted and users(teachers, admins) who can switch pahase..
  3286. if (has_capability('mod/workshop:switchphase', $workshop->context, $userid) ||
  3287. (!$workshop->get_submission_by_author($userid) && $workshop->submissionend < time())) {
  3288. $task = new stdclass();
  3289. $task->title = get_string('latesubmissionsallowed', 'workshop');
  3290. $task->completed = 'info';
  3291. $phase->tasks['latesubmissionsallowed'] = $task;
  3292. }
  3293. }
  3294. if (isset($phase->tasks['submissionstartdatetime']) or isset($phase->tasks['submissionenddatetime'])) {
  3295. if (has_capability('mod/workshop:ignoredeadlines', $workshop->context, $userid)) {
  3296. $task = new stdclass();
  3297. $task->title = get_string('deadlinesignored', 'workshop');
  3298. $task->completed = 'info';
  3299. $phase->tasks['deadlinesignored'] = $task;
  3300. }
  3301. }
  3302. $this->phases[workshop::PHASE_SUBMISSION] = $phase;
  3303. //---------------------------------------------------------
  3304. // setup | submission | * ASSESSMENT | evaluation | closed
  3305. //---------------------------------------------------------
  3306. $phase = new stdclass();
  3307. $phase->title = get_string('phaseassessment', 'workshop');
  3308. $phase->tasks = array();
  3309. $phase->isreviewer = has_capability('mod/workshop:peerassess', $workshop->context, $userid);
  3310. if ($workshop->phase == workshop::PHASE_SUBMISSION and $workshop->phaseswitchassessment
  3311. and has_capability('mod/workshop:switchphase', $workshop->context, $userid)) {
  3312. $task = new stdClass();
  3313. $task->title = get_string('switchphase30auto', 'mod_workshop', workshop::timestamp_formats($workshop->submissionend));
  3314. $task->completed = 'info';
  3315. $phase->tasks['autoswitchinfo'] = $task;
  3316. }
  3317. if ($workshop->useexamples and $workshop->examplesmode == workshop::EXAMPLES_BEFORE_ASSESSMENT
  3318. and $phase->isreviewer and !has_capability('mod/workshop:manageexamples', $workshop->context, $userid)) {
  3319. $task = new stdclass();
  3320. $task->title = get_string('exampleassesstask', 'workshop');
  3321. $examples = $workshop->get_examples_for_reviewer($userid);
  3322. $a = new stdclass();
  3323. $a->expected = count($examples);
  3324. $a->assessed = 0;
  3325. foreach ($examples as $exampleid => $example) {
  3326. if (!is_null($example->grade)) {
  3327. $a->assessed++;
  3328. }
  3329. }
  3330. $task->details = get_string('exampleassesstaskdetails', 'workshop', $a);
  3331. if ($a->assessed == $a->expected) {
  3332. $task->completed = true;
  3333. } elseif ($workshop->phase > workshop::PHASE_ASSESSMENT) {
  3334. $task->completed = false;
  3335. }
  3336. $phase->tasks['examples'] = $task;
  3337. }
  3338. if (empty($phase->tasks['examples']) or !empty($phase->tasks['examples']->completed)) {
  3339. $phase->assessments = $workshop->get_assessments_by_reviewer($userid);
  3340. $numofpeers = 0; // number of allocated peer-assessments
  3341. $numofpeerstodo = 0; // number of peer-assessments to do
  3342. $numofself = 0; // number of allocated self-assessments - should be 0 or 1
  3343. $numofselftodo = 0; // number of self-assessments to do - should be 0 or 1
  3344. foreach ($phase->assessments as $a) {
  3345. if ($a->authorid == $userid) {
  3346. $numofself++;
  3347. if (is_null($a->grade)) {
  3348. $numofselftodo++;
  3349. }
  3350. } else {
  3351. $numofpeers++;
  3352. if (is_null($a->grade)) {
  3353. $numofpeerstodo++;
  3354. }
  3355. }
  3356. }
  3357. unset($a);
  3358. if ($numofpeers) {
  3359. $task = new stdclass();
  3360. if ($numofpeerstodo == 0) {
  3361. $task->completed = true;
  3362. } elseif ($workshop->phase > workshop::PHASE_ASSESSMENT) {
  3363. $task->completed = false;
  3364. }
  3365. $a = new stdclass();
  3366. $a->total = $numofpeers;
  3367. $a->todo = $numofpeerstodo;
  3368. $task->title = get_string('taskassesspeers', 'workshop');
  3369. $task->details = get_string('taskassesspeersdetails', 'workshop', $a);
  3370. unset($a);
  3371. $phase->tasks['assesspeers'] = $task;
  3372. }
  3373. if ($workshop->useselfassessment and $numofself) {
  3374. $task = new stdclass();
  3375. if ($numofselftodo == 0) {
  3376. $task->completed = true;
  3377. } elseif ($workshop->phase > workshop::PHASE_ASSESSMENT) {
  3378. $task->completed = false;
  3379. }
  3380. $task->title = get_string('taskassessself', 'workshop');
  3381. $phase->tasks['assessself'] = $task;
  3382. }
  3383. }
  3384. if ($workshop->assessmentstart) {
  3385. $task = new stdclass();
  3386. $task->title = get_string('assessmentstartdatetime', 'workshop', workshop::timestamp_formats($workshop->assessmentstart));
  3387. $task->completed = 'info';
  3388. $phase->tasks['assessmentstartdatetime'] = $task;
  3389. }
  3390. if ($workshop->assessmentend) {
  3391. $task = new stdclass();
  3392. $task->title = get_string('assessmentenddatetime', 'workshop', workshop::timestamp_formats($workshop->assessmentend));
  3393. $task->completed = 'info';
  3394. $phase->tasks['assessmentenddatetime'] = $task;
  3395. }
  3396. if (isset($phase->tasks['assessmentstartdatetime']) or isset($phase->tasks['assessmentenddatetime'])) {
  3397. if (has_capability('mod/workshop:ignoredeadlines', $workshop->context, $userid)) {
  3398. $task = new stdclass();
  3399. $task->title = get_string('deadlinesignored', 'workshop');
  3400. $task->completed = 'info';
  3401. $phase->tasks['deadlinesignored'] = $task;
  3402. }
  3403. }
  3404. $this->phases[workshop::PHASE_ASSESSMENT] = $phase;
  3405. //---------------------------------------------------------
  3406. // setup | submission | assessment | * EVALUATION | closed
  3407. //---------------------------------------------------------
  3408. $phase = new stdclass();
  3409. $phase->title = get_string('phaseevaluation', 'workshop');
  3410. $phase->tasks = array();
  3411. if (has_capability('mod/workshop:overridegrades', $workshop->context)) {
  3412. $expected = $workshop->count_potential_authors(false);
  3413. $calculated = $DB->count_records_select('workshop_submissions',
  3414. 'workshopid = ? AND (grade IS NOT NULL OR gradeover IS NOT NULL)', array($workshop->id));
  3415. $task = new stdclass();
  3416. $task->title = get_string('calculatesubmissiongrades', 'workshop');
  3417. $a = new stdclass();
  3418. $a->expected = $expected;
  3419. $a->calculated = $calculated;
  3420. $task->details = get_string('calculatesubmissiongradesdetails', 'workshop', $a);
  3421. if ($calculated >= $expected) {
  3422. $task->completed = true;
  3423. } elseif ($workshop->phase > workshop::PHASE_EVALUATION) {
  3424. $task->completed = false;
  3425. }
  3426. $phase->tasks['calculatesubmissiongrade'] = $task;
  3427. $expected = $workshop->count_potential_reviewers(false);
  3428. $calculated = $DB->count_records_select('workshop_aggregations',
  3429. 'workshopid = ? AND gradinggrade IS NOT NULL', array($workshop->id));
  3430. $task = new stdclass();
  3431. $task->title = get_string('calculategradinggrades', 'workshop');
  3432. $a = new stdclass();
  3433. $a->expected = $expected;
  3434. $a->calculated = $calculated;
  3435. $task->details = get_string('calculategradinggradesdetails', 'workshop', $a);
  3436. if ($calculated >= $expected) {
  3437. $task->completed = true;
  3438. } elseif ($workshop->phase > workshop::PHASE_EVALUATION) {
  3439. $task->completed = false;
  3440. }
  3441. $phase->tasks['calculategradinggrade'] = $task;
  3442. } elseif ($workshop->phase == workshop::PHASE_EVALUATION) {
  3443. $task = new stdclass();
  3444. $task->title = get_string('evaluategradeswait', 'workshop');
  3445. $task->completed = 'info';
  3446. $phase->tasks['evaluateinfo'] = $task;
  3447. }
  3448. if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) {
  3449. $task = new stdclass();
  3450. $task->title = get_string('taskconclusion', 'workshop');
  3451. $task->link = $workshop->updatemod_url();
  3452. if (trim($workshop->conclusion)) {
  3453. $task->completed = true;
  3454. } elseif ($workshop->phase >= workshop::PHASE_EVALUATION) {
  3455. $task->completed = false;
  3456. }
  3457. $phase->tasks['conclusion'] = $task;
  3458. }
  3459. $this->phases[workshop::PHASE_EVALUATION] = $phase;
  3460. //---------------------------------------------------------
  3461. // setup | submission | assessment | evaluation | * CLOSED
  3462. //---------------------------------------------------------
  3463. $phase = new stdclass();
  3464. $phase->title = get_string('phaseclosed', 'workshop');
  3465. $phase->tasks = array();
  3466. $this->phases[workshop::PHASE_CLOSED] = $phase;
  3467. // Polish data, set default values if not done explicitly
  3468. foreach ($this->phases as $phasecode => $phase) {
  3469. $phase->title = isset($phase->title) ? $phase->title : '';
  3470. $phase->tasks = isset($phase->tasks) ? $phase->tasks : array();
  3471. if ($phasecode == $workshop->phase) {
  3472. $phase->active = true;
  3473. } else {
  3474. $phase->active = false;
  3475. }
  3476. if (!isset($phase->actions)) {
  3477. $phase->actions = array();
  3478. }
  3479. foreach ($phase->tasks as $taskcode => $task) {
  3480. $task->title = isset($task->title) ? $task->title : '';
  3481. $task->link = isset($task->link) ? $task->link : null;
  3482. $task->details = isset($task->details) ? $task->details : '';
  3483. $task->completed = isset($task->completed) ? $task->completed : null;
  3484. }
  3485. }
  3486. // Add phase switching actions.
  3487. if (has_capability('mod/workshop:switchphase', $workshop->context, $userid)) {
  3488. $nextphases = array(
  3489. workshop::PHASE_SETUP => workshop::PHASE_SUBMISSION,
  3490. workshop::PHASE_SUBMISSION => workshop::PHASE_ASSESSMENT,
  3491. workshop::PHASE_ASSESSMENT => workshop::PHASE_EVALUATION,
  3492. workshop::PHASE_EVALUATION => workshop::PHASE_CLOSED,
  3493. );
  3494. foreach ($this->phases as $phasecode => $phase) {
  3495. if ($phase->active) {
  3496. if (isset($nextphases[$workshop->phase])) {
  3497. $task = new stdClass();
  3498. $task->title = get_string('switchphasenext', 'mod_workshop');
  3499. $task->link = $workshop->switchphase_url($nextphases[$workshop->phase]);
  3500. $task->details = '';
  3501. $task->completed = null;
  3502. $phase->tasks['switchtonextphase'] = $task;
  3503. }
  3504. } else {
  3505. $action = new stdclass();
  3506. $action->type = 'switchphase';
  3507. $action->url = $workshop->switchphase_url($phasecode);
  3508. $phase->actions[] = $action;
  3509. }
  3510. }
  3511. }
  3512. }
  3513. /**
  3514. * Returns example submissions to be assessed by the owner of the planner
  3515. *
  3516. * This is here to cache the DB query because the same list is needed later in view.php
  3517. *
  3518. * @see workshop::get_examples_for_reviewer() for the format of returned value
  3519. * @return array
  3520. */
  3521. public function get_examples() {
  3522. if (is_null($this->examples)) {
  3523. $this->examples = $this->workshop->get_examples_for_reviewer($this->userid);
  3524. }
  3525. return $this->examples;
  3526. }
  3527. }
  3528. /**
  3529. * Common base class for submissions and example submissions rendering
  3530. *
  3531. * Subclasses of this class convert raw submission record from
  3532. * workshop_submissions table (as returned by {@see workshop::get_submission_by_id()}
  3533. * for example) into renderable objects.
  3534. */
  3535. abstract class workshop_submission_base {
  3536. /** @var bool is the submission anonymous (i.e. contains author information) */
  3537. protected $anonymous;
  3538. /* @var array of columns from workshop_submissions that are assigned as properties */
  3539. protected $fields = array();
  3540. /** @var workshop */
  3541. protected $workshop;
  3542. /**
  3543. * Copies the properties of the given database record into properties of $this instance
  3544. *
  3545. * @param workshop $workshop
  3546. * @param stdClass $submission full record
  3547. * @param bool $showauthor show the author-related information
  3548. * @param array $options additional properties
  3549. */
  3550. public function __construct(workshop $workshop, stdClass $submission, $showauthor = false) {
  3551. $this->workshop = $workshop;
  3552. foreach ($this->fields as $field) {
  3553. if (!property_exists($submission, $field)) {
  3554. throw new coding_exception('Submission record must provide public property ' . $field);
  3555. }
  3556. if (!property_exists($this, $field)) {
  3557. throw new coding_exception('Renderable component must accept public property ' . $field);
  3558. }
  3559. $this->{$field} = $submission->{$field};
  3560. }
  3561. if ($showauthor) {
  3562. $this->anonymous = false;
  3563. } else {
  3564. $this->anonymize();
  3565. }
  3566. }
  3567. /**
  3568. * Unsets all author-related properties so that the renderer does not have access to them
  3569. *
  3570. * Usually this is called by the contructor but can be called explicitely, too.
  3571. */
  3572. public function anonymize() {
  3573. $authorfields = explode(',', implode(',', \core_user\fields::get_picture_fields()));
  3574. foreach ($authorfields as $field) {
  3575. $prefixedusernamefield = 'author' . $field;
  3576. unset($this->{$prefixedusernamefield});
  3577. }
  3578. $this->anonymous = true;
  3579. }
  3580. /**
  3581. * Does the submission object contain author-related information?
  3582. *
  3583. * @return null|boolean
  3584. */
  3585. public function is_anonymous() {
  3586. return $this->anonymous;
  3587. }
  3588. }
  3589. /**
  3590. * Renderable object containing a basic set of information needed to display the submission summary
  3591. *
  3592. * @see workshop_renderer::render_workshop_submission_summary
  3593. */
  3594. class workshop_submission_summary extends workshop_submission_base implements renderable {
  3595. /** @var int */
  3596. public $id;
  3597. /** @var string */
  3598. public $title;
  3599. /** @var string graded|notgraded */
  3600. public $status;
  3601. /** @var int */
  3602. public $timecreated;
  3603. /** @var int */
  3604. public $timemodified;
  3605. /** @var int */
  3606. public $authorid;
  3607. /** @var string */
  3608. public $authorfirstname;
  3609. /** @var string */
  3610. public $authorlastname;
  3611. /** @var string */
  3612. public $authorfirstnamephonetic;
  3613. /** @var string */
  3614. public $authorlastnamephonetic;
  3615. /** @var string */
  3616. public $authormiddlename;
  3617. /** @var string */
  3618. public $authoralternatename;
  3619. /** @var int */
  3620. public $authorpicture;
  3621. /** @var string */
  3622. public $authorimagealt;
  3623. /** @var string */
  3624. public $authoremail;
  3625. /** @var moodle_url to display submission */
  3626. public $url;
  3627. /**
  3628. * @var array of columns from workshop_submissions that are assigned as properties
  3629. * of instances of this class
  3630. */
  3631. protected $fields = array(
  3632. 'id', 'title', 'timecreated', 'timemodified',
  3633. 'authorid', 'authorfirstname', 'authorlastname', 'authorfirstnamephonetic', 'authorlastnamephonetic',
  3634. 'authormiddlename', 'authoralternatename', 'authorpicture',
  3635. 'authorimagealt', 'authoremail');
  3636. }
  3637. /**
  3638. * Renderable object containing all the information needed to display the submission
  3639. *
  3640. * @see workshop_renderer::render_workshop_submission()
  3641. */
  3642. class workshop_submission extends workshop_submission_summary implements renderable {
  3643. /** @var string */
  3644. public $content;
  3645. /** @var int */
  3646. public $contentformat;
  3647. /** @var bool */
  3648. public $contenttrust;
  3649. /** @var array */
  3650. public $attachment;
  3651. /**
  3652. * @var array of columns from workshop_submissions that are assigned as properties
  3653. * of instances of this class
  3654. */
  3655. protected $fields = array(
  3656. 'id', 'title', 'timecreated', 'timemodified', 'content', 'contentformat', 'contenttrust',
  3657. 'attachment', 'authorid', 'authorfirstname', 'authorlastname', 'authorfirstnamephonetic', 'authorlastnamephonetic',
  3658. 'authormiddlename', 'authoralternatename', 'authorpicture', 'authorimagealt', 'authoremail');
  3659. }
  3660. /**
  3661. * Renderable object containing a basic set of information needed to display the example submission summary
  3662. *
  3663. * @see workshop::prepare_example_summary()
  3664. * @see workshop_renderer::render_workshop_example_submission_summary()
  3665. */
  3666. class workshop_example_submission_summary extends workshop_submission_base implements renderable {
  3667. /** @var int */
  3668. public $id;
  3669. /** @var string */
  3670. public $title;
  3671. /** @var string graded|notgraded */
  3672. public $status;
  3673. /** @var stdClass */
  3674. public $gradeinfo;
  3675. /** @var moodle_url */
  3676. public $url;
  3677. /** @var moodle_url */
  3678. public $editurl;
  3679. /** @var string */
  3680. public $assesslabel;
  3681. /** @var moodle_url */
  3682. public $assessurl;
  3683. /** @var bool must be set explicitly by the caller */
  3684. public $editable = false;
  3685. /**
  3686. * @var array of columns from workshop_submissions that are assigned as properties
  3687. * of instances of this class
  3688. */
  3689. protected $fields = array('id', 'title');
  3690. /**
  3691. * Example submissions are always anonymous
  3692. *
  3693. * @return true
  3694. */
  3695. public function is_anonymous() {
  3696. return true;
  3697. }
  3698. }
  3699. /**
  3700. * Renderable object containing all the information needed to display the example submission
  3701. *
  3702. * @see workshop_renderer::render_workshop_example_submission()
  3703. */
  3704. class workshop_example_submission extends workshop_example_submission_summary implements renderable {
  3705. /** @var string */
  3706. public $content;
  3707. /** @var int */
  3708. public $contentformat;
  3709. /** @var bool */
  3710. public $contenttrust;
  3711. /** @var array */
  3712. public $attachment;
  3713. /**
  3714. * @var array of columns from workshop_submissions that are assigned as properties
  3715. * of instances of this class
  3716. */
  3717. protected $fields = array('id', 'title', 'content', 'contentformat', 'contenttrust', 'attachment');
  3718. }
  3719. /**
  3720. * Common base class for assessments rendering
  3721. *
  3722. * Subclasses of this class convert raw assessment record from
  3723. * workshop_assessments table (as returned by {@see workshop::get_assessment_by_id()}
  3724. * for example) into renderable objects.
  3725. */
  3726. abstract class workshop_assessment_base {
  3727. /** @var string the optional title of the assessment */
  3728. public $title = '';
  3729. /** @var workshop_assessment_form $form as returned by {@link workshop_strategy::get_assessment_form()} */
  3730. public $form;
  3731. /** @var moodle_url */
  3732. public $url;
  3733. /** @var float|null the real received grade */
  3734. public $realgrade = null;
  3735. /** @var float the real maximum grade */
  3736. public $maxgrade;
  3737. /** @var stdClass|null reviewer user info */
  3738. public $reviewer = null;
  3739. /** @var stdClass|null assessed submission's author user info */
  3740. public $author = null;
  3741. /** @var array of actions */
  3742. public $actions = array();
  3743. /* @var array of columns that are assigned as properties */
  3744. protected $fields = array();
  3745. /** @var workshop */
  3746. public $workshop;
  3747. /**
  3748. * Copies the properties of the given database record into properties of $this instance
  3749. *
  3750. * The $options keys are: showreviewer, showauthor
  3751. * @param workshop $workshop
  3752. * @param stdClass $assessment full record
  3753. * @param array $options additional properties
  3754. */
  3755. public function __construct(workshop $workshop, stdClass $record, array $options = array()) {
  3756. $this->workshop = $workshop;
  3757. $this->validate_raw_record($record);
  3758. foreach ($this->fields as $field) {
  3759. if (!property_exists($record, $field)) {
  3760. throw new coding_exception('Assessment record must provide public property ' . $field);
  3761. }
  3762. if (!property_exists($this, $field)) {
  3763. throw new coding_exception('Renderable component must accept public property ' . $field);
  3764. }
  3765. $this->{$field} = $record->{$field};
  3766. }
  3767. if (!empty($options['showreviewer'])) {
  3768. $this->reviewer = user_picture::unalias($record, null, 'revieweridx', 'reviewer');
  3769. }
  3770. if (!empty($options['showauthor'])) {
  3771. $this->author = user_picture::unalias($record, null, 'authorid', 'author');
  3772. }
  3773. }
  3774. /**
  3775. * Adds a new action
  3776. *
  3777. * @param moodle_url $url action URL
  3778. * @param string $label action label
  3779. * @param string $method get|post
  3780. */
  3781. public function add_action(moodle_url $url, $label, $method = 'get') {
  3782. $action = new stdClass();
  3783. $action->url = $url;
  3784. $action->label = $label;
  3785. $action->method = $method;
  3786. $this->actions[] = $action;
  3787. }
  3788. /**
  3789. * Makes sure that we can cook the renderable component from the passed raw database record
  3790. *
  3791. * @param stdClass $assessment full assessment record
  3792. * @throws coding_exception if the caller passed unexpected data
  3793. */
  3794. protected function validate_raw_record(stdClass $record) {
  3795. // nothing to do here
  3796. }
  3797. }
  3798. /**
  3799. * Represents a rendarable full assessment
  3800. */
  3801. class workshop_assessment extends workshop_assessment_base implements renderable {
  3802. /** @var int */
  3803. public $id;
  3804. /** @var int */
  3805. public $submissionid;
  3806. /** @var int */
  3807. public $weight;
  3808. /** @var int */
  3809. public $timecreated;
  3810. /** @var int */
  3811. public $timemodified;
  3812. /** @var float */
  3813. public $grade;
  3814. /** @var float */
  3815. public $gradinggrade;
  3816. /** @var float */
  3817. public $gradinggradeover;
  3818. /** @var string */
  3819. public $feedbackauthor;
  3820. /** @var int */
  3821. public $feedbackauthorformat;
  3822. /** @var int */
  3823. public $feedbackauthorattachment;
  3824. /** @var array */
  3825. protected $fields = array('id', 'submissionid', 'weight', 'timecreated',
  3826. 'timemodified', 'grade', 'gradinggrade', 'gradinggradeover', 'feedbackauthor',
  3827. 'feedbackauthorformat', 'feedbackauthorattachment');
  3828. /**
  3829. * Format the overall feedback text content
  3830. *
  3831. * False is returned if the overall feedback feature is disabled. Null is returned
  3832. * if the overall feedback content has not been found. Otherwise, string with
  3833. * formatted feedback text is returned.
  3834. *
  3835. * @return string|bool|null
  3836. */
  3837. public function get_overall_feedback_content() {
  3838. if ($this->workshop->overallfeedbackmode == 0) {
  3839. return false;
  3840. }
  3841. if (trim($this->feedbackauthor) === '') {
  3842. return null;
  3843. }
  3844. $content = file_rewrite_pluginfile_urls($this->feedbackauthor, 'pluginfile.php', $this->workshop->context->id,
  3845. 'mod_workshop', 'overallfeedback_content', $this->id);
  3846. $content = format_text($content, $this->feedbackauthorformat,
  3847. array('overflowdiv' => true, 'context' => $this->workshop->context));
  3848. return $content;
  3849. }
  3850. /**
  3851. * Prepares the list of overall feedback attachments
  3852. *
  3853. * Returns false if overall feedback attachments are not allowed. Otherwise returns
  3854. * list of attachments (may be empty).
  3855. *
  3856. * @return bool|array of stdClass
  3857. */
  3858. public function get_overall_feedback_attachments() {
  3859. if ($this->workshop->overallfeedbackmode == 0) {
  3860. return false;
  3861. }
  3862. if ($this->workshop->overallfeedbackfiles == 0) {
  3863. return false;
  3864. }
  3865. if (empty($this->feedbackauthorattachment)) {
  3866. return array();
  3867. }
  3868. $attachments = array();
  3869. $fs = get_file_storage();
  3870. $files = $fs->get_area_files($this->workshop->context->id, 'mod_workshop', 'overallfeedback_attachment', $this->id);
  3871. foreach ($files as $file) {
  3872. if ($file->is_directory()) {
  3873. continue;
  3874. }
  3875. $filepath = $file->get_filepath();
  3876. $filename = $file->get_filename();
  3877. $fileurl = moodle_url::make_pluginfile_url($this->workshop->context->id, 'mod_workshop',
  3878. 'overallfeedback_attachment', $this->id, $filepath, $filename, true);
  3879. $previewurl = new moodle_url(moodle_url::make_pluginfile_url($this->workshop->context->id, 'mod_workshop',
  3880. 'overallfeedback_attachment', $this->id, $filepath, $filename, false), array('preview' => 'bigthumb'));
  3881. $attachments[] = (object)array(
  3882. 'filepath' => $filepath,
  3883. 'filename' => $filename,
  3884. 'fileurl' => $fileurl,
  3885. 'previewurl' => $previewurl,
  3886. 'mimetype' => $file->get_mimetype(),
  3887. );
  3888. }
  3889. return $attachments;
  3890. }
  3891. }
  3892. /**
  3893. * Represents a renderable training assessment of an example submission
  3894. */
  3895. class workshop_example_assessment extends workshop_assessment implements renderable {
  3896. /**
  3897. * @see parent::validate_raw_record()
  3898. */
  3899. protected function validate_raw_record(stdClass $record) {
  3900. if ($record->weight != 0) {
  3901. throw new coding_exception('Invalid weight of example submission assessment');
  3902. }
  3903. parent::validate_raw_record($record);
  3904. }
  3905. }
  3906. /**
  3907. * Represents a renderable reference assessment of an example submission
  3908. */
  3909. class workshop_example_reference_assessment extends workshop_assessment implements renderable {
  3910. /**
  3911. * @see parent::validate_raw_record()
  3912. */
  3913. protected function validate_raw_record(stdClass $record) {
  3914. if ($record->weight != 1) {
  3915. throw new coding_exception('Invalid weight of the reference example submission assessment');
  3916. }
  3917. parent::validate_raw_record($record);
  3918. }
  3919. }
  3920. /**
  3921. * Renderable message to be displayed to the user
  3922. *
  3923. * Message can contain an optional action link with a label that is supposed to be rendered
  3924. * as a button or a link.
  3925. *
  3926. * @see workshop::renderer::render_workshop_message()
  3927. */
  3928. class workshop_message implements renderable {
  3929. const TYPE_INFO = 10;
  3930. const TYPE_OK = 20;
  3931. const TYPE_ERROR = 30;
  3932. /** @var string */
  3933. protected $text = '';
  3934. /** @var int */
  3935. protected $type = self::TYPE_INFO;
  3936. /** @var moodle_url */
  3937. protected $actionurl = null;
  3938. /** @var string */
  3939. protected $actionlabel = '';
  3940. /**
  3941. * @param string $text short text to be displayed
  3942. * @param string $type optional message type info|ok|error
  3943. */
  3944. public function __construct($text = null, $type = self::TYPE_INFO) {
  3945. $this->set_text($text);
  3946. $this->set_type($type);
  3947. }
  3948. /**
  3949. * Sets the message text
  3950. *
  3951. * @param string $text short text to be displayed
  3952. */
  3953. public function set_text($text) {
  3954. $this->text = $text;
  3955. }
  3956. /**
  3957. * Sets the message type
  3958. *
  3959. * @param int $type
  3960. */
  3961. public function set_type($type = self::TYPE_INFO) {
  3962. if (in_array($type, array(self::TYPE_OK, self::TYPE_ERROR, self::TYPE_INFO))) {
  3963. $this->type = $type;
  3964. } else {
  3965. throw new coding_exception('Unknown message type.');
  3966. }
  3967. }
  3968. /**
  3969. * Sets the optional message action
  3970. *
  3971. * @param moodle_url $url to follow on action
  3972. * @param string $label action label
  3973. */
  3974. public function set_action(moodle_url $url, $label) {
  3975. $this->actionurl = $url;
  3976. $this->actionlabel = $label;
  3977. }
  3978. /**
  3979. * Returns message text with HTML tags quoted
  3980. *
  3981. * @return string
  3982. */
  3983. public function get_message() {
  3984. return s($this->text);
  3985. }
  3986. /**
  3987. * Returns message type
  3988. *
  3989. * @return int
  3990. */
  3991. public function get_type() {
  3992. return $this->type;
  3993. }
  3994. /**
  3995. * Returns action URL
  3996. *
  3997. * @return moodle_url|null
  3998. */
  3999. public function get_action_url() {
  4000. return $this->actionurl;
  4001. }
  4002. /**
  4003. * Returns action label
  4004. *
  4005. * @return string
  4006. */
  4007. public function get_action_label() {
  4008. return $this->actionlabel;
  4009. }
  4010. }
  4011. /**
  4012. * Renderable component containing all the data needed to display the grading report
  4013. */
  4014. class workshop_grading_report implements renderable {
  4015. /** @var stdClass returned by {@see workshop::prepare_grading_report_data()} */
  4016. protected $data;
  4017. /** @var stdClass rendering options */
  4018. protected $options;
  4019. /**
  4020. * Grades in $data must be already rounded to the set number of decimals or must be null
  4021. * (in which later case, the [mod_workshop,nullgrade] string shall be displayed)
  4022. *
  4023. * @param stdClass $data prepared by {@link workshop::prepare_grading_report_data()}
  4024. * @param stdClass $options display options (showauthornames, showreviewernames, sortby, sorthow, showsubmissiongrade, showgradinggrade)
  4025. */
  4026. public function __construct(stdClass $data, stdClass $options) {
  4027. $this->data = $data;
  4028. $this->options = $options;
  4029. }
  4030. /**
  4031. * @return stdClass grading report data
  4032. */
  4033. public function get_data() {
  4034. return $this->data;
  4035. }
  4036. /**
  4037. * @return stdClass rendering options
  4038. */
  4039. public function get_options() {
  4040. return $this->options;
  4041. }
  4042. /**
  4043. * Prepare the data to be exported to a external system via Web Services.
  4044. *
  4045. * This function applies extra capabilities checks.
  4046. * @return stdClass the data ready for external systems
  4047. */
  4048. public function export_data_for_external() {
  4049. $data = $this->get_data();
  4050. $options = $this->get_options();
  4051. foreach ($data->grades as $reportdata) {
  4052. // If we are in submission phase ignore the following data.
  4053. if ($options->workshopphase == workshop::PHASE_SUBMISSION) {
  4054. unset($reportdata->submissiongrade);
  4055. unset($reportdata->gradinggrade);
  4056. unset($reportdata->submissiongradeover);
  4057. unset($reportdata->submissiongradeoverby);
  4058. unset($reportdata->submissionpublished);
  4059. unset($reportdata->reviewedby);
  4060. unset($reportdata->reviewerof);
  4061. continue;
  4062. }
  4063. if (!$options->showsubmissiongrade) {
  4064. unset($reportdata->submissiongrade);
  4065. unset($reportdata->submissiongradeover);
  4066. }
  4067. if (!$options->showgradinggrade and $tr == 0) {
  4068. unset($reportdata->gradinggrade);
  4069. }
  4070. if (!$options->showreviewernames) {
  4071. foreach ($reportdata->reviewedby as $reviewedby) {
  4072. $reviewedby->userid = 0;
  4073. }
  4074. }
  4075. if (!$options->showauthornames) {
  4076. foreach ($reportdata->reviewerof as $reviewerof) {
  4077. $reviewerof->userid = 0;
  4078. }
  4079. }
  4080. }
  4081. return $data;
  4082. }
  4083. }
  4084. /**
  4085. * Base class for renderable feedback for author and feedback for reviewer
  4086. */
  4087. abstract class workshop_feedback {
  4088. /** @var stdClass the user info */
  4089. protected $provider = null;
  4090. /** @var string the feedback text */
  4091. protected $content = null;
  4092. /** @var int format of the feedback text */
  4093. protected $format = null;
  4094. /**
  4095. * @return stdClass the user info
  4096. */
  4097. public function get_provider() {
  4098. if (is_null($this->provider)) {
  4099. throw new coding_exception('Feedback provider not set');
  4100. }
  4101. return $this->provider;
  4102. }
  4103. /**
  4104. * @return string the feedback text
  4105. */
  4106. public function get_content() {
  4107. if (is_null($this->content)) {
  4108. throw new coding_exception('Feedback content not set');
  4109. }
  4110. return $this->content;
  4111. }
  4112. /**
  4113. * @return int format of the feedback text
  4114. */
  4115. public function get_format() {
  4116. if (is_null($this->format)) {
  4117. throw new coding_exception('Feedback text format not set');
  4118. }
  4119. return $this->format;
  4120. }
  4121. }
  4122. /**
  4123. * Renderable feedback for the author of submission
  4124. */
  4125. class workshop_feedback_author extends workshop_feedback implements renderable {
  4126. /**
  4127. * Extracts feedback from the given submission record
  4128. *
  4129. * @param stdClass $submission record as returned by {@see self::get_submission_by_id()}
  4130. */
  4131. public function __construct(stdClass $submission) {
  4132. $this->provider = user_picture::unalias($submission, null, 'gradeoverbyx', 'gradeoverby');
  4133. $this->content = $submission->feedbackauthor;
  4134. $this->format = $submission->feedbackauthorformat;
  4135. }
  4136. }
  4137. /**
  4138. * Renderable feedback for the reviewer
  4139. */
  4140. class workshop_feedback_reviewer extends workshop_feedback implements renderable {
  4141. /**
  4142. * Extracts feedback from the given assessment record
  4143. *
  4144. * @param stdClass $assessment record as returned by eg {@see self::get_assessment_by_id()}
  4145. */
  4146. public function __construct(stdClass $assessment) {
  4147. $this->provider = user_picture::unalias($assessment, null, 'gradinggradeoverbyx', 'overby');
  4148. $this->content = $assessment->feedbackreviewer;
  4149. $this->format = $assessment->feedbackreviewerformat;
  4150. }
  4151. }
  4152. /**
  4153. * Holds the final grades for the activity as are stored in the gradebook
  4154. */
  4155. class workshop_final_grades implements renderable {
  4156. /** @var object the info from the gradebook about the grade for submission */
  4157. public $submissiongrade = null;
  4158. /** @var object the infor from the gradebook about the grade for assessment */
  4159. public $assessmentgrade = null;
  4160. }