PageRenderTime 53ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/mod/choice/lib.php

http://github.com/moodle/moodle
PHP | 1391 lines | 782 code | 183 blank | 426 comment | 165 complexity | c59bbdf63b8afc46d37e98946297b45e 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. * @package mod_choice
  18. * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
  19. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  20. */
  21. defined('MOODLE_INTERNAL') || die();
  22. /** @global int $CHOICE_COLUMN_HEIGHT */
  23. global $CHOICE_COLUMN_HEIGHT;
  24. $CHOICE_COLUMN_HEIGHT = 300;
  25. /** @global int $CHOICE_COLUMN_WIDTH */
  26. global $CHOICE_COLUMN_WIDTH;
  27. $CHOICE_COLUMN_WIDTH = 300;
  28. define('CHOICE_PUBLISH_ANONYMOUS', '0');
  29. define('CHOICE_PUBLISH_NAMES', '1');
  30. define('CHOICE_SHOWRESULTS_NOT', '0');
  31. define('CHOICE_SHOWRESULTS_AFTER_ANSWER', '1');
  32. define('CHOICE_SHOWRESULTS_AFTER_CLOSE', '2');
  33. define('CHOICE_SHOWRESULTS_ALWAYS', '3');
  34. define('CHOICE_DISPLAY_HORIZONTAL', '0');
  35. define('CHOICE_DISPLAY_VERTICAL', '1');
  36. define('CHOICE_EVENT_TYPE_OPEN', 'open');
  37. define('CHOICE_EVENT_TYPE_CLOSE', 'close');
  38. /** @global array $CHOICE_PUBLISH */
  39. global $CHOICE_PUBLISH;
  40. $CHOICE_PUBLISH = array (CHOICE_PUBLISH_ANONYMOUS => get_string('publishanonymous', 'choice'),
  41. CHOICE_PUBLISH_NAMES => get_string('publishnames', 'choice'));
  42. /** @global array $CHOICE_SHOWRESULTS */
  43. global $CHOICE_SHOWRESULTS;
  44. $CHOICE_SHOWRESULTS = array (CHOICE_SHOWRESULTS_NOT => get_string('publishnot', 'choice'),
  45. CHOICE_SHOWRESULTS_AFTER_ANSWER => get_string('publishafteranswer', 'choice'),
  46. CHOICE_SHOWRESULTS_AFTER_CLOSE => get_string('publishafterclose', 'choice'),
  47. CHOICE_SHOWRESULTS_ALWAYS => get_string('publishalways', 'choice'));
  48. /** @global array $CHOICE_DISPLAY */
  49. global $CHOICE_DISPLAY;
  50. $CHOICE_DISPLAY = array (CHOICE_DISPLAY_HORIZONTAL => get_string('displayhorizontal', 'choice'),
  51. CHOICE_DISPLAY_VERTICAL => get_string('displayvertical','choice'));
  52. /// Standard functions /////////////////////////////////////////////////////////
  53. /**
  54. * @global object
  55. * @param object $course
  56. * @param object $user
  57. * @param object $mod
  58. * @param object $choice
  59. * @return object|null
  60. */
  61. function choice_user_outline($course, $user, $mod, $choice) {
  62. global $DB;
  63. if ($answer = $DB->get_record('choice_answers', array('choiceid' => $choice->id, 'userid' => $user->id))) {
  64. $result = new stdClass();
  65. $result->info = "'".format_string(choice_get_option_text($choice, $answer->optionid))."'";
  66. $result->time = $answer->timemodified;
  67. return $result;
  68. }
  69. return NULL;
  70. }
  71. /**
  72. * Callback for the "Complete" report - prints the activity summary for the given user
  73. *
  74. * @param object $course
  75. * @param object $user
  76. * @param object $mod
  77. * @param object $choice
  78. */
  79. function choice_user_complete($course, $user, $mod, $choice) {
  80. global $DB;
  81. if ($answers = $DB->get_records('choice_answers', array("choiceid" => $choice->id, "userid" => $user->id))) {
  82. $info = [];
  83. foreach ($answers as $answer) {
  84. $info[] = "'" . format_string(choice_get_option_text($choice, $answer->optionid)) . "'";
  85. }
  86. core_collator::asort($info);
  87. echo get_string("answered", "choice") . ": ". join(', ', $info) . ". " .
  88. get_string("updated", '', userdate($answer->timemodified));
  89. } else {
  90. print_string("notanswered", "choice");
  91. }
  92. }
  93. /**
  94. * Given an object containing all the necessary data,
  95. * (defined by the form in mod_form.php) this function
  96. * will create a new instance and return the id number
  97. * of the new instance.
  98. *
  99. * @global object
  100. * @param object $choice
  101. * @return int
  102. */
  103. function choice_add_instance($choice) {
  104. global $DB, $CFG;
  105. require_once($CFG->dirroot.'/mod/choice/locallib.php');
  106. $choice->timemodified = time();
  107. //insert answers
  108. $choice->id = $DB->insert_record("choice", $choice);
  109. foreach ($choice->option as $key => $value) {
  110. $value = trim($value);
  111. if (isset($value) && $value <> '') {
  112. $option = new stdClass();
  113. $option->text = $value;
  114. $option->choiceid = $choice->id;
  115. if (isset($choice->limit[$key])) {
  116. $option->maxanswers = $choice->limit[$key];
  117. }
  118. $option->timemodified = time();
  119. $DB->insert_record("choice_options", $option);
  120. }
  121. }
  122. // Add calendar events if necessary.
  123. choice_set_events($choice);
  124. if (!empty($choice->completionexpected)) {
  125. \core_completion\api::update_completion_date_event($choice->coursemodule, 'choice', $choice->id,
  126. $choice->completionexpected);
  127. }
  128. return $choice->id;
  129. }
  130. /**
  131. * Given an object containing all the necessary data,
  132. * (defined by the form in mod_form.php) this function
  133. * will update an existing instance with new data.
  134. *
  135. * @global object
  136. * @param object $choice
  137. * @return bool
  138. */
  139. function choice_update_instance($choice) {
  140. global $DB, $CFG;
  141. require_once($CFG->dirroot.'/mod/choice/locallib.php');
  142. $choice->id = $choice->instance;
  143. $choice->timemodified = time();
  144. //update, delete or insert answers
  145. foreach ($choice->option as $key => $value) {
  146. $value = trim($value);
  147. $option = new stdClass();
  148. $option->text = $value;
  149. $option->choiceid = $choice->id;
  150. if (isset($choice->limit[$key])) {
  151. $option->maxanswers = $choice->limit[$key];
  152. }
  153. $option->timemodified = time();
  154. if (isset($choice->optionid[$key]) && !empty($choice->optionid[$key])){//existing choice record
  155. $option->id=$choice->optionid[$key];
  156. if (isset($value) && $value <> '') {
  157. $DB->update_record("choice_options", $option);
  158. } else {
  159. // Remove the empty (unused) option.
  160. $DB->delete_records("choice_options", array("id" => $option->id));
  161. // Delete any answers associated with this option.
  162. $DB->delete_records("choice_answers", array("choiceid" => $choice->id, "optionid" => $option->id));
  163. }
  164. } else {
  165. if (isset($value) && $value <> '') {
  166. $DB->insert_record("choice_options", $option);
  167. }
  168. }
  169. }
  170. // Add calendar events if necessary.
  171. choice_set_events($choice);
  172. $completionexpected = (!empty($choice->completionexpected)) ? $choice->completionexpected : null;
  173. \core_completion\api::update_completion_date_event($choice->coursemodule, 'choice', $choice->id, $completionexpected);
  174. return $DB->update_record('choice', $choice);
  175. }
  176. /**
  177. * @global object
  178. * @param object $choice
  179. * @param object $user
  180. * @param object $coursemodule
  181. * @param array $allresponses
  182. * @return array
  183. */
  184. function choice_prepare_options($choice, $user, $coursemodule, $allresponses) {
  185. global $DB;
  186. $cdisplay = array('options'=>array());
  187. $cdisplay['limitanswers'] = true;
  188. $context = context_module::instance($coursemodule->id);
  189. foreach ($choice->option as $optionid => $text) {
  190. if (isset($text)) { //make sure there are no dud entries in the db with blank text values.
  191. $option = new stdClass;
  192. $option->attributes = new stdClass;
  193. $option->attributes->value = $optionid;
  194. $option->text = format_string($text);
  195. $option->maxanswers = $choice->maxanswers[$optionid];
  196. $option->displaylayout = $choice->display;
  197. if (isset($allresponses[$optionid])) {
  198. $option->countanswers = count($allresponses[$optionid]);
  199. } else {
  200. $option->countanswers = 0;
  201. }
  202. if ($DB->record_exists('choice_answers', array('choiceid' => $choice->id, 'userid' => $user->id, 'optionid' => $optionid))) {
  203. $option->attributes->checked = true;
  204. }
  205. if ( $choice->limitanswers && ($option->countanswers >= $option->maxanswers) && empty($option->attributes->checked)) {
  206. $option->attributes->disabled = true;
  207. }
  208. $cdisplay['options'][] = $option;
  209. }
  210. }
  211. $cdisplay['hascapability'] = is_enrolled($context, NULL, 'mod/choice:choose'); //only enrolled users are allowed to make a choice
  212. if ($choice->allowupdate && $DB->record_exists('choice_answers', array('choiceid'=> $choice->id, 'userid'=> $user->id))) {
  213. $cdisplay['allowupdate'] = true;
  214. }
  215. if ($choice->showpreview && $choice->timeopen > time()) {
  216. $cdisplay['previewonly'] = true;
  217. }
  218. return $cdisplay;
  219. }
  220. /**
  221. * Modifies responses of other users adding the option $newoptionid to them
  222. *
  223. * @param array $userids list of users to add option to (must be users without any answers yet)
  224. * @param array $answerids list of existing attempt ids of users (will be either appended or
  225. * substituted with the newoptionid, depending on $choice->allowmultiple)
  226. * @param int $newoptionid
  227. * @param stdClass $choice choice object, result of {@link choice_get_choice()}
  228. * @param stdClass $cm
  229. * @param stdClass $course
  230. */
  231. function choice_modify_responses($userids, $answerids, $newoptionid, $choice, $cm, $course) {
  232. // Get all existing responses and the list of non-respondents.
  233. $groupmode = groups_get_activity_groupmode($cm);
  234. $onlyactive = $choice->includeinactive ? false : true;
  235. $allresponses = choice_get_response_data($choice, $cm, $groupmode, $onlyactive);
  236. // Check that the option value is valid.
  237. if (!$newoptionid || !isset($choice->option[$newoptionid])) {
  238. return;
  239. }
  240. // First add responses for users who did not make any choice yet.
  241. foreach ($userids as $userid) {
  242. if (isset($allresponses[0][$userid])) {
  243. choice_user_submit_response($newoptionid, $choice, $userid, $course, $cm);
  244. }
  245. }
  246. // Create the list of all options already selected by each user.
  247. $optionsbyuser = []; // Mapping userid=>array of chosen choice options.
  248. $usersbyanswer = []; // Mapping answerid=>userid (which answer belongs to each user).
  249. foreach ($allresponses as $optionid => $responses) {
  250. if ($optionid > 0) {
  251. foreach ($responses as $userid => $userresponse) {
  252. $optionsbyuser += [$userid => []];
  253. $optionsbyuser[$userid][] = $optionid;
  254. $usersbyanswer[$userresponse->answerid] = $userid;
  255. }
  256. }
  257. }
  258. // Go through the list of submitted attemptids and find which users answers need to be updated.
  259. foreach ($answerids as $answerid) {
  260. if (isset($usersbyanswer[$answerid])) {
  261. $userid = $usersbyanswer[$answerid];
  262. if (!in_array($newoptionid, $optionsbyuser[$userid])) {
  263. $options = $choice->allowmultiple ?
  264. array_merge($optionsbyuser[$userid], [$newoptionid]) : $newoptionid;
  265. choice_user_submit_response($options, $choice, $userid, $course, $cm);
  266. }
  267. }
  268. }
  269. }
  270. /**
  271. * Process user submitted answers for a choice,
  272. * and either updating them or saving new answers.
  273. *
  274. * @param int|array $formanswer the id(s) of the user submitted choice options.
  275. * @param object $choice the selected choice.
  276. * @param int $userid user identifier.
  277. * @param object $course current course.
  278. * @param object $cm course context.
  279. * @return void
  280. */
  281. function choice_user_submit_response($formanswer, $choice, $userid, $course, $cm) {
  282. global $DB, $CFG, $USER;
  283. require_once($CFG->libdir.'/completionlib.php');
  284. $continueurl = new moodle_url('/mod/choice/view.php', array('id' => $cm->id));
  285. if (empty($formanswer)) {
  286. print_error('atleastoneoption', 'choice', $continueurl);
  287. }
  288. if (is_array($formanswer)) {
  289. if (!$choice->allowmultiple) {
  290. print_error('multiplenotallowederror', 'choice', $continueurl);
  291. }
  292. $formanswers = $formanswer;
  293. } else {
  294. $formanswers = array($formanswer);
  295. }
  296. $options = $DB->get_records('choice_options', array('choiceid' => $choice->id), '', 'id');
  297. foreach ($formanswers as $key => $val) {
  298. if (!isset($options[$val])) {
  299. print_error('cannotsubmit', 'choice', $continueurl);
  300. }
  301. }
  302. // Start lock to prevent synchronous access to the same data
  303. // before it's updated, if using limits.
  304. if ($choice->limitanswers) {
  305. $timeout = 10;
  306. $locktype = 'mod_choice_choice_user_submit_response';
  307. // Limiting access to this choice.
  308. $resouce = 'choiceid:' . $choice->id;
  309. $lockfactory = \core\lock\lock_config::get_lock_factory($locktype);
  310. // Opening the lock.
  311. $choicelock = $lockfactory->get_lock($resouce, $timeout, MINSECS);
  312. if (!$choicelock) {
  313. print_error('cannotsubmit', 'choice', $continueurl);
  314. }
  315. }
  316. $current = $DB->get_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $userid));
  317. // Array containing [answerid => optionid] mapping.
  318. $existinganswers = array_map(function($answer) {
  319. return $answer->optionid;
  320. }, $current);
  321. $context = context_module::instance($cm->id);
  322. $choicesexceeded = false;
  323. $countanswers = array();
  324. foreach ($formanswers as $val) {
  325. $countanswers[$val] = 0;
  326. }
  327. if($choice->limitanswers) {
  328. // Find out whether groups are being used and enabled
  329. if (groups_get_activity_groupmode($cm) > 0) {
  330. $currentgroup = groups_get_activity_group($cm);
  331. } else {
  332. $currentgroup = 0;
  333. }
  334. list ($insql, $params) = $DB->get_in_or_equal($formanswers, SQL_PARAMS_NAMED);
  335. if($currentgroup) {
  336. // If groups are being used, retrieve responses only for users in
  337. // current group
  338. global $CFG;
  339. $params['groupid'] = $currentgroup;
  340. $sql = "SELECT ca.*
  341. FROM {choice_answers} ca
  342. INNER JOIN {groups_members} gm ON ca.userid=gm.userid
  343. WHERE optionid $insql
  344. AND gm.groupid= :groupid";
  345. } else {
  346. // Groups are not used, retrieve all answers for this option ID
  347. $sql = "SELECT ca.*
  348. FROM {choice_answers} ca
  349. WHERE optionid $insql";
  350. }
  351. $answers = $DB->get_records_sql($sql, $params);
  352. if ($answers) {
  353. foreach ($answers as $a) { //only return enrolled users.
  354. if (is_enrolled($context, $a->userid, 'mod/choice:choose')) {
  355. $countanswers[$a->optionid]++;
  356. }
  357. }
  358. }
  359. foreach ($countanswers as $opt => $count) {
  360. // Ignore the user's existing answers when checking whether an answer count has been exceeded.
  361. // A user may wish to update their response with an additional choice option and shouldn't be competing with themself!
  362. if (in_array($opt, $existinganswers)) {
  363. continue;
  364. }
  365. if ($count >= $choice->maxanswers[$opt]) {
  366. $choicesexceeded = true;
  367. break;
  368. }
  369. }
  370. }
  371. // Check the user hasn't exceeded the maximum selections for the choice(s) they have selected.
  372. $answersnapshots = array();
  373. $deletedanswersnapshots = array();
  374. if (!($choice->limitanswers && $choicesexceeded)) {
  375. if ($current) {
  376. // Update an existing answer.
  377. foreach ($current as $c) {
  378. if (in_array($c->optionid, $formanswers)) {
  379. $DB->set_field('choice_answers', 'timemodified', time(), array('id' => $c->id));
  380. } else {
  381. $deletedanswersnapshots[] = $c;
  382. $DB->delete_records('choice_answers', array('id' => $c->id));
  383. }
  384. }
  385. // Add new ones.
  386. foreach ($formanswers as $f) {
  387. if (!in_array($f, $existinganswers)) {
  388. $newanswer = new stdClass();
  389. $newanswer->optionid = $f;
  390. $newanswer->choiceid = $choice->id;
  391. $newanswer->userid = $userid;
  392. $newanswer->timemodified = time();
  393. $newanswer->id = $DB->insert_record("choice_answers", $newanswer);
  394. $answersnapshots[] = $newanswer;
  395. }
  396. }
  397. } else {
  398. // Add new answer.
  399. foreach ($formanswers as $answer) {
  400. $newanswer = new stdClass();
  401. $newanswer->choiceid = $choice->id;
  402. $newanswer->userid = $userid;
  403. $newanswer->optionid = $answer;
  404. $newanswer->timemodified = time();
  405. $newanswer->id = $DB->insert_record("choice_answers", $newanswer);
  406. $answersnapshots[] = $newanswer;
  407. }
  408. // Update completion state
  409. $completion = new completion_info($course);
  410. if ($completion->is_enabled($cm) && $choice->completionsubmit) {
  411. $completion->update_state($cm, COMPLETION_COMPLETE);
  412. }
  413. }
  414. } else {
  415. // This is a choice with limited options, and one of the options selected has just run over its limit.
  416. $choicelock->release();
  417. print_error('choicefull', 'choice', $continueurl);
  418. }
  419. // Release lock.
  420. if (isset($choicelock)) {
  421. $choicelock->release();
  422. }
  423. // Trigger events.
  424. foreach ($deletedanswersnapshots as $answer) {
  425. \mod_choice\event\answer_deleted::create_from_object($answer, $choice, $cm, $course)->trigger();
  426. }
  427. foreach ($answersnapshots as $answer) {
  428. \mod_choice\event\answer_created::create_from_object($answer, $choice, $cm, $course)->trigger();
  429. }
  430. }
  431. /**
  432. * @param array $user
  433. * @param object $cm
  434. * @return void Output is echo'd
  435. */
  436. function choice_show_reportlink($user, $cm) {
  437. $userschosen = array();
  438. foreach($user as $optionid => $userlist) {
  439. if ($optionid) {
  440. $userschosen = array_merge($userschosen, array_keys($userlist));
  441. }
  442. }
  443. $responsecount = count(array_unique($userschosen));
  444. echo '<div class="reportlink">';
  445. echo "<a href=\"report.php?id=$cm->id\">".get_string("viewallresponses", "choice", $responsecount)."</a>";
  446. echo '</div>';
  447. }
  448. /**
  449. * @global object
  450. * @param object $choice
  451. * @param object $course
  452. * @param object $coursemodule
  453. * @param array $allresponses
  454. * * @param bool $allresponses
  455. * @return object
  456. */
  457. function prepare_choice_show_results($choice, $course, $cm, $allresponses) {
  458. global $OUTPUT;
  459. $display = clone($choice);
  460. $display->coursemoduleid = $cm->id;
  461. $display->courseid = $course->id;
  462. if (!empty($choice->showunanswered)) {
  463. $choice->option[0] = get_string('notanswered', 'choice');
  464. $choice->maxanswers[0] = 0;
  465. }
  466. // Remove from the list of non-respondents the users who do not have access to this activity.
  467. if (!empty($display->showunanswered) && $allresponses[0]) {
  468. $info = new \core_availability\info_module(cm_info::create($cm));
  469. $allresponses[0] = $info->filter_user_list($allresponses[0]);
  470. }
  471. //overwrite options value;
  472. $display->options = array();
  473. $allusers = [];
  474. foreach ($choice->option as $optionid => $optiontext) {
  475. $display->options[$optionid] = new stdClass;
  476. $display->options[$optionid]->text = format_string($optiontext, true,
  477. ['context' => context_module::instance($cm->id)]);
  478. $display->options[$optionid]->maxanswer = $choice->maxanswers[$optionid];
  479. if (array_key_exists($optionid, $allresponses)) {
  480. $display->options[$optionid]->user = $allresponses[$optionid];
  481. $allusers = array_merge($allusers, array_keys($allresponses[$optionid]));
  482. }
  483. }
  484. unset($display->option);
  485. unset($display->maxanswers);
  486. $display->numberofuser = count(array_unique($allusers));
  487. $context = context_module::instance($cm->id);
  488. $display->viewresponsecapability = has_capability('mod/choice:readresponses', $context);
  489. $display->deleterepsonsecapability = has_capability('mod/choice:deleteresponses',$context);
  490. $display->fullnamecapability = has_capability('moodle/site:viewfullnames', $context);
  491. if (empty($allresponses)) {
  492. echo $OUTPUT->heading(get_string("nousersyet"), 3, null);
  493. return false;
  494. }
  495. return $display;
  496. }
  497. /**
  498. * @global object
  499. * @param array $attemptids
  500. * @param object $choice Choice main table row
  501. * @param object $cm Course-module object
  502. * @param object $course Course object
  503. * @return bool
  504. */
  505. function choice_delete_responses($attemptids, $choice, $cm, $course) {
  506. global $DB, $CFG, $USER;
  507. require_once($CFG->libdir.'/completionlib.php');
  508. if(!is_array($attemptids) || empty($attemptids)) {
  509. return false;
  510. }
  511. foreach($attemptids as $num => $attemptid) {
  512. if(empty($attemptid)) {
  513. unset($attemptids[$num]);
  514. }
  515. }
  516. $completion = new completion_info($course);
  517. foreach($attemptids as $attemptid) {
  518. if ($todelete = $DB->get_record('choice_answers', array('choiceid' => $choice->id, 'id' => $attemptid))) {
  519. // Trigger the event answer deleted.
  520. \mod_choice\event\answer_deleted::create_from_object($todelete, $choice, $cm, $course)->trigger();
  521. $DB->delete_records('choice_answers', array('choiceid' => $choice->id, 'id' => $attemptid));
  522. }
  523. }
  524. // Update completion state.
  525. if ($completion->is_enabled($cm) && $choice->completionsubmit) {
  526. $completion->update_state($cm, COMPLETION_INCOMPLETE);
  527. }
  528. return true;
  529. }
  530. /**
  531. * Given an ID of an instance of this module,
  532. * this function will permanently delete the instance
  533. * and any data that depends on it.
  534. *
  535. * @global object
  536. * @param int $id
  537. * @return bool
  538. */
  539. function choice_delete_instance($id) {
  540. global $DB;
  541. if (! $choice = $DB->get_record("choice", array("id"=>"$id"))) {
  542. return false;
  543. }
  544. $result = true;
  545. if (! $DB->delete_records("choice_answers", array("choiceid"=>"$choice->id"))) {
  546. $result = false;
  547. }
  548. if (! $DB->delete_records("choice_options", array("choiceid"=>"$choice->id"))) {
  549. $result = false;
  550. }
  551. if (! $DB->delete_records("choice", array("id"=>"$choice->id"))) {
  552. $result = false;
  553. }
  554. // Remove old calendar events.
  555. if (! $DB->delete_records('event', array('modulename' => 'choice', 'instance' => $choice->id))) {
  556. $result = false;
  557. }
  558. return $result;
  559. }
  560. /**
  561. * Returns text string which is the answer that matches the id
  562. *
  563. * @global object
  564. * @param object $choice
  565. * @param int $id
  566. * @return string
  567. */
  568. function choice_get_option_text($choice, $id) {
  569. global $DB;
  570. if ($result = $DB->get_record("choice_options", array("id" => $id))) {
  571. return $result->text;
  572. } else {
  573. return get_string("notanswered", "choice");
  574. }
  575. }
  576. /**
  577. * Gets a full choice record
  578. *
  579. * @global object
  580. * @param int $choiceid
  581. * @return object|bool The choice or false
  582. */
  583. function choice_get_choice($choiceid) {
  584. global $DB;
  585. if ($choice = $DB->get_record("choice", array("id" => $choiceid))) {
  586. if ($options = $DB->get_records("choice_options", array("choiceid" => $choiceid), "id")) {
  587. foreach ($options as $option) {
  588. $choice->option[$option->id] = $option->text;
  589. $choice->maxanswers[$option->id] = $option->maxanswers;
  590. }
  591. return $choice;
  592. }
  593. }
  594. return false;
  595. }
  596. /**
  597. * List the actions that correspond to a view of this module.
  598. * This is used by the participation report.
  599. *
  600. * Note: This is not used by new logging system. Event with
  601. * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
  602. * be considered as view action.
  603. *
  604. * @return array
  605. */
  606. function choice_get_view_actions() {
  607. return array('view','view all','report');
  608. }
  609. /**
  610. * List the actions that correspond to a post of this module.
  611. * This is used by the participation report.
  612. *
  613. * Note: This is not used by new logging system. Event with
  614. * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
  615. * will be considered as post action.
  616. *
  617. * @return array
  618. */
  619. function choice_get_post_actions() {
  620. return array('choose','choose again');
  621. }
  622. /**
  623. * Implementation of the function for printing the form elements that control
  624. * whether the course reset functionality affects the choice.
  625. *
  626. * @param object $mform form passed by reference
  627. */
  628. function choice_reset_course_form_definition(&$mform) {
  629. $mform->addElement('header', 'choiceheader', get_string('modulenameplural', 'choice'));
  630. $mform->addElement('advcheckbox', 'reset_choice', get_string('removeresponses','choice'));
  631. }
  632. /**
  633. * Course reset form defaults.
  634. *
  635. * @return array
  636. */
  637. function choice_reset_course_form_defaults($course) {
  638. return array('reset_choice'=>1);
  639. }
  640. /**
  641. * Actual implementation of the reset course functionality, delete all the
  642. * choice responses for course $data->courseid.
  643. *
  644. * @global object
  645. * @global object
  646. * @param object $data the data submitted from the reset course.
  647. * @return array status array
  648. */
  649. function choice_reset_userdata($data) {
  650. global $CFG, $DB;
  651. $componentstr = get_string('modulenameplural', 'choice');
  652. $status = array();
  653. if (!empty($data->reset_choice)) {
  654. $choicessql = "SELECT ch.id
  655. FROM {choice} ch
  656. WHERE ch.course=?";
  657. $DB->delete_records_select('choice_answers', "choiceid IN ($choicessql)", array($data->courseid));
  658. $status[] = array('component'=>$componentstr, 'item'=>get_string('removeresponses', 'choice'), 'error'=>false);
  659. }
  660. /// updating dates - shift may be negative too
  661. if ($data->timeshift) {
  662. // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
  663. // See MDL-9367.
  664. shift_course_mod_dates('choice', array('timeopen', 'timeclose'), $data->timeshift, $data->courseid);
  665. $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
  666. }
  667. return $status;
  668. }
  669. /**
  670. * @global object
  671. * @global object
  672. * @global object
  673. * @uses CONTEXT_MODULE
  674. * @param object $choice
  675. * @param object $cm
  676. * @param int $groupmode
  677. * @param bool $onlyactive Whether to get response data for active users only.
  678. * @return array
  679. */
  680. function choice_get_response_data($choice, $cm, $groupmode, $onlyactive) {
  681. global $CFG, $USER, $DB;
  682. $context = context_module::instance($cm->id);
  683. /// Get the current group
  684. if ($groupmode > 0) {
  685. $currentgroup = groups_get_activity_group($cm);
  686. } else {
  687. $currentgroup = 0;
  688. }
  689. /// Initialise the returned array, which is a matrix: $allresponses[responseid][userid] = responseobject
  690. $allresponses = array();
  691. /// First get all the users who have access here
  692. /// To start with we assume they are all "unanswered" then move them later
  693. $extrafields = get_extra_user_fields($context);
  694. $allresponses[0] = get_enrolled_users($context, 'mod/choice:choose', $currentgroup,
  695. user_picture::fields('u', $extrafields), null, 0, 0, $onlyactive);
  696. /// Get all the recorded responses for this choice
  697. $rawresponses = $DB->get_records('choice_answers', array('choiceid' => $choice->id));
  698. /// Use the responses to move users into the correct column
  699. if ($rawresponses) {
  700. $answeredusers = array();
  701. foreach ($rawresponses as $response) {
  702. if (isset($allresponses[0][$response->userid])) { // This person is enrolled and in correct group
  703. $allresponses[0][$response->userid]->timemodified = $response->timemodified;
  704. $allresponses[$response->optionid][$response->userid] = clone($allresponses[0][$response->userid]);
  705. $allresponses[$response->optionid][$response->userid]->answerid = $response->id;
  706. $answeredusers[] = $response->userid;
  707. }
  708. }
  709. foreach ($answeredusers as $answereduser) {
  710. unset($allresponses[0][$answereduser]);
  711. }
  712. }
  713. return $allresponses;
  714. }
  715. /**
  716. * @uses FEATURE_GROUPS
  717. * @uses FEATURE_GROUPINGS
  718. * @uses FEATURE_MOD_INTRO
  719. * @uses FEATURE_COMPLETION_TRACKS_VIEWS
  720. * @uses FEATURE_GRADE_HAS_GRADE
  721. * @uses FEATURE_GRADE_OUTCOMES
  722. * @param string $feature FEATURE_xx constant for requested feature
  723. * @return mixed True if module supports feature, null if doesn't know
  724. */
  725. function choice_supports($feature) {
  726. switch($feature) {
  727. case FEATURE_GROUPS: return true;
  728. case FEATURE_GROUPINGS: return true;
  729. case FEATURE_MOD_INTRO: return true;
  730. case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
  731. case FEATURE_COMPLETION_HAS_RULES: return true;
  732. case FEATURE_GRADE_HAS_GRADE: return false;
  733. case FEATURE_GRADE_OUTCOMES: return false;
  734. case FEATURE_BACKUP_MOODLE2: return true;
  735. case FEATURE_SHOW_DESCRIPTION: return true;
  736. default: return null;
  737. }
  738. }
  739. /**
  740. * Adds module specific settings to the settings block
  741. *
  742. * @param settings_navigation $settings The settings navigation object
  743. * @param navigation_node $choicenode The node to add module settings to
  744. */
  745. function choice_extend_settings_navigation(settings_navigation $settings, navigation_node $choicenode) {
  746. global $PAGE;
  747. if (has_capability('mod/choice:readresponses', $PAGE->cm->context)) {
  748. $groupmode = groups_get_activity_groupmode($PAGE->cm);
  749. if ($groupmode) {
  750. groups_get_activity_group($PAGE->cm, true);
  751. }
  752. $choice = choice_get_choice($PAGE->cm->instance);
  753. // Check if we want to include responses from inactive users.
  754. $onlyactive = $choice->includeinactive ? false : true;
  755. // Big function, approx 6 SQL calls per user.
  756. $allresponses = choice_get_response_data($choice, $PAGE->cm, $groupmode, $onlyactive);
  757. $allusers = [];
  758. foreach($allresponses as $optionid => $userlist) {
  759. if ($optionid) {
  760. $allusers = array_merge($allusers, array_keys($userlist));
  761. }
  762. }
  763. $responsecount = count(array_unique($allusers));
  764. $choicenode->add(get_string("viewallresponses", "choice", $responsecount), new moodle_url('/mod/choice/report.php', array('id'=>$PAGE->cm->id)));
  765. }
  766. }
  767. /**
  768. * Obtains the automatic completion state for this choice based on any conditions
  769. * in forum settings.
  770. *
  771. * @param object $course Course
  772. * @param object $cm Course-module
  773. * @param int $userid User ID
  774. * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
  775. * @return bool True if completed, false if not, $type if conditions not set.
  776. */
  777. function choice_get_completion_state($course, $cm, $userid, $type) {
  778. global $CFG,$DB;
  779. // Get choice details
  780. $choice = $DB->get_record('choice', array('id'=>$cm->instance), '*',
  781. MUST_EXIST);
  782. // If completion option is enabled, evaluate it and return true/false
  783. if($choice->completionsubmit) {
  784. return $DB->record_exists('choice_answers', array(
  785. 'choiceid'=>$choice->id, 'userid'=>$userid));
  786. } else {
  787. // Completion option is not enabled so just return $type
  788. return $type;
  789. }
  790. }
  791. /**
  792. * Return a list of page types
  793. * @param string $pagetype current page type
  794. * @param stdClass $parentcontext Block's parent context
  795. * @param stdClass $currentcontext Current context of block
  796. */
  797. function choice_page_type_list($pagetype, $parentcontext, $currentcontext) {
  798. $module_pagetype = array('mod-choice-*'=>get_string('page-mod-choice-x', 'choice'));
  799. return $module_pagetype;
  800. }
  801. /**
  802. * @deprecated since Moodle 3.3, when the block_course_overview block was removed.
  803. */
  804. function choice_print_overview() {
  805. throw new coding_exception('choice_print_overview() can not be used any more and is obsolete.');
  806. }
  807. /**
  808. * Get responses of a given user on a given choice.
  809. *
  810. * @param stdClass $choice Choice record
  811. * @param int $userid User id
  812. * @return array of choice answers records
  813. * @since Moodle 3.6
  814. */
  815. function choice_get_user_response($choice, $userid) {
  816. global $DB;
  817. return $DB->get_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $userid), 'optionid');
  818. }
  819. /**
  820. * Get my responses on a given choice.
  821. *
  822. * @param stdClass $choice Choice record
  823. * @return array of choice answers records
  824. * @since Moodle 3.0
  825. */
  826. function choice_get_my_response($choice) {
  827. global $USER;
  828. return choice_get_user_response($choice, $USER->id);
  829. }
  830. /**
  831. * Get all the responses on a given choice.
  832. *
  833. * @param stdClass $choice Choice record
  834. * @return array of choice answers records
  835. * @since Moodle 3.0
  836. */
  837. function choice_get_all_responses($choice) {
  838. global $DB;
  839. return $DB->get_records('choice_answers', array('choiceid' => $choice->id));
  840. }
  841. /**
  842. * Return true if we are allowd to view the choice results.
  843. *
  844. * @param stdClass $choice Choice record
  845. * @param rows|null $current my choice responses
  846. * @param bool|null $choiceopen if the choice is open
  847. * @return bool true if we can view the results, false otherwise.
  848. * @since Moodle 3.0
  849. */
  850. function choice_can_view_results($choice, $current = null, $choiceopen = null) {
  851. if (is_null($choiceopen)) {
  852. $timenow = time();
  853. if ($choice->timeopen != 0 && $timenow < $choice->timeopen) {
  854. // If the choice is not available, we can't see the results.
  855. return false;
  856. }
  857. if ($choice->timeclose != 0 && $timenow > $choice->timeclose) {
  858. $choiceopen = false;
  859. } else {
  860. $choiceopen = true;
  861. }
  862. }
  863. if (empty($current)) {
  864. $current = choice_get_my_response($choice);
  865. }
  866. if ($choice->showresults == CHOICE_SHOWRESULTS_ALWAYS or
  867. ($choice->showresults == CHOICE_SHOWRESULTS_AFTER_ANSWER and !empty($current)) or
  868. ($choice->showresults == CHOICE_SHOWRESULTS_AFTER_CLOSE and !$choiceopen)) {
  869. return true;
  870. }
  871. return false;
  872. }
  873. /**
  874. * Mark the activity completed (if required) and trigger the course_module_viewed event.
  875. *
  876. * @param stdClass $choice choice object
  877. * @param stdClass $course course object
  878. * @param stdClass $cm course module object
  879. * @param stdClass $context context object
  880. * @since Moodle 3.0
  881. */
  882. function choice_view($choice, $course, $cm, $context) {
  883. // Trigger course_module_viewed event.
  884. $params = array(
  885. 'context' => $context,
  886. 'objectid' => $choice->id
  887. );
  888. $event = \mod_choice\event\course_module_viewed::create($params);
  889. $event->add_record_snapshot('course_modules', $cm);
  890. $event->add_record_snapshot('course', $course);
  891. $event->add_record_snapshot('choice', $choice);
  892. $event->trigger();
  893. // Completion.
  894. $completion = new completion_info($course);
  895. $completion->set_module_viewed($cm);
  896. }
  897. /**
  898. * Check if a choice is available for the current user.
  899. *
  900. * @param stdClass $choice choice record
  901. * @return array status (available or not and possible warnings)
  902. */
  903. function choice_get_availability_status($choice) {
  904. $available = true;
  905. $warnings = array();
  906. $timenow = time();
  907. if (!empty($choice->timeopen) && ($choice->timeopen > $timenow)) {
  908. $available = false;
  909. $warnings['notopenyet'] = userdate($choice->timeopen);
  910. } else if (!empty($choice->timeclose) && ($timenow > $choice->timeclose)) {
  911. $available = false;
  912. $warnings['expired'] = userdate($choice->timeclose);
  913. }
  914. if (!$choice->allowupdate && choice_get_my_response($choice)) {
  915. $available = false;
  916. $warnings['choicesaved'] = '';
  917. }
  918. // Choice is available.
  919. return array($available, $warnings);
  920. }
  921. /**
  922. * This standard function will check all instances of this module
  923. * and make sure there are up-to-date events created for each of them.
  924. * If courseid = 0, then every choice event in the site is checked, else
  925. * only choice events belonging to the course specified are checked.
  926. * This function is used, in its new format, by restore_refresh_events()
  927. *
  928. * @param int $courseid
  929. * @param int|stdClass $instance Choice module instance or ID.
  930. * @param int|stdClass $cm Course module object or ID (not used in this module).
  931. * @return bool
  932. */
  933. function choice_refresh_events($courseid = 0, $instance = null, $cm = null) {
  934. global $DB, $CFG;
  935. require_once($CFG->dirroot.'/mod/choice/locallib.php');
  936. // If we have instance information then we can just update the one event instead of updating all events.
  937. if (isset($instance)) {
  938. if (!is_object($instance)) {
  939. $instance = $DB->get_record('choice', array('id' => $instance), '*', MUST_EXIST);
  940. }
  941. choice_set_events($instance);
  942. return true;
  943. }
  944. if ($courseid) {
  945. if (! $choices = $DB->get_records("choice", array("course" => $courseid))) {
  946. return true;
  947. }
  948. } else {
  949. if (! $choices = $DB->get_records("choice")) {
  950. return true;
  951. }
  952. }
  953. foreach ($choices as $choice) {
  954. choice_set_events($choice);
  955. }
  956. return true;
  957. }
  958. /**
  959. * Check if the module has any update that affects the current user since a given time.
  960. *
  961. * @param cm_info $cm course module data
  962. * @param int $from the time to check updates from
  963. * @param array $filter if we need to check only specific updates
  964. * @return stdClass an object with the different type of areas indicating if they were updated or not
  965. * @since Moodle 3.2
  966. */
  967. function choice_check_updates_since(cm_info $cm, $from, $filter = array()) {
  968. global $DB;
  969. $updates = new stdClass();
  970. $choice = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
  971. list($available, $warnings) = choice_get_availability_status($choice);
  972. if (!$available) {
  973. return $updates;
  974. }
  975. $updates = course_check_module_updates_since($cm, $from, array(), $filter);
  976. if (!choice_can_view_results($choice)) {
  977. return $updates;
  978. }
  979. // Check if there are new responses in the choice.
  980. $updates->answers = (object) array('updated' => false);
  981. $select = 'choiceid = :id AND timemodified > :since';
  982. $params = array('id' => $choice->id, 'since' => $from);
  983. $answers = $DB->get_records_select('choice_answers', $select, $params, '', 'id');
  984. if (!empty($answers)) {
  985. $updates->answers->updated = true;
  986. $updates->answers->itemids = array_keys($answers);
  987. }
  988. return $updates;
  989. }
  990. /**
  991. * This function receives a calendar event and returns the action associated with it, or null if there is none.
  992. *
  993. * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
  994. * is not displayed on the block.
  995. *
  996. * @param calendar_event $event
  997. * @param \core_calendar\action_factory $factory
  998. * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
  999. * @return \core_calendar\local\event\entities\action_interface|null
  1000. */
  1001. function mod_choice_core_calendar_provide_event_action(calendar_event $event,
  1002. \core_calendar\action_factory $factory,
  1003. int $userid = 0) {
  1004. global $USER;
  1005. if (!$userid) {
  1006. $userid = $USER->id;
  1007. }
  1008. $cm = get_fast_modinfo($event->courseid, $userid)->instances['choice'][$event->instance];
  1009. if (!$cm->uservisible) {
  1010. // The module is not visible to the user for any reason.
  1011. return null;
  1012. }
  1013. $completion = new \completion_info($cm->get_course());
  1014. $completiondata = $completion->get_data($cm, false, $userid);
  1015. if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
  1016. return null;
  1017. }
  1018. $now = time();
  1019. if (!empty($cm->customdata['timeclose']) && $cm->customdata['timeclose'] < $now) {
  1020. // The choice has closed so the user can no longer submit anything.
  1021. return null;
  1022. }
  1023. // The choice is actionable if we don't have a start time or the start time is
  1024. // in the past.
  1025. $actionable = (empty($cm->customdata['timeopen']) || $cm->customdata['timeopen'] <= $now);
  1026. if ($actionable && choice_get_user_response((object)['id' => $event->instance], $userid)) {
  1027. // There is no action if the user has already submitted their choice.
  1028. return null;
  1029. }
  1030. return $factory->create_instance(
  1031. get_string('viewchoices', 'choice'),
  1032. new \moodle_url('/mod/choice/view.php', array('id' => $cm->id)),
  1033. 1,
  1034. $actionable
  1035. );
  1036. }
  1037. /**
  1038. * This function calculates the minimum and maximum cutoff values for the timestart of
  1039. * the given event.
  1040. *
  1041. * It will return an array with two values, the first being the minimum cutoff value and
  1042. * the second being the maximum cutoff value. Either or both values can be null, which
  1043. * indicates there is no minimum or maximum, respectively.
  1044. *
  1045. * If a cutoff is required then the function must return an array containing the cutoff
  1046. * timestamp and error string to display to the user if the cutoff value is violated.
  1047. *
  1048. * A minimum and maximum cutoff return value will look like:
  1049. * [
  1050. * [1505704373, 'The date must be after this date'],
  1051. * [1506741172, 'The date must be before this date']
  1052. * ]
  1053. *
  1054. * @param calendar_event $event The calendar event to get the time range for
  1055. * @param stdClass $choice The module instance to get the range from
  1056. */
  1057. function mod_choice_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $choice) {
  1058. $mindate = null;
  1059. $maxdate = null;
  1060. if ($event->eventtype == CHOICE_EVENT_TYPE_OPEN) {
  1061. if (!empty($choice->timeclose)) {
  1062. $maxdate = [
  1063. $choice->timeclose,
  1064. get_string('openafterclose', 'choice')
  1065. ];
  1066. }
  1067. } else if ($event->eventtype == CHOICE_EVENT_TYPE_CLOSE) {
  1068. if (!empty($choice->timeopen)) {
  1069. $mindate = [
  1070. $choice->timeopen,
  1071. get_string('closebeforeopen', 'choice')
  1072. ];
  1073. }
  1074. }
  1075. return [$mindate, $maxdate];
  1076. }
  1077. /**
  1078. * This function will update the choice module according to the
  1079. * event that has been modified.
  1080. *
  1081. * It will set the timeopen or timeclose value of the choice instance
  1082. * according to the type of event provided.
  1083. *
  1084. * @throws \moodle_exception
  1085. * @param \calendar_event $event
  1086. * @param stdClass $choice The module instance to get the range from
  1087. */
  1088. function mod_choice_core_calendar_event_timestart_updated(\calendar_event $event, \stdClass $choice) {
  1089. global $DB;
  1090. if (!in_array($event->eventtype, [CHOICE_EVENT_TYPE_OPEN, CHOICE_EVENT_TYPE_CLOSE])) {
  1091. return;
  1092. }
  1093. $courseid = $event->courseid;
  1094. $modulename = $event->modulename;
  1095. $instanceid = $event->instance;
  1096. $modified = false;
  1097. // Something weird going on. The event is for a different module so
  1098. // we should ignore it.
  1099. if ($modulename != 'choice') {
  1100. return;
  1101. }
  1102. if ($choice->id != $instanceid) {
  1103. return;
  1104. }
  1105. $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
  1106. $context = context_module::instance($coursemodule->id);
  1107. // The user does not have the capability to modify this activity.
  1108. if (!has_capability('moodle/course:manageactivities', $context)) {
  1109. return;
  1110. }
  1111. if ($event->eventtype == CHOICE_EVENT_TYPE_OPEN) {
  1112. // If the event is for the choice activity opening then we should
  1113. // set the start time of the choice activity to be the new start
  1114. // time of the event.
  1115. if ($choice->timeopen != $event->timestart) {
  1116. $choice->timeopen = $event->timestart;
  1117. $modified = true;
  1118. }
  1119. } else if ($event->eventtype == CHOICE_EVENT_TYPE_CLOSE) {
  1120. // If the event is for the choice activity closing then we should
  1121. // set the end time of the choice activity to be the new start
  1122. // time of the event.
  1123. if ($choice->timeclose != $event->timestart) {
  1124. $choice->timeclose = $event->timestart;
  1125. $modified = true;
  1126. }
  1127. }
  1128. if ($modified) {
  1129. $choice->timemodified = time();
  1130. // Persist the instance changes.
  1131. $DB->update_record('choice', $choice);
  1132. $event = \core\event\course_module_updated::create_from_cm($coursemodule, $context);
  1133. $event->trigger();
  1134. }
  1135. }
  1136. /**
  1137. * Get icon mapping for font-awesome.
  1138. */
  1139. function mod_choice_get_fontawesome_icon_map() {
  1140. return [
  1141. 'mod_choice:row' => 'fa-info',
  1142. 'mod_choice:column' => 'fa-columns',
  1143. ];
  1144. }
  1145. /**
  1146. * Add a get_coursemodule_info function in case any choice type wants to add 'extra' information
  1147. * for the course (see resource).
  1148. *
  1149. * Given a course_module object, this function returns any "extra" information that may be needed
  1150. * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
  1151. *
  1152. * @param stdClass $coursemodule The coursemodule object (record).
  1153. * @return cached_cm_info An object on information that the courses
  1154. * will know about (most noticeably, an icon).
  1155. */
  1156. function choice_get_coursemodule_info($coursemodule) {
  1157. global $DB;
  1158. $dbparams = ['id' => $coursemodule->instance];
  1159. $fields = 'id, name, intro, introformat, completionsubmit, timeopen, timeclose';
  1160. if (!$choice = $DB->get_record('choice', $dbparams, $fields)) {
  1161. return false;
  1162. }
  1163. $result = new cached_cm_info();
  1164. $result->name = $choice->name;
  1165. if ($coursemodule->showdescription) {
  1166. // Convert intro to html. Do not filter cached version, filters run at display time.
  1167. $result->content = format_module_intro('choice', $choice, $coursemodule->id, false);
  1168. }
  1169. // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
  1170. if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
  1171. $result->customdata['customcompletionrules']['completionsubmit'] = $choice->completionsubmit;
  1172. }
  1173. // Populate some other values that can be used in calendar or on dashboard.
  1174. if ($choice->timeopen) {
  1175. $result->customdata['timeopen'] = $choice->timeopen;
  1176. }
  1177. if ($choice->timeclose) {
  1178. $result->customdata['timeclose'] = $choice->timeclose;
  1179. }
  1180. return $result;
  1181. }
  1182. /**
  1183. * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
  1184. *
  1185. * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
  1186. * @return array $descriptions the array of descriptions for the custom rules.
  1187. */
  1188. function mod_choice_get_completion_active_rule_descriptions($cm) {
  1189. // Values will be present in cm_info, and we assume these are up to date.
  1190. if (empty($cm->customdata['customcompletionrules'])
  1191. || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
  1192. return [];
  1193. }
  1194. $descriptions = [];
  1195. foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
  1196. switch ($key) {
  1197. case 'completionsubmit':
  1198. if (!empty($val)) {
  1199. $descriptions[] = get_string('completionsubmit', 'choice');
  1200. }
  1201. break;
  1202. default:
  1203. break;
  1204. }
  1205. }
  1206. return $descriptions;
  1207. }