PageRenderTime 58ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 2ms

/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

Large files files are truncated, but you can click here to view the full file

  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)

Large files files are truncated, but you can click here to view the full file