PageRenderTime 77ms CodeModel.GetById 8ms RepoModel.GetById 0ms app.codeStats 1ms

/mod/workshop/lib.php

http://github.com/moodle/moodle
PHP | 2207 lines | 1470 code | 266 blank | 471 comment | 321 complexity | fcd96577e388b96d70c6cb3a7c397e50 MD5 | raw file
Possible License(s): MIT, AGPL-3.0, MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, Apache-2.0, LGPL-2.1, BSD-3-Clause
  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 workshop module functions needed by Moodle core and other subsystems
  18. *
  19. * All the functions neeeded by Moodle core, gradebook, file subsystem etc
  20. * are placed here.
  21. *
  22. * @package mod_workshop
  23. * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
  24. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  25. */
  26. defined('MOODLE_INTERNAL') || die();
  27. require_once($CFG->dirroot . '/calendar/lib.php');
  28. define('WORKSHOP_EVENT_TYPE_SUBMISSION_OPEN', 'opensubmission');
  29. define('WORKSHOP_EVENT_TYPE_SUBMISSION_CLOSE', 'closesubmission');
  30. define('WORKSHOP_EVENT_TYPE_ASSESSMENT_OPEN', 'openassessment');
  31. define('WORKSHOP_EVENT_TYPE_ASSESSMENT_CLOSE', 'closeassessment');
  32. define('WORKSHOP_SUBMISSION_TYPE_DISABLED', 0);
  33. define('WORKSHOP_SUBMISSION_TYPE_AVAILABLE', 1);
  34. define('WORKSHOP_SUBMISSION_TYPE_REQUIRED', 2);
  35. ////////////////////////////////////////////////////////////////////////////////
  36. // Moodle core API //
  37. ////////////////////////////////////////////////////////////////////////////////
  38. /**
  39. * Returns the information if the module supports a feature
  40. *
  41. * @see plugin_supports() in lib/moodlelib.php
  42. * @param string $feature FEATURE_xx constant for requested feature
  43. * @return mixed true if the feature is supported, null if unknown
  44. */
  45. function workshop_supports($feature) {
  46. switch($feature) {
  47. case FEATURE_GRADE_HAS_GRADE: return true;
  48. case FEATURE_GROUPS: return true;
  49. case FEATURE_GROUPINGS: return true;
  50. case FEATURE_MOD_INTRO: return true;
  51. case FEATURE_BACKUP_MOODLE2: return true;
  52. case FEATURE_COMPLETION_TRACKS_VIEWS:
  53. return true;
  54. case FEATURE_SHOW_DESCRIPTION: return true;
  55. case FEATURE_PLAGIARISM: return true;
  56. default: return null;
  57. }
  58. }
  59. /**
  60. * Saves a new instance of the workshop into the database
  61. *
  62. * Given an object containing all the necessary data,
  63. * (defined by the form in mod_form.php) this function
  64. * will save a new instance and return the id number
  65. * of the new instance.
  66. *
  67. * @param stdClass $workshop An object from the form in mod_form.php
  68. * @return int The id of the newly inserted workshop record
  69. */
  70. function workshop_add_instance(stdclass $workshop) {
  71. global $CFG, $DB;
  72. require_once(__DIR__ . '/locallib.php');
  73. $workshop->phase = workshop::PHASE_SETUP;
  74. $workshop->timecreated = time();
  75. $workshop->timemodified = $workshop->timecreated;
  76. $workshop->useexamples = (int)!empty($workshop->useexamples);
  77. $workshop->usepeerassessment = 1;
  78. $workshop->useselfassessment = (int)!empty($workshop->useselfassessment);
  79. $workshop->latesubmissions = (int)!empty($workshop->latesubmissions);
  80. $workshop->phaseswitchassessment = (int)!empty($workshop->phaseswitchassessment);
  81. $workshop->evaluation = 'best';
  82. if (isset($workshop->gradinggradepass)) {
  83. $workshop->gradinggradepass = (float)unformat_float($workshop->gradinggradepass);
  84. }
  85. if (isset($workshop->submissiongradepass)) {
  86. $workshop->submissiongradepass = (float)unformat_float($workshop->submissiongradepass);
  87. }
  88. if (isset($workshop->submissionfiletypes)) {
  89. $filetypesutil = new \core_form\filetypes_util();
  90. $submissionfiletypes = $filetypesutil->normalize_file_types($workshop->submissionfiletypes);
  91. $workshop->submissionfiletypes = implode(' ', $submissionfiletypes);
  92. }
  93. if (isset($workshop->overallfeedbackfiletypes)) {
  94. $filetypesutil = new \core_form\filetypes_util();
  95. $overallfeedbackfiletypes = $filetypesutil->normalize_file_types($workshop->overallfeedbackfiletypes);
  96. $workshop->overallfeedbackfiletypes = implode(' ', $overallfeedbackfiletypes);
  97. }
  98. // insert the new record so we get the id
  99. $workshop->id = $DB->insert_record('workshop', $workshop);
  100. // we need to use context now, so we need to make sure all needed info is already in db
  101. $cmid = $workshop->coursemodule;
  102. $DB->set_field('course_modules', 'instance', $workshop->id, array('id' => $cmid));
  103. $context = context_module::instance($cmid);
  104. // process the custom wysiwyg editors
  105. if ($draftitemid = $workshop->instructauthorseditor['itemid']) {
  106. $workshop->instructauthors = file_save_draft_area_files($draftitemid, $context->id, 'mod_workshop', 'instructauthors',
  107. 0, workshop::instruction_editors_options($context), $workshop->instructauthorseditor['text']);
  108. $workshop->instructauthorsformat = $workshop->instructauthorseditor['format'];
  109. }
  110. if ($draftitemid = $workshop->instructreviewerseditor['itemid']) {
  111. $workshop->instructreviewers = file_save_draft_area_files($draftitemid, $context->id, 'mod_workshop', 'instructreviewers',
  112. 0, workshop::instruction_editors_options($context), $workshop->instructreviewerseditor['text']);
  113. $workshop->instructreviewersformat = $workshop->instructreviewerseditor['format'];
  114. }
  115. if ($draftitemid = $workshop->conclusioneditor['itemid']) {
  116. $workshop->conclusion = file_save_draft_area_files($draftitemid, $context->id, 'mod_workshop', 'conclusion',
  117. 0, workshop::instruction_editors_options($context), $workshop->conclusioneditor['text']);
  118. $workshop->conclusionformat = $workshop->conclusioneditor['format'];
  119. }
  120. // re-save the record with the replaced URLs in editor fields
  121. $DB->update_record('workshop', $workshop);
  122. // create gradebook items
  123. workshop_grade_item_update($workshop);
  124. workshop_grade_item_category_update($workshop);
  125. // create calendar events
  126. workshop_calendar_update($workshop, $workshop->coursemodule);
  127. if (!empty($workshop->completionexpected)) {
  128. \core_completion\api::update_completion_date_event($cmid, 'workshop', $workshop->id, $workshop->completionexpected);
  129. }
  130. return $workshop->id;
  131. }
  132. /**
  133. * Given an object containing all the necessary data,
  134. * (defined by the form in mod_form.php) this function
  135. * will update an existing instance with new data.
  136. *
  137. * @param stdClass $workshop An object from the form in mod_form.php
  138. * @return bool success
  139. */
  140. function workshop_update_instance(stdclass $workshop) {
  141. global $CFG, $DB;
  142. require_once(__DIR__ . '/locallib.php');
  143. $workshop->timemodified = time();
  144. $workshop->id = $workshop->instance;
  145. $workshop->useexamples = (int)!empty($workshop->useexamples);
  146. $workshop->usepeerassessment = 1;
  147. $workshop->useselfassessment = (int)!empty($workshop->useselfassessment);
  148. $workshop->latesubmissions = (int)!empty($workshop->latesubmissions);
  149. $workshop->phaseswitchassessment = (int)!empty($workshop->phaseswitchassessment);
  150. if (isset($workshop->gradinggradepass)) {
  151. $workshop->gradinggradepass = (float)unformat_float($workshop->gradinggradepass);
  152. }
  153. if (isset($workshop->submissiongradepass)) {
  154. $workshop->submissiongradepass = (float)unformat_float($workshop->submissiongradepass);
  155. }
  156. if (isset($workshop->submissionfiletypes)) {
  157. $filetypesutil = new \core_form\filetypes_util();
  158. $submissionfiletypes = $filetypesutil->normalize_file_types($workshop->submissionfiletypes);
  159. $workshop->submissionfiletypes = implode(' ', $submissionfiletypes);
  160. }
  161. if (isset($workshop->overallfeedbackfiletypes)) {
  162. $filetypesutil = new \core_form\filetypes_util();
  163. $overallfeedbackfiletypes = $filetypesutil->normalize_file_types($workshop->overallfeedbackfiletypes);
  164. $workshop->overallfeedbackfiletypes = implode(' ', $overallfeedbackfiletypes);
  165. }
  166. // todo - if the grading strategy is being changed, we may want to replace all aggregated peer grades with nulls
  167. $DB->update_record('workshop', $workshop);
  168. $context = context_module::instance($workshop->coursemodule);
  169. // process the custom wysiwyg editors
  170. if ($draftitemid = $workshop->instructauthorseditor['itemid']) {
  171. $workshop->instructauthors = file_save_draft_area_files($draftitemid, $context->id, 'mod_workshop', 'instructauthors',
  172. 0, workshop::instruction_editors_options($context), $workshop->instructauthorseditor['text']);
  173. $workshop->instructauthorsformat = $workshop->instructauthorseditor['format'];
  174. }
  175. if ($draftitemid = $workshop->instructreviewerseditor['itemid']) {
  176. $workshop->instructreviewers = file_save_draft_area_files($draftitemid, $context->id, 'mod_workshop', 'instructreviewers',
  177. 0, workshop::instruction_editors_options($context), $workshop->instructreviewerseditor['text']);
  178. $workshop->instructreviewersformat = $workshop->instructreviewerseditor['format'];
  179. }
  180. if ($draftitemid = $workshop->conclusioneditor['itemid']) {
  181. $workshop->conclusion = file_save_draft_area_files($draftitemid, $context->id, 'mod_workshop', 'conclusion',
  182. 0, workshop::instruction_editors_options($context), $workshop->conclusioneditor['text']);
  183. $workshop->conclusionformat = $workshop->conclusioneditor['format'];
  184. }
  185. // re-save the record with the replaced URLs in editor fields
  186. $DB->update_record('workshop', $workshop);
  187. // update gradebook items
  188. workshop_grade_item_update($workshop);
  189. workshop_grade_item_category_update($workshop);
  190. // update calendar events
  191. workshop_calendar_update($workshop, $workshop->coursemodule);
  192. $completionexpected = (!empty($workshop->completionexpected)) ? $workshop->completionexpected : null;
  193. \core_completion\api::update_completion_date_event($workshop->coursemodule, 'workshop', $workshop->id, $completionexpected);
  194. return true;
  195. }
  196. /**
  197. * Given an ID of an instance of this module,
  198. * this function will permanently delete the instance
  199. * and any data that depends on it.
  200. *
  201. * @param int $id Id of the module instance
  202. * @return boolean Success/Failure
  203. */
  204. function workshop_delete_instance($id) {
  205. global $CFG, $DB;
  206. require_once($CFG->libdir.'/gradelib.php');
  207. if (! $workshop = $DB->get_record('workshop', array('id' => $id))) {
  208. return false;
  209. }
  210. // delete all associated aggregations
  211. $DB->delete_records('workshop_aggregations', array('workshopid' => $workshop->id));
  212. // get the list of ids of all submissions
  213. $submissions = $DB->get_records('workshop_submissions', array('workshopid' => $workshop->id), '', 'id');
  214. // get the list of all allocated assessments
  215. $assessments = $DB->get_records_list('workshop_assessments', 'submissionid', array_keys($submissions), '', 'id');
  216. // delete the associated records from the workshop core tables
  217. $DB->delete_records_list('workshop_grades', 'assessmentid', array_keys($assessments));
  218. $DB->delete_records_list('workshop_assessments', 'id', array_keys($assessments));
  219. $DB->delete_records_list('workshop_submissions', 'id', array_keys($submissions));
  220. // call the static clean-up methods of all available subplugins
  221. $strategies = core_component::get_plugin_list('workshopform');
  222. foreach ($strategies as $strategy => $path) {
  223. require_once($path.'/lib.php');
  224. $classname = 'workshop_'.$strategy.'_strategy';
  225. call_user_func($classname.'::delete_instance', $workshop->id);
  226. }
  227. $allocators = core_component::get_plugin_list('workshopallocation');
  228. foreach ($allocators as $allocator => $path) {
  229. require_once($path.'/lib.php');
  230. $classname = 'workshop_'.$allocator.'_allocator';
  231. call_user_func($classname.'::delete_instance', $workshop->id);
  232. }
  233. $evaluators = core_component::get_plugin_list('workshopeval');
  234. foreach ($evaluators as $evaluator => $path) {
  235. require_once($path.'/lib.php');
  236. $classname = 'workshop_'.$evaluator.'_evaluation';
  237. call_user_func($classname.'::delete_instance', $workshop->id);
  238. }
  239. // delete the calendar events
  240. $events = $DB->get_records('event', array('modulename' => 'workshop', 'instance' => $workshop->id));
  241. foreach ($events as $event) {
  242. $event = calendar_event::load($event);
  243. $event->delete();
  244. }
  245. // gradebook cleanup
  246. grade_update('mod/workshop', $workshop->course, 'mod', 'workshop', $workshop->id, 0, null, array('deleted' => true));
  247. grade_update('mod/workshop', $workshop->course, 'mod', 'workshop', $workshop->id, 1, null, array('deleted' => true));
  248. // finally remove the workshop record itself
  249. // We must delete the module record after we delete the grade item.
  250. $DB->delete_records('workshop', array('id' => $workshop->id));
  251. return true;
  252. }
  253. /**
  254. * This standard function will check all instances of this module
  255. * and make sure there are up-to-date events created for each of them.
  256. * If courseid = 0, then every workshop event in the site is checked, else
  257. * only workshop events belonging to the course specified are checked.
  258. *
  259. * @param integer $courseid The Course ID.
  260. * @param int|stdClass $instance workshop module instance or ID.
  261. * @param int|stdClass $cm Course module object or ID.
  262. * @return bool Returns true if the calendar events were successfully updated.
  263. */
  264. function workshop_refresh_events($courseid = 0, $instance = null, $cm = null) {
  265. global $DB;
  266. // If we have instance information then we can just update the one event instead of updating all events.
  267. if (isset($instance)) {
  268. if (!is_object($instance)) {
  269. $instance = $DB->get_record('workshop', array('id' => $instance), '*', MUST_EXIST);
  270. }
  271. if (isset($cm)) {
  272. if (!is_object($cm)) {
  273. $cm = (object)array('id' => $cm);
  274. }
  275. } else {
  276. $cm = get_coursemodule_from_instance('workshop', $instance->id);
  277. }
  278. workshop_calendar_update($instance, $cm->id);
  279. return true;
  280. }
  281. if ($courseid) {
  282. // Make sure that the course id is numeric.
  283. if (!is_numeric($courseid)) {
  284. return false;
  285. }
  286. if (!$workshops = $DB->get_records('workshop', array('course' => $courseid))) {
  287. return false;
  288. }
  289. } else {
  290. if (!$workshops = $DB->get_records('workshop')) {
  291. return false;
  292. }
  293. }
  294. foreach ($workshops as $workshop) {
  295. if (!$cm = get_coursemodule_from_instance('workshop', $workshop->id, $courseid, false)) {
  296. continue;
  297. }
  298. workshop_calendar_update($workshop, $cm->id);
  299. }
  300. return true;
  301. }
  302. /**
  303. * List the actions that correspond to a view of this module.
  304. * This is used by the participation report.
  305. *
  306. * Note: This is not used by new logging system. Event with
  307. * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
  308. * be considered as view action.
  309. *
  310. * @return array
  311. */
  312. function workshop_get_view_actions() {
  313. return array('view', 'view all', 'view submission', 'view example');
  314. }
  315. /**
  316. * List the actions that correspond to a post of this module.
  317. * This is used by the participation report.
  318. *
  319. * Note: This is not used by new logging system. Event with
  320. * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
  321. * will be considered as post action.
  322. *
  323. * @return array
  324. */
  325. function workshop_get_post_actions() {
  326. return array('add', 'add assessment', 'add example', 'add submission',
  327. 'update', 'update assessment', 'update example', 'update submission');
  328. }
  329. /**
  330. * Return a small object with summary information about what a
  331. * user has done with a given particular instance of this module
  332. * Used for user activity reports.
  333. * $return->time = the time they did it
  334. * $return->info = a short text description
  335. *
  336. * @param stdClass $course The course record.
  337. * @param stdClass $user The user record.
  338. * @param cm_info|stdClass $mod The course module info object or record.
  339. * @param stdClass $workshop The workshop instance record.
  340. * @return stdclass|null
  341. */
  342. function workshop_user_outline($course, $user, $mod, $workshop) {
  343. global $CFG, $DB;
  344. require_once($CFG->libdir.'/gradelib.php');
  345. $grades = grade_get_grades($course->id, 'mod', 'workshop', $workshop->id, $user->id);
  346. $submissiongrade = null;
  347. $assessmentgrade = null;
  348. $info = '';
  349. $time = 0;
  350. if (!empty($grades->items[0]->grades)) {
  351. $submissiongrade = reset($grades->items[0]->grades);
  352. $time = max($time, $submissiongrade->dategraded);
  353. if (!$submissiongrade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
  354. $info .= get_string('submissiongrade', 'workshop') . ': ' . $submissiongrade->str_long_grade
  355. . html_writer::empty_tag('br');
  356. } else {
  357. $info .= get_string('submissiongrade', 'workshop') . ': ' . get_string('hidden', 'grades')
  358. . html_writer::empty_tag('br');
  359. }
  360. }
  361. if (!empty($grades->items[1]->grades)) {
  362. $assessmentgrade = reset($grades->items[1]->grades);
  363. $time = max($time, $assessmentgrade->dategraded);
  364. if (!$assessmentgrade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
  365. $info .= get_string('gradinggrade', 'workshop') . ': ' . $assessmentgrade->str_long_grade;
  366. } else {
  367. $info .= get_string('gradinggrade', 'workshop') . ': ' . get_string('hidden', 'grades');
  368. }
  369. }
  370. if (!empty($info) and !empty($time)) {
  371. $return = new stdclass();
  372. $return->time = $time;
  373. $return->info = $info;
  374. return $return;
  375. }
  376. return null;
  377. }
  378. /**
  379. * Print a detailed representation of what a user has done with
  380. * a given particular instance of this module, for user activity reports.
  381. *
  382. * @param stdClass $course The course record.
  383. * @param stdClass $user The user record.
  384. * @param cm_info|stdClass $mod The course module info object or record.
  385. * @param stdClass $workshop The workshop instance record.
  386. * @return string HTML
  387. */
  388. function workshop_user_complete($course, $user, $mod, $workshop) {
  389. global $CFG, $DB, $OUTPUT;
  390. require_once(__DIR__.'/locallib.php');
  391. require_once($CFG->libdir.'/gradelib.php');
  392. $workshop = new workshop($workshop, $mod, $course);
  393. $grades = grade_get_grades($course->id, 'mod', 'workshop', $workshop->id, $user->id);
  394. if (!empty($grades->items[0]->grades)) {
  395. $submissiongrade = reset($grades->items[0]->grades);
  396. if (!$submissiongrade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
  397. $info = get_string('submissiongrade', 'workshop') . ': ' . $submissiongrade->str_long_grade;
  398. } else {
  399. $info = get_string('submissiongrade', 'workshop') . ': ' . get_string('hidden', 'grades');
  400. }
  401. echo html_writer::tag('li', $info, array('class'=>'submissiongrade'));
  402. }
  403. if (!empty($grades->items[1]->grades)) {
  404. $assessmentgrade = reset($grades->items[1]->grades);
  405. if (!$assessmentgrade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
  406. $info = get_string('gradinggrade', 'workshop') . ': ' . $assessmentgrade->str_long_grade;
  407. } else {
  408. $info = get_string('gradinggrade', 'workshop') . ': ' . get_string('hidden', 'grades');
  409. }
  410. echo html_writer::tag('li', $info, array('class'=>'gradinggrade'));
  411. }
  412. if (has_capability('mod/workshop:viewallsubmissions', $workshop->context)) {
  413. $canviewsubmission = true;
  414. if (groups_get_activity_groupmode($workshop->cm) == SEPARATEGROUPS) {
  415. // user must have accessallgroups or share at least one group with the submission author
  416. if (!has_capability('moodle/site:accessallgroups', $workshop->context)) {
  417. $usersgroups = groups_get_activity_allowed_groups($workshop->cm);
  418. $authorsgroups = groups_get_all_groups($workshop->course->id, $user->id, $workshop->cm->groupingid, 'g.id');
  419. $sharedgroups = array_intersect_key($usersgroups, $authorsgroups);
  420. if (empty($sharedgroups)) {
  421. $canviewsubmission = false;
  422. }
  423. }
  424. }
  425. if ($canviewsubmission and $submission = $workshop->get_submission_by_author($user->id)) {
  426. $title = format_string($submission->title);
  427. $url = $workshop->submission_url($submission->id);
  428. $link = html_writer::link($url, $title);
  429. $info = get_string('submission', 'workshop').': '.$link;
  430. echo html_writer::tag('li', $info, array('class'=>'submission'));
  431. }
  432. }
  433. if (has_capability('mod/workshop:viewallassessments', $workshop->context)) {
  434. if ($assessments = $workshop->get_assessments_by_reviewer($user->id)) {
  435. foreach ($assessments as $assessment) {
  436. $a = new stdclass();
  437. $a->submissionurl = $workshop->submission_url($assessment->submissionid)->out();
  438. $a->assessmenturl = $workshop->assess_url($assessment->id)->out();
  439. $a->submissiontitle = s($assessment->submissiontitle);
  440. echo html_writer::tag('li', get_string('assessmentofsubmission', 'workshop', $a));
  441. }
  442. }
  443. }
  444. }
  445. /**
  446. * Given a course and a time, this module should find recent activity
  447. * that has occurred in workshop activities and print it out.
  448. * Return true if there was output, or false is there was none.
  449. *
  450. * @param stdClass $course
  451. * @param bool $viewfullnames
  452. * @param int $timestart
  453. * @return boolean
  454. */
  455. function workshop_print_recent_activity($course, $viewfullnames, $timestart) {
  456. global $CFG, $USER, $DB, $OUTPUT;
  457. $authoramefields = get_all_user_name_fields(true, 'author', null, 'author');
  458. $reviewerfields = get_all_user_name_fields(true, 'reviewer', null, 'reviewer');
  459. $sql = "SELECT s.id AS submissionid, s.title AS submissiontitle, s.timemodified AS submissionmodified,
  460. author.id AS authorid, $authoramefields, a.id AS assessmentid, a.timemodified AS assessmentmodified,
  461. reviewer.id AS reviewerid, $reviewerfields, cm.id AS cmid
  462. FROM {workshop} w
  463. INNER JOIN {course_modules} cm ON cm.instance = w.id
  464. INNER JOIN {modules} md ON md.id = cm.module
  465. INNER JOIN {workshop_submissions} s ON s.workshopid = w.id
  466. INNER JOIN {user} author ON s.authorid = author.id
  467. LEFT JOIN {workshop_assessments} a ON a.submissionid = s.id
  468. LEFT JOIN {user} reviewer ON a.reviewerid = reviewer.id
  469. WHERE cm.course = ?
  470. AND md.name = 'workshop'
  471. AND s.example = 0
  472. AND (s.timemodified > ? OR a.timemodified > ?)
  473. ORDER BY s.timemodified";
  474. $rs = $DB->get_recordset_sql($sql, array($course->id, $timestart, $timestart));
  475. $modinfo = get_fast_modinfo($course); // reference needed because we might load the groups
  476. $submissions = array(); // recent submissions indexed by submission id
  477. $assessments = array(); // recent assessments indexed by assessment id
  478. $users = array();
  479. foreach ($rs as $activity) {
  480. if (!array_key_exists($activity->cmid, $modinfo->cms)) {
  481. // this should not happen but just in case
  482. continue;
  483. }
  484. $cm = $modinfo->cms[$activity->cmid];
  485. if (!$cm->uservisible) {
  486. continue;
  487. }
  488. // remember all user names we can use later
  489. if (empty($users[$activity->authorid])) {
  490. $u = new stdclass();
  491. $users[$activity->authorid] = username_load_fields_from_object($u, $activity, 'author');
  492. }
  493. if ($activity->reviewerid and empty($users[$activity->reviewerid])) {
  494. $u = new stdclass();
  495. $users[$activity->reviewerid] = username_load_fields_from_object($u, $activity, 'reviewer');
  496. }
  497. $context = context_module::instance($cm->id);
  498. $groupmode = groups_get_activity_groupmode($cm, $course);
  499. if ($activity->submissionmodified > $timestart and empty($submissions[$activity->submissionid])) {
  500. $s = new stdclass();
  501. $s->title = $activity->submissiontitle;
  502. $s->authorid = $activity->authorid;
  503. $s->timemodified = $activity->submissionmodified;
  504. $s->cmid = $activity->cmid;
  505. if ($activity->authorid == $USER->id || has_capability('mod/workshop:viewauthornames', $context)) {
  506. $s->authornamevisible = true;
  507. } else {
  508. $s->authornamevisible = false;
  509. }
  510. // the following do-while wrapper allows to break from deeply nested if-statements
  511. do {
  512. if ($s->authorid === $USER->id) {
  513. // own submissions always visible
  514. $submissions[$activity->submissionid] = $s;
  515. break;
  516. }
  517. if (has_capability('mod/workshop:viewallsubmissions', $context)) {
  518. if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
  519. if (isguestuser()) {
  520. // shortcut - guest user does not belong into any group
  521. break;
  522. }
  523. // this might be slow - show only submissions by users who share group with me in this cm
  524. if (!$modinfo->get_groups($cm->groupingid)) {
  525. break;
  526. }
  527. $authorsgroups = groups_get_all_groups($course->id, $s->authorid, $cm->groupingid);
  528. if (is_array($authorsgroups)) {
  529. $authorsgroups = array_keys($authorsgroups);
  530. $intersect = array_intersect($authorsgroups, $modinfo->get_groups($cm->groupingid));
  531. if (empty($intersect)) {
  532. break;
  533. } else {
  534. // can see all submissions and shares a group with the author
  535. $submissions[$activity->submissionid] = $s;
  536. break;
  537. }
  538. }
  539. } else {
  540. // can see all submissions from all groups
  541. $submissions[$activity->submissionid] = $s;
  542. }
  543. }
  544. } while (0);
  545. }
  546. if ($activity->assessmentmodified > $timestart and empty($assessments[$activity->assessmentid])) {
  547. $a = new stdclass();
  548. $a->submissionid = $activity->submissionid;
  549. $a->submissiontitle = $activity->submissiontitle;
  550. $a->reviewerid = $activity->reviewerid;
  551. $a->timemodified = $activity->assessmentmodified;
  552. $a->cmid = $activity->cmid;
  553. if ($activity->reviewerid == $USER->id || has_capability('mod/workshop:viewreviewernames', $context)) {
  554. $a->reviewernamevisible = true;
  555. } else {
  556. $a->reviewernamevisible = false;
  557. }
  558. // the following do-while wrapper allows to break from deeply nested if-statements
  559. do {
  560. if ($a->reviewerid === $USER->id) {
  561. // own assessments always visible
  562. $assessments[$activity->assessmentid] = $a;
  563. break;
  564. }
  565. if (has_capability('mod/workshop:viewallassessments', $context)) {
  566. if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
  567. if (isguestuser()) {
  568. // shortcut - guest user does not belong into any group
  569. break;
  570. }
  571. // this might be slow - show only submissions by users who share group with me in this cm
  572. if (!$modinfo->get_groups($cm->groupingid)) {
  573. break;
  574. }
  575. $reviewersgroups = groups_get_all_groups($course->id, $a->reviewerid, $cm->groupingid);
  576. if (is_array($reviewersgroups)) {
  577. $reviewersgroups = array_keys($reviewersgroups);
  578. $intersect = array_intersect($reviewersgroups, $modinfo->get_groups($cm->groupingid));
  579. if (empty($intersect)) {
  580. break;
  581. } else {
  582. // can see all assessments and shares a group with the reviewer
  583. $assessments[$activity->assessmentid] = $a;
  584. break;
  585. }
  586. }
  587. } else {
  588. // can see all assessments from all groups
  589. $assessments[$activity->assessmentid] = $a;
  590. }
  591. }
  592. } while (0);
  593. }
  594. }
  595. $rs->close();
  596. $shown = false;
  597. if (!empty($submissions)) {
  598. $shown = true;
  599. echo $OUTPUT->heading(get_string('recentsubmissions', 'workshop') . ':', 6);
  600. foreach ($submissions as $id => $submission) {
  601. $link = new moodle_url('/mod/workshop/submission.php', array('id'=>$id, 'cmid'=>$submission->cmid));
  602. if ($submission->authornamevisible) {
  603. $author = $users[$submission->authorid];
  604. } else {
  605. $author = null;
  606. }
  607. print_recent_activity_note($submission->timemodified, $author, $submission->title, $link->out(), false, $viewfullnames);
  608. }
  609. }
  610. if (!empty($assessments)) {
  611. $shown = true;
  612. echo $OUTPUT->heading(get_string('recentassessments', 'workshop') . ':', 6);
  613. core_collator::asort_objects_by_property($assessments, 'timemodified');
  614. foreach ($assessments as $id => $assessment) {
  615. $link = new moodle_url('/mod/workshop/assessment.php', array('asid' => $id));
  616. if ($assessment->reviewernamevisible) {
  617. $reviewer = $users[$assessment->reviewerid];
  618. } else {
  619. $reviewer = null;
  620. }
  621. print_recent_activity_note($assessment->timemodified, $reviewer, $assessment->submissiontitle, $link->out(), false, $viewfullnames);
  622. }
  623. }
  624. if ($shown) {
  625. return true;
  626. }
  627. return false;
  628. }
  629. /**
  630. * Returns all activity in course workshops since a given time
  631. *
  632. * @param array $activities sequentially indexed array of objects
  633. * @param int $index
  634. * @param int $timestart
  635. * @param int $courseid
  636. * @param int $cmid
  637. * @param int $userid defaults to 0
  638. * @param int $groupid defaults to 0
  639. * @return void adds items into $activities and increases $index
  640. */
  641. function workshop_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0) {
  642. global $CFG, $COURSE, $USER, $DB;
  643. if ($COURSE->id == $courseid) {
  644. $course = $COURSE;
  645. } else {
  646. $course = $DB->get_record('course', array('id'=>$courseid));
  647. }
  648. $modinfo = get_fast_modinfo($course);
  649. $cm = $modinfo->cms[$cmid];
  650. $params = array();
  651. if ($userid) {
  652. $userselect = "AND (author.id = :authorid OR reviewer.id = :reviewerid)";
  653. $params['authorid'] = $userid;
  654. $params['reviewerid'] = $userid;
  655. } else {
  656. $userselect = "";
  657. }
  658. if ($groupid) {
  659. $groupselect = "AND (authorgroupmembership.groupid = :authorgroupid OR reviewergroupmembership.groupid = :reviewergroupid)";
  660. $groupjoin = "LEFT JOIN {groups_members} authorgroupmembership ON authorgroupmembership.userid = author.id
  661. LEFT JOIN {groups_members} reviewergroupmembership ON reviewergroupmembership.userid = reviewer.id";
  662. $params['authorgroupid'] = $groupid;
  663. $params['reviewergroupid'] = $groupid;
  664. } else {
  665. $groupselect = "";
  666. $groupjoin = "";
  667. }
  668. $params['cminstance'] = $cm->instance;
  669. $params['submissionmodified'] = $timestart;
  670. $params['assessmentmodified'] = $timestart;
  671. $authornamefields = get_all_user_name_fields(true, 'author', null, 'author');
  672. $reviewerfields = get_all_user_name_fields(true, 'reviewer', null, 'reviewer');
  673. $sql = "SELECT s.id AS submissionid, s.title AS submissiontitle, s.timemodified AS submissionmodified,
  674. author.id AS authorid, $authornamefields, author.picture AS authorpicture, author.imagealt AS authorimagealt,
  675. author.email AS authoremail, a.id AS assessmentid, a.timemodified AS assessmentmodified,
  676. reviewer.id AS reviewerid, $reviewerfields, reviewer.picture AS reviewerpicture,
  677. reviewer.imagealt AS reviewerimagealt, reviewer.email AS revieweremail
  678. FROM {workshop_submissions} s
  679. INNER JOIN {workshop} w ON s.workshopid = w.id
  680. INNER JOIN {user} author ON s.authorid = author.id
  681. LEFT JOIN {workshop_assessments} a ON a.submissionid = s.id
  682. LEFT JOIN {user} reviewer ON a.reviewerid = reviewer.id
  683. $groupjoin
  684. WHERE w.id = :cminstance
  685. AND s.example = 0
  686. $userselect $groupselect
  687. AND (s.timemodified > :submissionmodified OR a.timemodified > :assessmentmodified)
  688. ORDER BY s.timemodified ASC, a.timemodified ASC";
  689. $rs = $DB->get_recordset_sql($sql, $params);
  690. $groupmode = groups_get_activity_groupmode($cm, $course);
  691. $context = context_module::instance($cm->id);
  692. $grader = has_capability('moodle/grade:viewall', $context);
  693. $accessallgroups = has_capability('moodle/site:accessallgroups', $context);
  694. $viewauthors = has_capability('mod/workshop:viewauthornames', $context);
  695. $viewreviewers = has_capability('mod/workshop:viewreviewernames', $context);
  696. $submissions = array(); // recent submissions indexed by submission id
  697. $assessments = array(); // recent assessments indexed by assessment id
  698. $users = array();
  699. foreach ($rs as $activity) {
  700. // remember all user names we can use later
  701. if (empty($users[$activity->authorid])) {
  702. $u = new stdclass();
  703. $additionalfields = explode(',', user_picture::fields());
  704. $u = username_load_fields_from_object($u, $activity, 'author', $additionalfields);
  705. $users[$activity->authorid] = $u;
  706. }
  707. if ($activity->reviewerid and empty($users[$activity->reviewerid])) {
  708. $u = new stdclass();
  709. $additionalfields = explode(',', user_picture::fields());
  710. $u = username_load_fields_from_object($u, $activity, 'reviewer', $additionalfields);
  711. $users[$activity->reviewerid] = $u;
  712. }
  713. if ($activity->submissionmodified > $timestart and empty($submissions[$activity->submissionid])) {
  714. $s = new stdclass();
  715. $s->id = $activity->submissionid;
  716. $s->title = $activity->submissiontitle;
  717. $s->authorid = $activity->authorid;
  718. $s->timemodified = $activity->submissionmodified;
  719. if ($activity->authorid == $USER->id || has_capability('mod/workshop:viewauthornames', $context)) {
  720. $s->authornamevisible = true;
  721. } else {
  722. $s->authornamevisible = false;
  723. }
  724. // the following do-while wrapper allows to break from deeply nested if-statements
  725. do {
  726. if ($s->authorid === $USER->id) {
  727. // own submissions always visible
  728. $submissions[$activity->submissionid] = $s;
  729. break;
  730. }
  731. if (has_capability('mod/workshop:viewallsubmissions', $context)) {
  732. if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
  733. if (isguestuser()) {
  734. // shortcut - guest user does not belong into any group
  735. break;
  736. }
  737. // this might be slow - show only submissions by users who share group with me in this cm
  738. if (!$modinfo->get_groups($cm->groupingid)) {
  739. break;
  740. }
  741. $authorsgroups = groups_get_all_groups($course->id, $s->authorid, $cm->groupingid);
  742. if (is_array($authorsgroups)) {
  743. $authorsgroups = array_keys($authorsgroups);
  744. $intersect = array_intersect($authorsgroups, $modinfo->get_groups($cm->groupingid));
  745. if (empty($intersect)) {
  746. break;
  747. } else {
  748. // can see all submissions and shares a group with the author
  749. $submissions[$activity->submissionid] = $s;
  750. break;
  751. }
  752. }
  753. } else {
  754. // can see all submissions from all groups
  755. $submissions[$activity->submissionid] = $s;
  756. }
  757. }
  758. } while (0);
  759. }
  760. if ($activity->assessmentmodified > $timestart and empty($assessments[$activity->assessmentid])) {
  761. $a = new stdclass();
  762. $a->id = $activity->assessmentid;
  763. $a->submissionid = $activity->submissionid;
  764. $a->submissiontitle = $activity->submissiontitle;
  765. $a->reviewerid = $activity->reviewerid;
  766. $a->timemodified = $activity->assessmentmodified;
  767. if ($activity->reviewerid == $USER->id || has_capability('mod/workshop:viewreviewernames', $context)) {
  768. $a->reviewernamevisible = true;
  769. } else {
  770. $a->reviewernamevisible = false;
  771. }
  772. // the following do-while wrapper allows to break from deeply nested if-statements
  773. do {
  774. if ($a->reviewerid === $USER->id) {
  775. // own assessments always visible
  776. $assessments[$activity->assessmentid] = $a;
  777. break;
  778. }
  779. if (has_capability('mod/workshop:viewallassessments', $context)) {
  780. if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
  781. if (isguestuser()) {
  782. // shortcut - guest user does not belong into any group
  783. break;
  784. }
  785. // this might be slow - show only submissions by users who share group with me in this cm
  786. if (!$modinfo->get_groups($cm->groupingid)) {
  787. break;
  788. }
  789. $reviewersgroups = groups_get_all_groups($course->id, $a->reviewerid, $cm->groupingid);
  790. if (is_array($reviewersgroups)) {
  791. $reviewersgroups = array_keys($reviewersgroups);
  792. $intersect = array_intersect($reviewersgroups, $modinfo->get_groups($cm->groupingid));
  793. if (empty($intersect)) {
  794. break;
  795. } else {
  796. // can see all assessments and shares a group with the reviewer
  797. $assessments[$activity->assessmentid] = $a;
  798. break;
  799. }
  800. }
  801. } else {
  802. // can see all assessments from all groups
  803. $assessments[$activity->assessmentid] = $a;
  804. }
  805. }
  806. } while (0);
  807. }
  808. }
  809. $rs->close();
  810. $workshopname = format_string($cm->name, true);
  811. if ($grader) {
  812. require_once($CFG->libdir.'/gradelib.php');
  813. $grades = grade_get_grades($courseid, 'mod', 'workshop', $cm->instance, array_keys($users));
  814. }
  815. foreach ($submissions as $submission) {
  816. $tmpactivity = new stdclass();
  817. $tmpactivity->type = 'workshop';
  818. $tmpactivity->cmid = $cm->id;
  819. $tmpactivity->name = $workshopname;
  820. $tmpactivity->sectionnum = $cm->sectionnum;
  821. $tmpactivity->timestamp = $submission->timemodified;
  822. $tmpactivity->subtype = 'submission';
  823. $tmpactivity->content = $submission;
  824. if ($grader) {
  825. $tmpactivity->grade = $grades->items[0]->grades[$submission->authorid]->str_long_grade;
  826. }
  827. if ($submission->authornamevisible and !empty($users[$submission->authorid])) {
  828. $tmpactivity->user = $users[$submission->authorid];
  829. }
  830. $activities[$index++] = $tmpactivity;
  831. }
  832. foreach ($assessments as $assessment) {
  833. $tmpactivity = new stdclass();
  834. $tmpactivity->type = 'workshop';
  835. $tmpactivity->cmid = $cm->id;
  836. $tmpactivity->name = $workshopname;
  837. $tmpactivity->sectionnum = $cm->sectionnum;
  838. $tmpactivity->timestamp = $assessment->timemodified;
  839. $tmpactivity->subtype = 'assessment';
  840. $tmpactivity->content = $assessment;
  841. if ($grader) {
  842. $tmpactivity->grade = $grades->items[1]->grades[$assessment->reviewerid]->str_long_grade;
  843. }
  844. if ($assessment->reviewernamevisible and !empty($users[$assessment->reviewerid])) {
  845. $tmpactivity->user = $users[$assessment->reviewerid];
  846. }
  847. $activities[$index++] = $tmpactivity;
  848. }
  849. }
  850. /**
  851. * Print single activity item prepared by {@see workshop_get_recent_mod_activity()}
  852. */
  853. function workshop_print_recent_mod_activity($activity, $courseid, $detail, $modnames, $viewfullnames) {
  854. global $CFG, $OUTPUT;
  855. if (!empty($activity->user)) {
  856. echo html_writer::tag('div', $OUTPUT->user_picture($activity->user, array('courseid'=>$courseid)),
  857. array('style' => 'float: left; padding: 7px;'));
  858. }
  859. if ($activity->subtype == 'submission') {
  860. echo html_writer::start_tag('div', array('class'=>'submission', 'style'=>'padding: 7px; float:left;'));
  861. if ($detail) {
  862. echo html_writer::start_tag('h4', array('class'=>'workshop'));
  863. $url = new moodle_url('/mod/workshop/view.php', array('id'=>$activity->cmid));
  864. $name = s($activity->name);
  865. echo $OUTPUT->image_icon('icon', $name, $activity->type);
  866. echo ' ' . $modnames[$activity->type];
  867. echo html_writer::link($url, $name, array('class'=>'name', 'style'=>'margin-left: 5px'));
  868. echo html_writer::end_tag('h4');
  869. }
  870. echo html_writer::start_tag('div', array('class'=>'title'));
  871. $url = new moodle_url('/mod/workshop/submission.php', array('cmid'=>$activity->cmid, 'id'=>$activity->content->id));
  872. $name = s($activity->content->title);
  873. echo html_writer::tag('strong', html_writer::link($url, $name));
  874. echo html_writer::end_tag('div');
  875. if (!empty($activity->user)) {
  876. echo html_writer::start_tag('div', array('class'=>'user'));
  877. $url = new moodle_url('/user/view.php', array('id'=>$activity->user->id, 'course'=>$courseid));
  878. $name = fullname($activity->user);
  879. $link = html_writer::link($url, $name);
  880. echo get_string('submissionby', 'workshop', $link);
  881. echo ' - '.userdate($activity->timestamp);
  882. echo html_writer::end_tag('div');
  883. } else {
  884. echo html_writer::start_tag('div', array('class'=>'anonymous'));
  885. echo get_string('submission', 'workshop');
  886. echo ' - '.userdate($activity->timestamp);
  887. echo html_writer::end_tag('div');
  888. }
  889. echo html_writer::end_tag('div');
  890. }
  891. if ($activity->subtype == 'assessment') {
  892. echo html_writer::start_tag('div', array('class'=>'assessment', 'style'=>'padding: 7px; float:left;'));
  893. if ($detail) {
  894. echo html_writer::start_tag('h4', array('class'=>'workshop'));
  895. $url = new moodle_url('/mod/workshop/view.php', array('id'=>$activity->cmid));
  896. $name = s($activity->name);
  897. echo $OUTPUT->image_icon('icon', $name, $activity->type);
  898. echo ' ' . $modnames[$activity->type];
  899. echo html_writer::link($url, $name, array('class'=>'name', 'style'=>'margin-left: 5px'));
  900. echo html_writer::end_tag('h4');
  901. }
  902. echo html_writer::start_tag('div', array('class'=>'title'));
  903. $url = new moodle_url('/mod/workshop/assessment.php', array('asid'=>$activity->content->id));
  904. $name = s($activity->content->submissiontitle);
  905. echo html_writer::tag('em', html_writer::link($url, $name));
  906. echo html_writer::end_tag('div');
  907. if (!empty($activity->user)) {
  908. echo html_writer::start_tag('div', array('class'=>'user'));
  909. $url = new moodle_url('/user/view.php', array('id'=>$activity->user->id, 'course'=>$courseid));
  910. $name = fullname($activity->user);
  911. $link = html_writer::link($url, $name);
  912. echo get_string('assessmentbyfullname', 'workshop', $link);
  913. echo ' - '.userdate($activity->timestamp);
  914. echo html_writer::end_tag('div');
  915. } else {
  916. echo html_writer::start_tag('div', array('class'=>'anonymous'));
  917. echo get_string('assessment', 'workshop');
  918. echo ' - '.userdate($activity->timestamp);
  919. echo html_writer::end_tag('div');
  920. }
  921. echo html_writer::end_tag('div');
  922. }
  923. echo html_writer::empty_tag('br', array('style'=>'clear:both'));
  924. }
  925. /**
  926. * @deprecated since Moodle 3.8
  927. */
  928. function workshop_scale_used() {
  929. throw new coding_exception('workshop_scale_used() can not be used anymore. Plugins can implement ' .
  930. '<modname>_scale_used_anywhere, all implementations of <modname>_scale_used are now ignored');
  931. }
  932. /**
  933. * Is a given scale used by any instance of workshop?
  934. *
  935. * The function asks all installed grading strategy subplugins. The workshop
  936. * core itself does not use scales. Both grade for submission and grade for
  937. * assessments do not use scales.
  938. *
  939. * @param int $scaleid id of the scale to check
  940. * @return bool
  941. */
  942. function workshop_scale_used_anywhere($scaleid) {
  943. global $CFG; // other files included from here
  944. $strategies = core_component::get_plugin_list('workshopform');
  945. foreach ($strategies as $strategy => $strategypath) {
  946. $strategylib = $strategypath . '/lib.php';
  947. if (is_readable($strategylib)) {
  948. require_once($strategylib);
  949. } else {
  950. throw new coding_exception('the grading forms subplugin must contain library ' . $strategylib);
  951. }
  952. $classname = 'workshop_' . $strategy . '_strategy';
  953. if (method_exists($classname, 'scale_used')) {
  954. if (call_user_func(array($classname, 'scale_used'), $scaleid)) {
  955. // no need to include any other files - scale is used
  956. return true;
  957. }
  958. }
  959. }
  960. return false;
  961. }
  962. ////////////////////////////////////////////////////////////////////////////////
  963. // Gradebook API //
  964. ////////////////////////////////////////////////////////////////////////////////
  965. /**
  966. * Creates or updates grade items for the give workshop instance
  967. *
  968. * Needed by grade_update_mod_grades() in lib/gradelib.php. Also used by
  969. * {@link workshop_update_grades()}.
  970. *
  971. * @param stdClass $workshop instance object with extra cmidnumber property
  972. * @param stdClass $submissiongrades data for the first grade item
  973. * @param stdClass $assessmentgrades data for the second grade item
  974. * @return void
  975. */
  976. function workshop_grade_item_update(stdclass $workshop, $submissiongrades=null, $assessmentgrades=null) {
  977. global $CFG;
  978. require_once($CFG->libdir.'/gradelib.php');
  979. $a = new stdclass();
  980. $a->workshopname = clean_param($workshop->name, PARAM_NOTAGS);
  981. $item = array();
  982. $item['itemname'] = get_string('gradeitemsubmission', 'workshop', $a);
  983. $item['gradetype'] = GRADE_TYPE_VALUE;
  984. $item['grademax'] = $workshop->grade;
  985. $item['grademin'] = 0;
  986. grade_update('mod/workshop', $workshop->course, 'mod', 'workshop', $workshop->id, 0, $submissiongrades , $item);
  987. $item = array();
  988. $item['itemname'] = get_string('gradeitemassessment', 'workshop', $a);
  989. $item['gradetype'] = GRADE_TYPE_VALUE;
  990. $item['grademax'] = $workshop->gradinggrade;
  991. $item['grademin'] = 0;
  992. grade_update('mod/workshop', $workshop->course, 'mod', 'workshop', $workshop->id, 1, $assessmentgrades, $item);
  993. }
  994. /**
  995. * Update workshop grades in the gradebook
  996. *
  997. * Needed by grade_update_mod_grades() in lib/gradelib.php
  998. *
  999. * @category grade
  1000. * @param stdClass $workshop instance object with extra cmidnumber and modname property
  1001. * @param int $userid update grade of specific user only, 0 means all participants
  1002. * @return void
  1003. */
  1004. function workshop_update_grades(stdclass $workshop, $userid=0) {
  1005. global $CFG, $DB;
  1006. require_once($CFG->libdir.'/gradelib.php');
  1007. $whereuser = $userid ? ' AND authorid = :userid' : '';
  1008. $params = array('workshopid' => $workshop->id, 'userid' => $userid);
  1009. $sql = 'SELECT authorid, grade, gradeover, gradeoverby, feedbackauthor, feedbackauthorformat, timemodified, timegraded
  1010. FROM {workshop_submissions}
  1011. WHERE workshopid = :workshopid AND example=0' . $whereuser;
  1012. $records = $DB->get_records_sql($sql, $params);
  1013. $submissiongrades = array();
  1014. foreach ($records as $record) {
  1015. $grade = new stdclass();
  1016. $grade->userid = $record->authorid;
  1017. if (!is_null($record->gradeover)) {
  1018. $grade->rawgrade = grade_floatval($workshop->grade * $record->gradeover / 100);
  1019. $grade->usermodified = $record->gradeoverby;
  1020. } else {
  1021. $grade->rawgrade = grade_floatval($workshop->grade * $record->grade / 100);
  1022. }
  1023. $grade->feedback = $record->feedbackauthor;
  1024. $grade->feedbackformat = $record->feedbackauthorformat;
  1025. $grade->datesubmitted = $record->timemodified;
  1026. $grade->dategraded = $record->timegraded;
  1027. $submissiongrades[$record->authorid] = $grade;
  1028. }
  1029. $whereuser = $userid ? ' AND userid = :userid' : '';
  1030. $params = array('workshopid' => $workshop->id, 'userid' => $userid);
  1031. $sql = 'SELECT userid, gradinggrade, timegraded
  1032. FROM {workshop_aggregations}
  1033. WHERE workshopid = :workshopid' . $whereuser;
  1034. $records = $DB->get_records_sql($sql, $params);
  1035. $assessmentgrades = array();
  1036. foreach ($records as $record) {
  1037. $grade = new stdclass();
  1038. $grade->userid = $record->userid;
  1039. $grade->rawgrade = grade_floatval($workshop->gradinggrade * $record->gradinggrade / 100);
  1040. $grade->dategraded = $record->timegraded;
  1041. $assessmentgrades[$record->userid] = $grade;
  1042. }
  1043. workshop_grade_item_update($workshop, $submissiongrades, $assessmentgrades);
  1044. }
  1045. /**
  1046. * Update the grade items categories if they are changed via mod_form.php
  1047. *
  1048. * We must do it manually here in the workshop module because modedit supports only
  1049. * single grade item while we use two.
  1050. *
  1051. * @param stdClass $workshop An object from the form in mod_form.php
  1052. */
  1053. function workshop_grade_item_category_update($workshop) {
  1054. $gradeitems = grade_item::fetch_all(array(
  1055. 'itemtype' => 'mod',
  1056. 'itemmodule' => 'workshop',
  1057. 'iteminstance' => $workshop->id,
  1058. 'courseid' => $workshop->course));
  1059. if (!empty($gradeitems)) {
  1060. foreach ($gradeitems as $gradeitem) {
  1061. if ($gradeitem->itemnumber == 0) {
  1062. if (isset($workshop->submissiongradepass) &&
  1063. $gradeitem->gradepass != $workshop->submissiongradepass) {
  1064. $gradeitem->gradepass = $workshop->submissiongradepass;
  1065. $gradeitem->update();
  1066. }
  1067. if ($gradeitem->categoryid != $workshop->gradecategory) {
  1068. $gradeitem->set_parent($workshop->gradecategory);
  1069. }
  1070. } else if ($gradeitem->itemnumber == 1) {
  1071. if (isset($workshop->gradinggradepass) &&
  1072. $gradeitem->gradepass != $workshop->gradinggradepass) {
  1073. $gradeitem->gradepass = $workshop->gradinggradepass;
  1074. $gradeitem->update();
  1075. }
  1076. if ($gradeitem->categoryid != $workshop->gradinggradecategory) {
  1077. $gradeitem->set_parent($workshop->gradinggradecategory);
  1078. }
  1079. }
  1080. }
  1081. }
  1082. }
  1083. ////////////////////////////////////////////////////////////////////////////////
  1084. // File API //
  1085. ////////////////////////////////////////////////////////////////////////////////
  1086. /**
  1087. * Returns the lists of all browsable file areas within the given module context
  1088. *
  1089. * The file area workshop_intro for the activity introduction field is added automatically
  1090. * by {@link file_browser::get_file_info_context_module()}
  1091. *
  1092. * @package mod_workshop
  1093. * @category files
  1094. *
  1095. * @param stdClass $course
  1096. * @param stdClass $cm
  1097. * @param stdClass $context
  1098. * @return array of [(string)filearea] => (string)description
  1099. */
  1100. function workshop_get_file_areas($course, $cm, $context) {
  1101. $areas = array();
  1102. $areas['instructauthors'] = get_string('areainstructauthors', 'workshop');
  1103. $areas['instructreviewers'] = get_string('areainstructreviewers', 'workshop');
  1104. $areas['submission_content'] = get_string('areasubmissioncontent', 'workshop');
  1105. $areas['submission_attachment'] = get_string('areasubmissionattachment', 'workshop');
  1106. $areas['conclusion'] = get_string('areaconclusion', 'workshop');
  1107. $areas['overallfeedback_content'] = get_string('areaoverallfeedbackcontent', 'workshop');
  1108. $areas['overallfeedback_attachment'] = get_string('areaoverallfeedbackattachment', 'workshop');
  1109. return $areas;
  1110. }
  1111. /**
  1112. * Serves the files from the workshop file areas
  1113. *
  1114. * Apart from module intro (handled by pluginfile.php automatically), workshop files may be
  1115. * media inserted into submission content (like images) and submission attachments. For these two,
  1116. * the fileareas submission_content and submission_attachment are used.
  1117. * Besides that, areas instructauthors, instructreviewers and conclusion contain the media
  1118. * embedded using the mod_form.php.
  1119. *
  1120. * @package mod_workshop
  1121. * @category files
  1122. *
  1123. * @param stdClass $course the course object
  1124. * @param stdClass $cm the course module object
  1125. * @param stdClass $context the workshop's context
  1126. * @param string $filearea the name of the file area
  1127. * @param array $args extra arguments (itemid, path)
  1128. * @param bool $forcedownload whether or not force download
  1129. * @param array $options additional options affecting the file serving
  1130. * @return bool false if the file not found, just send the file otherwise and do not return anything
  1131. */
  1132. function workshop_pluginfile($course, $cm, $context, $filearea, array $args, $forcedownload, array $options=array()) {
  1133. global $DB, $CFG, $USER;
  1134. if ($context->contextlevel != CONTEXT_MODULE) {
  1135. return false;
  1136. }
  1137. require_login($course, true, $cm);
  1138. if ($filearea === 'instructauthors' or $filearea === 'instructreviewers' or $filearea === 'conclusion') {
  1139. // The $args are supposed to contain just the path, not the item id.
  1140. $relativepath = implode('/', $args);
  1141. $fullpath = "/$context->id/mod_workshop/$filearea/0/$relativepath";
  1142. $fs = get_file_storage();
  1143. if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
  1144. send_file_not_found();
  1145. }
  1146. send_stored_file($file, null, 0, $forcedownload, $options);
  1147. } else if ($filearea === 'submission_content' or $filearea === 'submission_attachment') {
  1148. $itemid = (int)array_shift($args);
  1149. if (!$workshop = $DB->get_record('workshop', array('id' => $cm->instance))) {
  1150. return false;
  1151. }
  1152. if (!$submission = $DB->get_record('workshop_submissions', array('id' => $itemid, 'workshopid' => $workshop->id))) {
  1153. return false;
  1154. }
  1155. // make sure the user is allowed to see the file
  1156. if (empty($submission->example)) {
  1157. if ($USER->id != $submission->authorid) {
  1158. if ($submission->published == 1 and $workshop->phase == 50
  1159. and has_capability('mod/workshop:viewpublishedsubmissions', $context)) {
  1160. // Published submission, we can go (workshop does not take the group mode
  1161. // into account in this case yet).
  1162. } else if (!$DB->record_exists('workshop_assessments', array('submissionid' => $submission->id, 'reviewerid' => $USER->id))) {
  1163. if (!has_capability('mod/workshop:viewallsubmissions', $context)) {
  1164. send_file_not_found();
  1165. } else {
  1166. $gmode = groups_get_activity_groupmode($cm, $course);
  1167. if ($gmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
  1168. // check there is at least one common group with both the $USER
  1169. // and the submission author
  1170. $sql = "SELECT 'x'
  1171. FROM {workshop_submissions} s
  1172. JOIN {user} a ON (a.id = s.authorid)
  1173. JOIN {groups_members} agm ON (a.id = agm.userid)
  1174. JOIN {user} u ON (u.id = ?)
  1175. JOIN {groups_members} ugm ON (u.id = ugm.userid)
  1176. WHERE s.example = 0 AND s.workshopid = ? AND s.id = ? AND agm.groupid = ugm.groupid";
  1177. $params = array($USER->id, $workshop->id, $submission->id);
  1178. if (!$DB->record_exists_sql($sql, $params)) {
  1179. send_file_not_found();
  1180. }
  1181. }
  1182. }
  1183. }
  1184. }
  1185. }
  1186. $fs = get_file_storage();
  1187. $relativepath = implode('/', $args);
  1188. $fullpath = "/$context->id/mod_workshop/$filearea/$itemid/$relativepath";
  1189. if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
  1190. return false;
  1191. }
  1192. // finally send the file
  1193. // these files are uploaded by students - forcing download for security reasons
  1194. send_stored_file($file, 0, 0, true, $options);
  1195. } else if ($filearea === 'overallfeedback_content' or $filearea === 'overallfeedback_attachment') {
  1196. $itemid = (int)array_shift($args);
  1197. if (!$workshop = $DB->get_record('workshop', array('id' => $cm->instance))) {
  1198. return false;
  1199. }
  1200. if (!$assessment = $DB->get_record('workshop_assessments', array('id' => $itemid))) {
  1201. return false;
  1202. }
  1203. if (!$submission = $DB->get_record('workshop_submissions', array('id' => $assessment->submissionid, 'workshopid' => $workshop->id))) {
  1204. return false;
  1205. }
  1206. if ($USER->id == $assessment->reviewerid) {
  1207. // Reviewers can always see their own files.
  1208. } else if ($USER->id == $submission->authorid and $workshop->phase == 50) {
  1209. // Authors can see the feedback once the workshop is closed.
  1210. } else if (!empty($submission->example) and $assessment->weight == 1) {
  1211. // Reference assessments of example submissions can be displayed.
  1212. } else if (!has_capability('mod/workshop:viewallassessments', $context)) {
  1213. send_file_not_found();
  1214. } else {
  1215. $gmode = groups_get_activity_groupmode($cm, $course);
  1216. if ($gmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
  1217. // Check there is at least one common group with both the $USER
  1218. // and the submission author.
  1219. $sql = "SELECT 'x'
  1220. FROM {workshop_submissions} s
  1221. JOIN {user} a ON (a.id = s.authorid)
  1222. JOIN {groups_members} agm ON (a.id = agm.userid)
  1223. JOIN {user} u ON (u.id = ?)
  1224. JOIN {groups_members} ugm ON (u.id = ugm.userid)
  1225. WHERE s.example = 0 AND s.workshopid = ? AND s.id = ? AND agm.groupid = ugm.groupid";
  1226. $params = array($USER->id, $workshop->id, $submission->id);
  1227. if (!$DB->record_exists_sql($sql, $params)) {
  1228. send_file_not_found();
  1229. }
  1230. }
  1231. }
  1232. $fs = get_file_storage();
  1233. $relativepath = implode('/', $args);
  1234. $fullpath = "/$context->id/mod_workshop/$filearea/$itemid/$relativepath";
  1235. if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
  1236. return false;
  1237. }
  1238. // finally send the file
  1239. // these files are uploaded by students - forcing download for security reasons
  1240. send_stored_file($file, 0, 0, true, $options);
  1241. }
  1242. return false;
  1243. }
  1244. /**
  1245. * File browsing support for workshop file areas
  1246. *
  1247. * @package mod_workshop
  1248. * @category files
  1249. *
  1250. * @param file_browser $browser
  1251. * @param array $areas
  1252. * @param stdClass $course
  1253. * @param stdClass $cm
  1254. * @param stdClass $context
  1255. * @param string $filearea
  1256. * @param int $itemid
  1257. * @param string $filepath
  1258. * @param string $filename
  1259. * @return file_info instance or null if not found
  1260. */
  1261. function workshop_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
  1262. global $CFG, $DB, $USER;
  1263. /** @var array internal cache for author names */
  1264. static $submissionauthors = array();
  1265. $fs = get_file_storage();
  1266. if ($filearea === 'submission_content' or $filearea === 'submission_attachment') {
  1267. if (!has_capability('mod/workshop:viewallsubmissions', $context)) {
  1268. return null;
  1269. }
  1270. if (is_null($itemid)) {
  1271. // no itemid (submissionid) passed, display the list of all submissions
  1272. require_once($CFG->dirroot . '/mod/workshop/fileinfolib.php');
  1273. return new workshop_file_info_submissions_container($browser, $course, $cm, $context, $areas, $filearea);
  1274. }
  1275. // make sure the user can see the particular submission in separate groups mode
  1276. $gmode = groups_get_activity_groupmode($cm, $course);
  1277. if ($gmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
  1278. // check there is at least one common group with both the $USER
  1279. // and the submission author (this is not expected to be a frequent
  1280. // usecase so we can live with pretty ineffective one query per submission here...)
  1281. $sql = "SELECT 'x'
  1282. FROM {workshop_submissions} s
  1283. JOIN {user} a ON (a.id = s.authorid)
  1284. JOIN {groups_members} agm ON (a.id = agm.userid)
  1285. JOIN {user} u ON (u.id = ?)
  1286. JOIN {groups_members} ugm ON (u.id = ugm.userid)
  1287. WHERE s.example = 0 AND s.workshopid = ? AND s.id = ? AND agm.groupid = ugm.groupid";
  1288. $params = array($USER->id, $cm->instance, $itemid);
  1289. if (!$DB->record_exists_sql($sql, $params)) {
  1290. return null;
  1291. }
  1292. }
  1293. // we are inside some particular submission container
  1294. $filepath = is_null($filepath) ? '/' : $filepath;
  1295. $filename = is_null($filename) ? '.' : $filename;
  1296. if (!$storedfile = $fs->get_file($context->id, 'mod_workshop', $filearea, $itemid, $filepath, $filename)) {
  1297. if ($filepath === '/' and $filename === '.') {
  1298. $storedfile = new virtual_root_file($context->id, 'mod_workshop', $filearea, $itemid);
  1299. } else {
  1300. // not found
  1301. return null;
  1302. }
  1303. }
  1304. // Checks to see if the user can manage files or is the owner.
  1305. // TODO MDL-33805 - Do not use userid here and move the capability check above.
  1306. if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id) {
  1307. return null;
  1308. }
  1309. // let us display the author's name instead of itemid (submission id)
  1310. if (isset($submissionauthors[$itemid])) {
  1311. $topvisiblename = $submissionauthors[$itemid];
  1312. } else {
  1313. $userfields = get_all_user_name_fields(true, 'u');
  1314. $sql = "SELECT s.id, $userfields
  1315. FROM {workshop_submissions} s
  1316. JOIN {user} u ON (s.authorid = u.id)
  1317. WHERE s.example = 0 AND s.workshopid = ?";
  1318. $params = array($cm->instance);
  1319. $rs = $DB->get_recordset_sql($sql, $params);
  1320. foreach ($rs as $submissionauthor) {
  1321. $title = s(fullname($submissionauthor)); // this is generally not unique...
  1322. $submissionauthors[$submissionauthor->id] = $title;
  1323. }
  1324. $rs->close();
  1325. if (!isset($submissionauthors[$itemid])) {
  1326. // should not happen
  1327. return null;
  1328. } else {
  1329. $topvisiblename = $submissionauthors[$itemid];
  1330. }
  1331. }
  1332. $urlbase = $CFG->wwwroot . '/pluginfile.php';
  1333. // do not allow manual modification of any files!
  1334. return new file_info_stored($browser, $context, $storedfile, $urlbase, $topvisiblename, true, true, false, false);
  1335. }
  1336. if ($filearea === 'overallfeedback_content' or $filearea === 'overallfeedback_attachment') {
  1337. if (!has_capability('mod/workshop:viewallassessments', $context)) {
  1338. return null;
  1339. }
  1340. if (is_null($itemid)) {
  1341. // No itemid (assessmentid) passed, display the list of all assessments.
  1342. require_once($CFG->dirroot . '/mod/workshop/fileinfolib.php');
  1343. return new workshop_file_info_overallfeedback_container($browser, $course, $cm, $context, $areas, $filearea);
  1344. }
  1345. // Make sure the user can see the particular assessment in separate groups mode.
  1346. $gmode = groups_get_activity_groupmode($cm, $course);
  1347. if ($gmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
  1348. // Check there is at least one common group with both the $USER
  1349. // and the submission author.
  1350. $sql = "SELECT 'x'
  1351. FROM {workshop_submissions} s
  1352. JOIN {user} a ON (a.id = s.authorid)
  1353. JOIN {groups_members} agm ON (a.id = agm.userid)
  1354. JOIN {user} u ON (u.id = ?)
  1355. JOIN {groups_members} ugm ON (u.id = ugm.userid)
  1356. WHERE s.example = 0 AND s.workshopid = ? AND s.id = ? AND agm.groupid = ugm.groupid";
  1357. $params = array($USER->id, $cm->instance, $itemid);
  1358. if (!$DB->record_exists_sql($sql, $params)) {
  1359. return null;
  1360. }
  1361. }
  1362. // We are inside a particular assessment container.
  1363. $filepath = is_null($filepath) ? '/' : $filepath;
  1364. $filename = is_null($filename) ? '.' : $filename;
  1365. if (!$storedfile = $fs->get_file($context->id, 'mod_workshop', $filearea, $itemid, $filepath, $filename)) {
  1366. if ($filepath === '/' and $filename === '.') {
  1367. $storedfile = new virtual_root_file($context->id, 'mod_workshop', $filearea, $itemid);
  1368. } else {
  1369. // Not found
  1370. return null;
  1371. }
  1372. }
  1373. // Check to see if the user can manage files or is the owner.
  1374. if (!has_capability('moodle/course:managefiles', $context) and $storedfile->get_userid() != $USER->id) {
  1375. return null;
  1376. }
  1377. $urlbase = $CFG->wwwroot . '/pluginfile.php';
  1378. // Do not allow manual modification of any files.
  1379. return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemid, true, true, false, false);
  1380. }
  1381. if ($filearea == 'instructauthors' or $filearea == 'instructreviewers' or $filearea == 'conclusion') {
  1382. // always only itemid 0
  1383. $filepath = is_null($filepath) ? '/' : $filepath;
  1384. $filename = is_null($filename) ? '.' : $filename;
  1385. $urlbase = $CFG->wwwroot.'/pluginfile.php';
  1386. if (!$storedfile = $fs->get_file($context->id, 'mod_workshop', $filearea, 0, $filepath, $filename)) {
  1387. if ($filepath === '/' and $filename === '.') {
  1388. $storedfile = new virtual_root_file($context->id, 'mod_workshop', $filearea, 0);
  1389. } else {
  1390. // not found
  1391. return null;
  1392. }
  1393. }
  1394. return new file_info_stored($browser, $context, $storedfile, $urlbase, $areas[$filearea], false, true, true, false);
  1395. }
  1396. }
  1397. ////////////////////////////////////////////////////////////////////////////////
  1398. // Navigation API //
  1399. ////////////////////////////////////////////////////////////////////////////////
  1400. /**
  1401. * Extends the global navigation tree by adding workshop nodes if there is a relevant content
  1402. *
  1403. * This can be called by an AJAX request so do not rely on $PAGE as it might not be set up properly.
  1404. *
  1405. * @param navigation_node $navref An object representing the navigation tree node of the workshop module instance
  1406. * @param stdClass $course
  1407. * @param stdClass $module
  1408. * @param cm_info $cm
  1409. */
  1410. function workshop_extend_navigation(navigation_node $navref, stdclass $course, stdclass $module, cm_info $cm) {
  1411. global $CFG;
  1412. if (has_capability('mod/workshop:submit', context_module::instance($cm->id))) {
  1413. $url = new moodle_url('/mod/workshop/submission.php', array('cmid' => $cm->id));
  1414. $mysubmission = $navref->add(get_string('mysubmission', 'workshop'), $url);
  1415. $mysubmission->mainnavonly = true;
  1416. }
  1417. }
  1418. /**
  1419. * Extends the settings navigation with the Workshop settings
  1420. * This function is called when the context for the page is a workshop module. This is not called by AJAX
  1421. * so it is safe to rely on the $PAGE.
  1422. *
  1423. * @param settings_navigation $settingsnav {@link settings_navigation}
  1424. * @param navigation_node $workshopnode {@link navigation_node}
  1425. */
  1426. function workshop_extend_settings_navigation(settings_navigation $settingsnav, navigation_node $workshopnode=null) {
  1427. global $PAGE;
  1428. //$workshopobject = $DB->get_record("workshop", array("id" => $PAGE->cm->instance));
  1429. if (has_capability('mod/workshop:editdimensions', $PAGE->cm->context)) {
  1430. $url = new moodle_url('/mod/workshop/editform.php', array('cmid' => $PAGE->cm->id));
  1431. $workshopnode->add(get_string('editassessmentform', 'workshop'), $url, settings_navigation::TYPE_SETTING);
  1432. }
  1433. if (has_capability('mod/workshop:allocate', $PAGE->cm->context)) {
  1434. $url = new moodle_url('/mod/workshop/allocation.php', array('cmid' => $PAGE->cm->id));
  1435. $workshopnode->add(get_string('allocate', 'workshop'), $url, settings_navigation::TYPE_SETTING);
  1436. }
  1437. }
  1438. /**
  1439. * Return a list of page types
  1440. * @param string $pagetype current page type
  1441. * @param stdClass $parentcontext Block's parent context
  1442. * @param stdClass $currentcontext Current context of block
  1443. */
  1444. function workshop_page_type_list($pagetype, $parentcontext, $currentcontext) {
  1445. $module_pagetype = array('mod-workshop-*'=>get_string('page-mod-workshop-x', 'workshop'));
  1446. return $module_pagetype;
  1447. }
  1448. ////////////////////////////////////////////////////////////////////////////////
  1449. // Calendar API //
  1450. ////////////////////////////////////////////////////////////////////////////////
  1451. /**
  1452. * Updates the calendar events associated to the given workshop
  1453. *
  1454. * @param stdClass $workshop the workshop instance record
  1455. * @param int $cmid course module id
  1456. */
  1457. function workshop_calendar_update(stdClass $workshop, $cmid) {
  1458. global $DB;
  1459. // get the currently registered events so that we can re-use their ids
  1460. $currentevents = $DB->get_records('event', array('modulename' => 'workshop', 'instance' => $workshop->id));
  1461. // the common properties for all events
  1462. $base = new stdClass();
  1463. $base->description = format_module_intro('workshop', $workshop, $cmid, false);
  1464. $base->courseid = $workshop->course;
  1465. $base->groupid = 0;
  1466. $base->userid = 0;
  1467. $base->modulename = 'workshop';
  1468. $base->instance = $workshop->id;
  1469. $base->visible = instance_is_visible('workshop', $workshop);
  1470. $base->timeduration = 0;
  1471. if ($workshop->submissionstart) {
  1472. $event = clone($base);
  1473. $event->name = get_string('submissionstartevent', 'mod_workshop', $workshop->name);
  1474. $event->eventtype = WORKSHOP_EVENT_TYPE_SUBMISSION_OPEN;
  1475. $event->type = empty($workshop->submissionend) ? CALENDAR_EVENT_TYPE_ACTION : CALENDAR_EVENT_TYPE_STANDARD;
  1476. $event->timestart = $workshop->submissionstart;
  1477. $event->timesort = $workshop->submissionstart;
  1478. if ($reusedevent = array_shift($currentevents)) {
  1479. $event->id = $reusedevent->id;
  1480. } else {
  1481. // should not be set but just in case
  1482. unset($event->id);
  1483. }
  1484. // update() will reuse a db record if the id field is set
  1485. $eventobj = new calendar_event($event);
  1486. $eventobj->update($event, false);
  1487. }
  1488. if ($workshop->submissionend) {
  1489. $event = clone($base);
  1490. $event->name = get_string('submissionendevent', 'mod_workshop', $workshop->name);
  1491. $event->eventtype = WORKSHOP_EVENT_TYPE_SUBMISSION_CLOSE;
  1492. $event->type = CALENDAR_EVENT_TYPE_ACTION;
  1493. $event->timestart = $workshop->submissionend;
  1494. $event->timesort = $workshop->submissionend;
  1495. if ($reusedevent = array_shift($currentevents)) {
  1496. $event->id = $reusedevent->id;
  1497. } else {
  1498. // should not be set but just in case
  1499. unset($event->id);
  1500. }
  1501. // update() will reuse a db record if the id field is set
  1502. $eventobj = new calendar_event($event);
  1503. $eventobj->update($event, false);
  1504. }
  1505. if ($workshop->assessmentstart) {
  1506. $event = clone($base);
  1507. $event->name = get_string('assessmentstartevent', 'mod_workshop', $workshop->name);
  1508. $event->eventtype = WORKSHOP_EVENT_TYPE_ASSESSMENT_OPEN;
  1509. $event->type = empty($workshop->assessmentend) ? CALENDAR_EVENT_TYPE_ACTION : CALENDAR_EVENT_TYPE_STANDARD;
  1510. $event->timestart = $workshop->assessmentstart;
  1511. $event->timesort = $workshop->assessmentstart;
  1512. if ($reusedevent = array_shift($currentevents)) {
  1513. $event->id = $reusedevent->id;
  1514. } else {
  1515. // should not be set but just in case
  1516. unset($event->id);
  1517. }
  1518. // update() will reuse a db record if the id field is set
  1519. $eventobj = new calendar_event($event);
  1520. $eventobj->update($event, false);
  1521. }
  1522. if ($workshop->assessmentend) {
  1523. $event = clone($base);
  1524. $event->name = get_string('assessmentendevent', 'mod_workshop', $workshop->name);
  1525. $event->eventtype = WORKSHOP_EVENT_TYPE_ASSESSMENT_CLOSE;
  1526. $event->type = CALENDAR_EVENT_TYPE_ACTION;
  1527. $event->timestart = $workshop->assessmentend;
  1528. $event->timesort = $workshop->assessmentend;
  1529. if ($reusedevent = array_shift($currentevents)) {
  1530. $event->id = $reusedevent->id;
  1531. } else {
  1532. // should not be set but just in case
  1533. unset($event->id);
  1534. }
  1535. // update() will reuse a db record if the id field is set
  1536. $eventobj = new calendar_event($event);
  1537. $eventobj->update($event, false);
  1538. }
  1539. // delete any leftover events
  1540. foreach ($currentevents as $oldevent) {
  1541. $oldevent = calendar_event::load($oldevent);
  1542. $oldevent->delete();
  1543. }
  1544. }
  1545. /**
  1546. * This function receives a calendar event and returns the action associated with it, or null if there is none.
  1547. *
  1548. * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
  1549. * is not displayed on the block.
  1550. *
  1551. * @param calendar_event $event
  1552. * @param \core_calendar\action_factory $factory
  1553. * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
  1554. * @return \core_calendar\local\event\entities\action_interface|null
  1555. */
  1556. function mod_workshop_core_calendar_provide_event_action(calendar_event $event,
  1557. \core_calendar\action_factory $factory, int $userid = 0) {
  1558. global $USER;
  1559. if (!$userid) {
  1560. $userid = $USER->id;
  1561. }
  1562. $cm = get_fast_modinfo($event->courseid, $userid)->instances['workshop'][$event->instance];
  1563. if (!$cm->uservisible) {
  1564. // The module is not visible to the user for any reason.
  1565. return null;
  1566. }
  1567. $completion = new \completion_info($cm->get_course());
  1568. $completiondata = $completion->get_data($cm, false, $userid);
  1569. if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
  1570. return null;
  1571. }
  1572. return $factory->create_instance(
  1573. get_string('viewworkshopsummary', 'workshop'),
  1574. new \moodle_url('/mod/workshop/view.php', array('id' => $cm->id)),
  1575. 1,
  1576. true
  1577. );
  1578. }
  1579. /**
  1580. * This function calculates the minimum and maximum cutoff values for the timestart of
  1581. * the given event.
  1582. *
  1583. * It will return an array with two values, the first being the minimum cutoff value and
  1584. * the second being the maximum cutoff value. Either or both values can be null, which
  1585. * indicates there is no minimum or maximum, respectively.
  1586. *
  1587. * If a cutoff is required then the function must return an array containing the cutoff
  1588. * timestamp and error string to display to the user if the cutoff value is violated.
  1589. *
  1590. * A minimum and maximum cutoff return value will look like:
  1591. * [
  1592. * [1505704373, 'The date must be after this date'],
  1593. * [1506741172, 'The date must be before this date']
  1594. * ]
  1595. *
  1596. * @param calendar_event $event The calendar event to get the time range for
  1597. * @param stdClass $workshop The module instance to get the range from
  1598. * @return array Returns an array with min and max date.
  1599. */
  1600. function mod_workshop_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $workshop) : array {
  1601. $mindate = null;
  1602. $maxdate = null;
  1603. $phasesubmissionend = max($workshop->submissionstart, $workshop->submissionend);
  1604. $phaseassessmentstart = min($workshop->assessmentstart, $workshop->assessmentend);
  1605. if ($phaseassessmentstart == 0) {
  1606. $phaseassessmentstart = max($workshop->assessmentstart, $workshop->assessmentend);
  1607. }
  1608. switch ($event->eventtype) {
  1609. case WORKSHOP_EVENT_TYPE_SUBMISSION_OPEN:
  1610. if (!empty($workshop->submissionend)) {
  1611. $maxdate = [
  1612. $workshop->submissionend - 1, // The submissionstart and submissionend cannot be exactly the same.
  1613. get_string('submissionendbeforestart', 'mod_workshop')
  1614. ];
  1615. } else if ($phaseassessmentstart) {
  1616. $maxdate = [
  1617. $phaseassessmentstart,
  1618. get_string('phasesoverlap', 'mod_workshop')
  1619. ];
  1620. }
  1621. break;
  1622. case WORKSHOP_EVENT_TYPE_SUBMISSION_CLOSE:
  1623. if (!empty($workshop->submissionstart)) {
  1624. $mindate = [
  1625. $workshop->submissionstart + 1, // The submissionstart and submissionend cannot be exactly the same.
  1626. get_string('submissionendbeforestart', 'mod_workshop')
  1627. ];
  1628. }
  1629. if ($phaseassessmentstart) {
  1630. $maxdate = [
  1631. $phaseassessmentstart,
  1632. get_string('phasesoverlap', 'mod_workshop')
  1633. ];
  1634. }
  1635. break;
  1636. case WORKSHOP_EVENT_TYPE_ASSESSMENT_OPEN:
  1637. if ($phasesubmissionend) {
  1638. $mindate = [
  1639. $phasesubmissionend,
  1640. get_string('phasesoverlap', 'mod_workshop')
  1641. ];
  1642. }
  1643. if (!empty($workshop->assessmentend)) {
  1644. $maxdate = [
  1645. $workshop->assessmentend - 1, // The assessmentstart and assessmentend cannot be exactly the same.
  1646. get_string('assessmentendbeforestart', 'mod_workshop')
  1647. ];
  1648. }
  1649. break;
  1650. case WORKSHOP_EVENT_TYPE_ASSESSMENT_CLOSE:
  1651. if (!empty($workshop->assessmentstart)) {
  1652. $mindate = [
  1653. $workshop->assessmentstart + 1, // The assessmentstart and assessmentend cannot be exactly the same.
  1654. get_string('assessmentendbeforestart', 'mod_workshop')
  1655. ];
  1656. } else if ($phasesubmissionend) {
  1657. $mindate = [
  1658. $phasesubmissionend,
  1659. get_string('phasesoverlap', 'mod_workshop')
  1660. ];
  1661. }
  1662. break;
  1663. }
  1664. return [$mindate, $maxdate];
  1665. }
  1666. /**
  1667. * This function will update the workshop module according to the
  1668. * event that has been modified.
  1669. *
  1670. * @param \calendar_event $event
  1671. * @param stdClass $workshop The module instance to get the range from
  1672. */
  1673. function mod_workshop_core_calendar_event_timestart_updated(\calendar_event $event, \stdClass $workshop) : void {
  1674. global $DB;
  1675. $courseid = $event->courseid;
  1676. $modulename = $event->modulename;
  1677. $instanceid = $event->instance;
  1678. // Something weird going on. The event is for a different module so
  1679. // we should ignore it.
  1680. if ($modulename != 'workshop') {
  1681. return;
  1682. }
  1683. if ($workshop->id != $instanceid) {
  1684. return;
  1685. }
  1686. if (!in_array(
  1687. $event->eventtype,
  1688. [
  1689. WORKSHOP_EVENT_TYPE_SUBMISSION_OPEN,
  1690. WORKSHOP_EVENT_TYPE_SUBMISSION_CLOSE,
  1691. WORKSHOP_EVENT_TYPE_ASSESSMENT_OPEN,
  1692. WORKSHOP_EVENT_TYPE_ASSESSMENT_CLOSE
  1693. ]
  1694. )) {
  1695. return;
  1696. }
  1697. $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
  1698. $context = context_module::instance($coursemodule->id);
  1699. // The user does not have the capability to modify this activity.
  1700. if (!has_capability('moodle/course:manageactivities', $context)) {
  1701. return;
  1702. }
  1703. $modified = false;
  1704. switch ($event->eventtype) {
  1705. case WORKSHOP_EVENT_TYPE_SUBMISSION_OPEN:
  1706. if ($event->timestart != $workshop->submissionstart) {
  1707. $workshop->submissionstart = $event->timestart;
  1708. $modified = true;
  1709. }
  1710. break;
  1711. case WORKSHOP_EVENT_TYPE_SUBMISSION_CLOSE:
  1712. if ($event->timestart != $workshop->submissionend) {
  1713. $workshop->submissionend = $event->timestart;
  1714. $modified = true;
  1715. }
  1716. break;
  1717. case WORKSHOP_EVENT_TYPE_ASSESSMENT_OPEN:
  1718. if ($event->timestart != $workshop->assessmentstart) {
  1719. $workshop->assessmentstart = $event->timestart;
  1720. $modified = true;
  1721. }
  1722. break;
  1723. case WORKSHOP_EVENT_TYPE_ASSESSMENT_CLOSE:
  1724. if ($event->timestart != $workshop->assessmentend) {
  1725. $workshop->assessmentend = $event->timestart;
  1726. $modified = true;
  1727. }
  1728. break;
  1729. }
  1730. if ($modified) {
  1731. $workshop->timemodified = time();
  1732. // Persist the assign instance changes.
  1733. $DB->update_record('workshop', $workshop);
  1734. $event = \core\event\course_module_updated::create_from_cm($coursemodule, $context);
  1735. $event->trigger();
  1736. }
  1737. }
  1738. ////////////////////////////////////////////////////////////////////////////////
  1739. // Course reset API //
  1740. ////////////////////////////////////////////////////////////////////////////////
  1741. /**
  1742. * Extends the course reset form with workshop specific settings.
  1743. *
  1744. * @param MoodleQuickForm $mform
  1745. */
  1746. function workshop_reset_course_form_definition($mform) {
  1747. $mform->addElement('header', 'workshopheader', get_string('modulenameplural', 'mod_workshop'));
  1748. $mform->addElement('advcheckbox', 'reset_workshop_submissions', get_string('resetsubmissions', 'mod_workshop'));
  1749. $mform->addHelpButton('reset_workshop_submissions', 'resetsubmissions', 'mod_workshop');
  1750. $mform->addElement('advcheckbox', 'reset_workshop_assessments', get_string('resetassessments', 'mod_workshop'));
  1751. $mform->addHelpButton('reset_workshop_assessments', 'resetassessments', 'mod_workshop');
  1752. $mform->disabledIf('reset_workshop_assessments', 'reset_workshop_submissions', 'checked');
  1753. $mform->addElement('advcheckbox', 'reset_workshop_phase', get_string('resetphase', 'mod_workshop'));
  1754. $mform->addHelpButton('reset_workshop_phase', 'resetphase', 'mod_workshop');
  1755. }
  1756. /**
  1757. * Provides default values for the workshop settings in the course reset form.
  1758. *
  1759. * @param stdClass $course The course to be reset.
  1760. */
  1761. function workshop_reset_course_form_defaults(stdClass $course) {
  1762. $defaults = array(
  1763. 'reset_workshop_submissions' => 1,
  1764. 'reset_workshop_assessments' => 1,
  1765. 'reset_workshop_phase' => 1,
  1766. );
  1767. return $defaults;
  1768. }
  1769. /**
  1770. * Performs the reset of all workshop instances in the course.
  1771. *
  1772. * @param stdClass $data The actual course reset settings.
  1773. * @return array List of results, each being array[(string)component, (string)item, (string)error]
  1774. */
  1775. function workshop_reset_userdata(stdClass $data) {
  1776. global $CFG, $DB;
  1777. // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
  1778. // See MDL-9367.
  1779. shift_course_mod_dates('workshop', array('submissionstart', 'submissionend', 'assessmentstart', 'assessmentend'),
  1780. $data->timeshift, $data->courseid);
  1781. $status = array();
  1782. $status[] = array('component' => get_string('modulenameplural', 'workshop'), 'item' => get_string('datechanged'),
  1783. 'error' => false);
  1784. if (empty($data->reset_workshop_submissions)
  1785. and empty($data->reset_workshop_assessments)
  1786. and empty($data->reset_workshop_phase) ) {
  1787. // Nothing to do here.
  1788. return $status;
  1789. }
  1790. $workshoprecords = $DB->get_records('workshop', array('course' => $data->courseid));
  1791. if (empty($workshoprecords)) {
  1792. // What a boring course - no workshops here!
  1793. return $status;
  1794. }
  1795. require_once($CFG->dirroot . '/mod/workshop/locallib.php');
  1796. $course = $DB->get_record('course', array('id' => $data->courseid), '*', MUST_EXIST);
  1797. foreach ($workshoprecords as $workshoprecord) {
  1798. $cm = get_coursemodule_from_instance('workshop', $workshoprecord->id, $course->id, false, MUST_EXIST);
  1799. $workshop = new workshop($workshoprecord, $cm, $course);
  1800. $status = array_merge($status, $workshop->reset_userdata($data));
  1801. }
  1802. return $status;
  1803. }
  1804. /**
  1805. * Get icon mapping for font-awesome.
  1806. */
  1807. function mod_workshop_get_fontawesome_icon_map() {
  1808. return [
  1809. 'mod_workshop:userplan/task-info' => 'fa-info text-info',
  1810. 'mod_workshop:userplan/task-todo' => 'fa-square-o',
  1811. 'mod_workshop:userplan/task-done' => 'fa-check text-success',
  1812. 'mod_workshop:userplan/task-fail' => 'fa-remove text-danger',
  1813. ];
  1814. }
  1815. /**
  1816. * Check if the module has any update that affects the current user since a given time.
  1817. *
  1818. * @param cm_info $cm course module data
  1819. * @param int $from the time to check updates from
  1820. * @param array $filter if we need to check only specific updates
  1821. * @return stdClass an object with the different type of areas indicating if they were updated or not
  1822. * @since Moodle 3.4
  1823. */
  1824. function workshop_check_updates_since(cm_info $cm, $from, $filter = array()) {
  1825. global $DB, $USER;
  1826. $updates = course_check_module_updates_since($cm, $from, array('instructauthors', 'instructreviewers', 'conclusion'), $filter);
  1827. // Check if there are new submissions, assessments or assessments grades in the workshop.
  1828. $updates->submissions = (object) array('updated' => false);
  1829. $updates->assessments = (object) array('updated' => false);
  1830. $updates->assessmentgrades = (object) array('updated' => false);
  1831. $select = 'workshopid = ? AND authorid = ? AND (timecreated > ? OR timegraded > ? OR timemodified > ?)';
  1832. $params = array($cm->instance, $USER->id, $from, $from, $from);
  1833. $submissions = $DB->get_records_select('workshop_submissions', $select, $params, '', 'id');
  1834. if (!empty($submissions)) {
  1835. $updates->submissions->updated = true;
  1836. $updates->submissions->itemids = array_keys($submissions);
  1837. }
  1838. // Get assessments updates (both submissions reviewed by me or reviews by others).
  1839. $select = "SELECT a.id
  1840. FROM {workshop_assessments} a
  1841. JOIN {workshop_submissions} s ON a.submissionid = s.id
  1842. WHERE s.workshopid = ? AND (a.timecreated > ? OR a.timemodified > ?) AND (s.authorid = ? OR a.reviewerid = ?)";
  1843. $params = array($cm->instance, $from, $from, $USER->id, $USER->id);
  1844. $assessments = $DB->get_records_sql($select, $params);
  1845. if (!empty($assessments)) {
  1846. $updates->assessments->updated = true;
  1847. $updates->assessments->itemids = array_keys($assessments);
  1848. }
  1849. // Finally assessment aggregated grades.
  1850. $select = 'workshopid = ? AND userid = ? AND timegraded > ?';
  1851. $params = array($cm->instance, $USER->id, $from);
  1852. $assessmentgrades = $DB->get_records_select('workshop_aggregations', $select, $params, '', 'id');
  1853. if (!empty($assessmentgrades)) {
  1854. $updates->assessmentgrades->updated = true;
  1855. $updates->assessmentgrades->itemids = array_keys($assessmentgrades);
  1856. }
  1857. // Now, teachers should see other students updates.
  1858. $canviewallsubmissions = has_capability('mod/workshop:viewallsubmissions', $cm->context);
  1859. $canviewallassessments = has_capability('mod/workshop:viewallassessments', $cm->context);
  1860. if ($canviewallsubmissions || $canviewallassessments) {
  1861. $insql = '';
  1862. $inparams = array();
  1863. // To filter by users in my groups when separated groups are forced.
  1864. if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
  1865. $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
  1866. if (empty($groupusers)) {
  1867. return $updates;
  1868. }
  1869. list($insql, $inparams) = $DB->get_in_or_equal($groupusers);
  1870. }
  1871. if ($canviewallsubmissions) {
  1872. $updates->usersubmissions = (object) array('updated' => false);
  1873. $select = 'workshopid = ? AND (timecreated > ? OR timegraded > ? OR timemodified > ?)';
  1874. $params = array($cm->instance, $from, $from, $from);
  1875. if (!empty($insql)) {
  1876. $select .= " AND authorid $insql";
  1877. $params = array_merge($params, $inparams);
  1878. }
  1879. $usersubmissions = $DB->get_records_select('workshop_submissions', $select, $params, '', 'id');
  1880. if (!empty($usersubmissions)) {
  1881. $updates->usersubmissions->updated = true;
  1882. $updates->usersubmissions->itemids = array_keys($usersubmissions);
  1883. }
  1884. }
  1885. if ($canviewallassessments) {
  1886. $updates->userassessments = (object) array('updated' => false);
  1887. $select = "SELECT a.id
  1888. FROM {workshop_assessments} a
  1889. JOIN {workshop_submissions} s ON a.submissionid = s.id
  1890. WHERE s.workshopid = ? AND (a.timecreated > ? OR a.timemodified > ?)";
  1891. $params = array($cm->instance, $from, $from);
  1892. if (!empty($insql)) {
  1893. $select .= " AND s.reviewerid $insql";
  1894. $params = array_merge($params, $inparams);
  1895. }
  1896. $userassessments = $DB->get_records_sql($select, $params);
  1897. if (!empty($userassessments)) {
  1898. $updates->userassessments->updated = true;
  1899. $updates->userassessments->itemids = array_keys($userassessments);
  1900. }
  1901. $updates->userassessmentgrades = (object) array('updated' => false);
  1902. $select = 'workshopid = ? AND timegraded > ?';
  1903. $params = array($cm->instance, $USER->id);
  1904. if (!empty($insql)) {
  1905. $select .= " AND userid $insql";
  1906. $params = array_merge($params, $inparams);
  1907. }
  1908. $userassessmentgrades = $DB->get_records_select('workshop_aggregations', $select, $params, '', 'id');
  1909. if (!empty($userassessmentgrades)) {
  1910. $updates->userassessmentgrades->updated = true;
  1911. $updates->userassessmentgrades->itemids = array_keys($userassessmentgrades);
  1912. }
  1913. }
  1914. }
  1915. return $updates;
  1916. }
  1917. /**
  1918. * Given an array with a file path, it returns the itemid and the filepath for the defined filearea.
  1919. *
  1920. * @param string $filearea The filearea.
  1921. * @param array $args The path (the part after the filearea and before the filename).
  1922. * @return array|null The itemid and the filepath inside the $args path, for the defined filearea.
  1923. */
  1924. function mod_workshop_get_path_from_pluginfile(string $filearea, array $args) : ?array {
  1925. if ($filearea !== 'instructauthors' && $filearea !== 'instructreviewers' && $filearea !== 'conclusion') {
  1926. return null;
  1927. }
  1928. // Workshop only has empty itemid for some of the fileareas.
  1929. array_shift($args);
  1930. // Get the filepath.
  1931. if (empty($args)) {
  1932. $filepath = '/';
  1933. } else {
  1934. $filepath = '/' . implode('/', $args) . '/';
  1935. }
  1936. return [
  1937. 'itemid' => 0,
  1938. 'filepath' => $filepath,
  1939. ];
  1940. }