Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.
/mod/choice/ -> lib.php (source)

Differences Between: [Versions 310 and 311] [Versions 311 and 400] [Versions 311 and 401] [Versions 311 and 402] [Versions 311 and 403] [Versions 39 and 311]

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