Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.10.x will end 8 November 2021 (12 months).
  • Bug fixes for security issues in 3.10.x will end 9 May 2022 (18 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.
/mod/survey/ -> lib.php (source)

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

   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_survey
  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  /**
  25   * Graph size
  26   * @global int $SURVEY_GHEIGHT
  27   */
  28  global $SURVEY_GHEIGHT;
  29  $SURVEY_GHEIGHT = 500;
  30  /**
  31   * Graph size
  32   * @global int $SURVEY_GWIDTH
  33   */
  34  global $SURVEY_GWIDTH;
  35  $SURVEY_GWIDTH  = 900;
  36  /**
  37   * Question Type
  38   * @global array $SURVEY_QTYPE
  39   */
  40  global $SURVEY_QTYPE;
  41  $SURVEY_QTYPE = array (
  42          "-3" => "Virtual Actual and Preferred",
  43          "-2" => "Virtual Preferred",
  44          "-1" => "Virtual Actual",
  45           "0" => "Text",
  46           "1" => "Actual",
  47           "2" => "Preferred",
  48           "3" => "Actual and Preferred",
  49          );
  50  
  51  
  52  define("SURVEY_COLLES_ACTUAL",           "1");
  53  define("SURVEY_COLLES_PREFERRED",        "2");
  54  define("SURVEY_COLLES_PREFERRED_ACTUAL", "3");
  55  define("SURVEY_ATTLS",                   "4");
  56  define("SURVEY_CIQ",                     "5");
  57  
  58  
  59  // STANDARD FUNCTIONS ////////////////////////////////////////////////////////
  60  /**
  61   * Given an object containing all the necessary data,
  62   * (defined by the form in mod_form.php) this function
  63   * will create a new instance and return the id number
  64   * of the new instance.
  65   *
  66   * @global object
  67   * @param object $survey
  68   * @return int|bool
  69   */
  70  function survey_add_instance($survey) {
  71      global $DB;
  72  
  73      if (!$template = $DB->get_record("survey", array("id"=>$survey->template))) {
  74          return 0;
  75      }
  76  
  77      $survey->questions    = $template->questions;
  78      $survey->timecreated  = time();
  79      $survey->timemodified = $survey->timecreated;
  80  
  81      $id = $DB->insert_record("survey", $survey);
  82  
  83      $completiontimeexpected = !empty($survey->completionexpected) ? $survey->completionexpected : null;
  84      \core_completion\api::update_completion_date_event($survey->coursemodule, 'survey', $id, $completiontimeexpected);
  85  
  86      return $id;
  87  
  88  }
  89  
  90  /**
  91   * Given an object containing all the necessary data,
  92   * (defined by the form in mod_form.php) this function
  93   * will update an existing instance with new data.
  94   *
  95   * @global object
  96   * @param object $survey
  97   * @return bool
  98   */
  99  function survey_update_instance($survey) {
 100      global $DB;
 101  
 102      if (!$template = $DB->get_record("survey", array("id"=>$survey->template))) {
 103          return 0;
 104      }
 105  
 106      $survey->id           = $survey->instance;
 107      $survey->questions    = $template->questions;
 108      $survey->timemodified = time();
 109  
 110      $completiontimeexpected = !empty($survey->completionexpected) ? $survey->completionexpected : null;
 111      \core_completion\api::update_completion_date_event($survey->coursemodule, 'survey', $survey->id, $completiontimeexpected);
 112  
 113      return $DB->update_record("survey", $survey);
 114  }
 115  
 116  /**
 117   * Given an ID of an instance of this module,
 118   * this function will permanently delete the instance
 119   * and any data that depends on it.
 120   *
 121   * @global object
 122   * @param int $id
 123   * @return bool
 124   */
 125  function survey_delete_instance($id) {
 126      global $DB;
 127  
 128      if (! $survey = $DB->get_record("survey", array("id"=>$id))) {
 129          return false;
 130      }
 131  
 132      $cm = get_coursemodule_from_instance('survey', $id);
 133      \core_completion\api::update_completion_date_event($cm->id, 'survey', $id, null);
 134  
 135      $result = true;
 136  
 137      if (! $DB->delete_records("survey_analysis", array("survey"=>$survey->id))) {
 138          $result = false;
 139      }
 140  
 141      if (! $DB->delete_records("survey_answers", array("survey"=>$survey->id))) {
 142          $result = false;
 143      }
 144  
 145      if (! $DB->delete_records("survey", array("id"=>$survey->id))) {
 146          $result = false;
 147      }
 148  
 149      return $result;
 150  }
 151  
 152  /**
 153   * @global object
 154   * @param object $course
 155   * @param object $user
 156   * @param object $mod
 157   * @param object $survey
 158   * @return $result
 159   */
 160  function survey_user_outline($course, $user, $mod, $survey) {
 161      global $DB;
 162  
 163      if ($answers = $DB->get_records("survey_answers", array('survey'=>$survey->id, 'userid'=>$user->id))) {
 164          $lastanswer = array_pop($answers);
 165  
 166          $result = new stdClass();
 167          $result->info = get_string("done", "survey");
 168          $result->time = $lastanswer->time;
 169          return $result;
 170      }
 171      return NULL;
 172  }
 173  
 174  /**
 175   * @global stdObject
 176   * @global object
 177   * @uses SURVEY_CIQ
 178   * @param object $course
 179   * @param object $user
 180   * @param object $mod
 181   * @param object $survey
 182   */
 183  function survey_user_complete($course, $user, $mod, $survey) {
 184      global $CFG, $DB, $OUTPUT;
 185  
 186      if (survey_already_done($survey->id, $user->id)) {
 187          if ($survey->template == SURVEY_CIQ) { // print out answers for critical incidents
 188              $table = new html_table();
 189              $table->align = array("left", "left");
 190  
 191              $questions = $DB->get_records_list("survey_questions", "id", explode(',', $survey->questions));
 192              $questionorder = explode(",", $survey->questions);
 193  
 194              foreach ($questionorder as $key=>$val) {
 195                  $question = $questions[$val];
 196                  $questiontext = get_string($question->shorttext, "survey");
 197  
 198                  if ($answer = survey_get_user_answer($survey->id, $question->id, $user->id)) {
 199                      $answertext = "$answer->answer1";
 200                  } else {
 201                      $answertext = "No answer";
 202                  }
 203                  $table->data[] = array("<b>$questiontext</b>", s($answertext));
 204              }
 205              echo html_writer::table($table);
 206  
 207          } else {
 208  
 209              survey_print_graph("id=$mod->id&amp;sid=$user->id&amp;type=student.png");
 210          }
 211  
 212      } else {
 213          print_string("notdone", "survey");
 214      }
 215  }
 216  
 217  /**
 218   * @global stdClass
 219   * @global object
 220   * @param object $course
 221   * @param mixed $viewfullnames
 222   * @param int $timestamp
 223   * @return bool
 224   */
 225  function survey_print_recent_activity($course, $viewfullnames, $timestart) {
 226      global $CFG, $DB, $OUTPUT;
 227  
 228      $modinfo = get_fast_modinfo($course);
 229      $ids = array();
 230      foreach ($modinfo->cms as $cm) {
 231          if ($cm->modname != 'survey') {
 232              continue;
 233          }
 234          if (!$cm->uservisible) {
 235              continue;
 236          }
 237          $ids[$cm->instance] = $cm->instance;
 238      }
 239  
 240      if (!$ids) {
 241          return false;
 242      }
 243  
 244      $slist = implode(',', $ids); // there should not be hundreds of glossaries in one course, right?
 245  
 246      $allusernames = user_picture::fields('u');
 247      $rs = $DB->get_recordset_sql("SELECT sa.userid, sa.survey, MAX(sa.time) AS time,
 248                                           $allusernames
 249                                      FROM {survey_answers} sa
 250                                      JOIN {user} u ON u.id = sa.userid
 251                                     WHERE sa.survey IN ($slist) AND sa.time > ?
 252                                  GROUP BY sa.userid, sa.survey, $allusernames
 253                                  ORDER BY time ASC", array($timestart));
 254      if (!$rs->valid()) {
 255          $rs->close(); // Not going to iterate (but exit), close rs
 256          return false;
 257      }
 258  
 259      $surveys = array();
 260  
 261      foreach ($rs as $survey) {
 262          $cm = $modinfo->instances['survey'][$survey->survey];
 263          $survey->name = $cm->name;
 264          $survey->cmid = $cm->id;
 265          $surveys[] = $survey;
 266      }
 267      $rs->close();
 268  
 269      if (!$surveys) {
 270          return false;
 271      }
 272  
 273      echo $OUTPUT->heading(get_string('newsurveyresponses', 'survey') . ':', 6);
 274      foreach ($surveys as $survey) {
 275          $url = $CFG->wwwroot.'/mod/survey/view.php?id='.$survey->cmid;
 276          print_recent_activity_note($survey->time, $survey, $survey->name, $url, false, $viewfullnames);
 277      }
 278  
 279      return true;
 280  }
 281  
 282  // SQL FUNCTIONS ////////////////////////////////////////////////////////
 283  
 284  /**
 285   * @global object
 286   * @param sting $log
 287   * @return array
 288   */
 289  function survey_log_info($log) {
 290      global $DB;
 291      return $DB->get_record_sql("SELECT s.name, u.firstname, u.lastname, u.picture
 292                                    FROM {survey} s, {user} u
 293                                   WHERE s.id = ?  AND u.id = ?", array($log->info, $log->userid));
 294  }
 295  
 296  /**
 297   * @global object
 298   * @param int $surveyid
 299   * @param int $groupid
 300   * @param int $groupingid
 301   * @return array
 302   */
 303  function survey_get_responses($surveyid, $groupid, $groupingid) {
 304      global $DB;
 305  
 306      $params = array('surveyid'=>$surveyid, 'groupid'=>$groupid, 'groupingid'=>$groupingid);
 307  
 308      if ($groupid) {
 309          $groupsjoin = "JOIN {groups_members} gm ON u.id = gm.userid AND gm.groupid = :groupid ";
 310  
 311      } else if ($groupingid) {
 312          $groupsjoin = "JOIN {groups_members} gm ON u.id = gm.userid
 313                         JOIN {groupings_groups} gg ON gm.groupid = gg.groupid AND gg.groupingid = :groupingid ";
 314      } else {
 315          $groupsjoin = "";
 316      }
 317  
 318      $userfields = user_picture::fields('u');
 319      return $DB->get_records_sql("SELECT $userfields, MAX(a.time) as time
 320                                     FROM {survey_answers} a
 321                                     JOIN {user} u ON a.userid = u.id
 322                              $groupsjoin
 323                                    WHERE a.survey = :surveyid
 324                                 GROUP BY $userfields
 325                                 ORDER BY time ASC", $params);
 326  }
 327  
 328  /**
 329   * @global object
 330   * @param int $survey
 331   * @param int $user
 332   * @return array
 333   */
 334  function survey_get_analysis($survey, $user) {
 335      global $DB;
 336  
 337      return $DB->get_record_sql("SELECT notes
 338                                    FROM {survey_analysis}
 339                                   WHERE survey=? AND userid=?", array($survey, $user));
 340  }
 341  
 342  /**
 343   * @global object
 344   * @param int $survey
 345   * @param int $user
 346   * @param string $notes
 347   */
 348  function survey_update_analysis($survey, $user, $notes) {
 349      global $DB;
 350  
 351      return $DB->execute("UPDATE {survey_analysis}
 352                              SET notes=?
 353                            WHERE survey=?
 354                              AND userid=?", array($notes, $survey, $user));
 355  }
 356  
 357  /**
 358   * @global object
 359   * @param int $surveyid
 360   * @param int $groupid
 361   * @param string $sort
 362   * @return array
 363   */
 364  function survey_get_user_answers($surveyid, $questionid, $groupid, $sort="sa.answer1,sa.answer2 ASC") {
 365      global $DB;
 366  
 367      $params = array('surveyid'=>$surveyid, 'questionid'=>$questionid);
 368  
 369      if ($groupid) {
 370          $groupfrom = ', {groups_members} gm';
 371          $groupsql  = 'AND gm.groupid = :groupid AND u.id = gm.userid';
 372          $params['groupid'] = $groupid;
 373      } else {
 374          $groupfrom = '';
 375          $groupsql  = '';
 376      }
 377  
 378      $userfields = user_picture::fields('u');
 379      return $DB->get_records_sql("SELECT sa.*, $userfields
 380                                     FROM {survey_answers} sa,  {user} u $groupfrom
 381                                    WHERE sa.survey = :surveyid
 382                                          AND sa.question = :questionid
 383                                          AND u.id = sa.userid $groupsql
 384                                 ORDER BY $sort", $params);
 385  }
 386  
 387  /**
 388   * @global object
 389   * @param int $surveyid
 390   * @param int $questionid
 391   * @param int $userid
 392   * @return array
 393   */
 394  function survey_get_user_answer($surveyid, $questionid, $userid) {
 395      global $DB;
 396  
 397      return $DB->get_record_sql("SELECT sa.*
 398                                    FROM {survey_answers} sa
 399                                   WHERE sa.survey = ?
 400                                         AND sa.question = ?
 401                                         AND sa.userid = ?", array($surveyid, $questionid, $userid));
 402  }
 403  
 404  // MODULE FUNCTIONS ////////////////////////////////////////////////////////
 405  /**
 406   * @global object
 407   * @param int $survey
 408   * @param int $user
 409   * @param string $notes
 410   * @return bool|int
 411   */
 412  function survey_add_analysis($survey, $user, $notes) {
 413      global $DB;
 414  
 415      $record = new stdClass();
 416      $record->survey = $survey;
 417      $record->userid = $user;
 418      $record->notes = $notes;
 419  
 420      return $DB->insert_record("survey_analysis", $record, false);
 421  }
 422  /**
 423   * @global object
 424   * @param int $survey
 425   * @param int $user
 426   * @return bool
 427   */
 428  function survey_already_done($survey, $user) {
 429      global $DB;
 430  
 431      return $DB->record_exists("survey_answers", array("survey"=>$survey, "userid"=>$user));
 432  }
 433  /**
 434   * @param int $surveyid
 435   * @param int $groupid
 436   * @param int $groupingid
 437   * @return int
 438   */
 439  function survey_count_responses($surveyid, $groupid, $groupingid) {
 440      if ($responses = survey_get_responses($surveyid, $groupid, $groupingid)) {
 441          return count($responses);
 442      } else {
 443          return 0;
 444      }
 445  }
 446  
 447  /**
 448   * @param int $cmid
 449   * @param array $results
 450   * @param int $courseid
 451   */
 452  function survey_print_all_responses($cmid, $results, $courseid) {
 453      global $OUTPUT;
 454      $table = new html_table();
 455      $table->head  = array ("", get_string("name"),  get_string("time"));
 456      $table->align = array ("", "left", "left");
 457      $table->size = array (35, "", "" );
 458  
 459      foreach ($results as $a) {
 460          $table->data[] = array($OUTPUT->user_picture($a, array('courseid'=>$courseid)),
 461                 html_writer::link("report.php?action=student&student=$a->id&id=$cmid", fullname($a)),
 462                 userdate($a->time));
 463      }
 464  
 465      echo html_writer::table($table);
 466  }
 467  
 468  /**
 469   * @global object
 470   * @param int $templateid
 471   * @return string
 472   */
 473  function survey_get_template_name($templateid) {
 474      global $DB;
 475  
 476      if ($templateid) {
 477          if ($ss = $DB->get_record("surveys", array("id"=>$templateid))) {
 478              return $ss->name;
 479          }
 480      } else {
 481          return "";
 482      }
 483  }
 484  
 485  
 486  /**
 487   * @param string $name
 488   * @param array $numwords
 489   * @return string
 490   */
 491  function survey_shorten_name ($name, $numwords) {
 492      $words = explode(" ", $name);
 493      $output = '';
 494      for ($i=0; $i < $numwords; $i++) {
 495          $output .= $words[$i]." ";
 496      }
 497      return $output;
 498  }
 499  
 500  /**
 501   * @todo Check this function
 502   *
 503   * @global object
 504   * @global object
 505   * @global int
 506   * @global void This is never defined
 507   * @global object This is defined twice?
 508   * @param object $question
 509   */
 510  function survey_print_multi($question) {
 511      global $USER, $DB, $qnum, $DB, $OUTPUT; //TODO: this is sloppy globals abuse
 512  
 513      $stripreferthat = get_string("ipreferthat", "survey");
 514      $strifoundthat = get_string("ifoundthat", "survey");
 515      $strdefault    = get_string('notyetanswered', 'survey');
 516      $strresponses  = get_string('responses', 'survey');
 517  
 518      echo $OUTPUT->heading($question->text, 3);
 519      echo "\n<table width=\"90%\" cellpadding=\"4\" cellspacing=\"1\" border=\"0\" class=\"surveytable\">";
 520  
 521      $options = explode( ",", $question->options);
 522      $numoptions = count($options);
 523  
 524      // COLLES Actual (which is having questions of type 1) and COLLES Preferred (type 2)
 525      // expect just one answer per question. COLLES Actual and Preferred (type 3) expects
 526      // two answers per question. ATTLS (having a single question of type 1) expects one
 527      // answer per question. CIQ is not using multiquestions (i.e. a question with subquestions).
 528      // Note that the type of subquestions does not really matter, it's the type of the
 529      // question itself that determines everything.
 530      $oneanswer = ($question->type == 1 || $question->type == 2) ? true : false;
 531  
 532      // COLLES Preferred (having questions of type 2) will use the radio elements with the name
 533      // like qP1, qP2 etc. COLLES Actual and ATTLS have radios like q1, q2 etc.
 534      if ($question->type == 2) {
 535          $P = "P";
 536      } else {
 537          $P = "";
 538      }
 539  
 540      echo "<colgroup colspan=\"7\"></colgroup>";
 541      echo "<tr class=\"smalltext\"><th scope=\"row\">$strresponses</th>";
 542      echo "<th scope=\"col\" class=\"hresponse\">". get_string('notyetanswered', 'survey'). "</th>";
 543      foreach ($options as $key => $val) {
 544          echo "<th scope=\"col\" class=\"hresponse\">$val</th>\n";
 545      }
 546      echo "</tr>\n";
 547  
 548      echo "<tr><th scope=\"colgroup\" colspan=\"7\">$question->intro</th></tr>\n";
 549  
 550      $subquestions = survey_get_subquestions($question);
 551  
 552      foreach ($subquestions as $q) {
 553          $qnum++;
 554          if ($oneanswer) {
 555              $rowclass = survey_question_rowclass($qnum);
 556          } else {
 557              $rowclass = survey_question_rowclass(round($qnum / 2));
 558          }
 559          if ($q->text) {
 560              $q->text = get_string($q->text, "survey");
 561          }
 562  
 563          echo "<tr class=\"$rowclass rblock\">";
 564          if ($oneanswer) {
 565              echo "<th scope=\"row\" class=\"optioncell\">";
 566              echo "<b class=\"qnumtopcell\">$qnum</b> &nbsp; ";
 567              echo $q->text ."</th>\n";
 568  
 569              $default = get_accesshide($strdefault);
 570              echo "<td class=\"whitecell\"><label for=\"q$P$q->id\"><input type=\"radio\" name=\"q$P$q->id\" id=\"q$P" . $q->id . "_D\" value=\"0\" checked=\"checked\" data-survey-default=\"true\" />$default</label></td>";
 571  
 572              for ($i=1;$i<=$numoptions;$i++) {
 573                  $hiddentext = get_accesshide($options[$i-1]);
 574                  $id = "q$P" . $q->id . "_$i";
 575                  echo "<td><label for=\"$id\"><input type=\"radio\" name=\"q$P$q->id\" id=\"$id\" value=\"$i\" />$hiddentext</label></td>";
 576              }
 577          } else {
 578              echo "<th scope=\"row\" class=\"optioncell\">";
 579              echo "<b class=\"qnumtopcell\">$qnum</b> &nbsp; ";
 580              $qnum++;
 581              echo "<span class=\"preferthat\">$stripreferthat</span> &nbsp; ";
 582              echo "<span class=\"option\">$q->text</span></th>\n";
 583  
 584              $default = get_accesshide($strdefault);
 585              echo '<td class="whitecell"><label for="qP'.$q->id.'"><input type="radio" name="qP'.$q->id.'" id="qP'.$q->id.'" value="0" checked="checked" data-survey-default="true" />'.$default.'</label></td>';
 586  
 587  
 588              for ($i=1;$i<=$numoptions;$i++) {
 589                  $hiddentext = get_accesshide($options[$i-1]);
 590                  $id = "qP" . $q->id . "_$i";
 591                  echo "<td><label for=\"$id\"><input type=\"radio\" name=\"qP$q->id\" id=\"$id\" value=\"$i\" />$hiddentext</label></td>";
 592              }
 593              echo "</tr>";
 594  
 595              echo "<tr class=\"$rowclass rblock\">";
 596              echo "<th scope=\"row\" class=\"optioncell\">";
 597              echo "<b class=\"qnumtopcell\">$qnum</b> &nbsp; ";
 598              echo "<span class=\"foundthat\">$strifoundthat</span> &nbsp; ";
 599              echo "<span class=\"option\">$q->text</span></th>\n";
 600  
 601              $default = get_accesshide($strdefault);
 602              echo '<td class="whitecell"><label for="q'. $q->id .'"><input type="radio" name="q'.$q->id. '" id="q'. $q->id .'" value="0" checked="checked" data-survey-default="true" />'.$default.'</label></td>';
 603  
 604              for ($i=1;$i<=$numoptions;$i++) {
 605                  $hiddentext = get_accesshide($options[$i-1]);
 606                  $id = "q" . $q->id . "_$i";
 607                  echo "<td><label for=\"$id\"><input type=\"radio\" name=\"q$q->id\" id=\"$id\" value=\"$i\" />$hiddentext</label></td>";
 608              }
 609          }
 610          echo "</tr>\n";
 611      }
 612      echo "</table>";
 613  }
 614  
 615  
 616  /**
 617   * @global object
 618   * @global int
 619   * @param object $question
 620   */
 621  function survey_print_single($question) {
 622      global $DB, $qnum, $OUTPUT;
 623  
 624      $rowclass = survey_question_rowclass(0);
 625  
 626      $qnum++;
 627  
 628      echo "<br />\n";
 629      echo "<table width=\"90%\" cellpadding=\"4\" cellspacing=\"0\">\n";
 630      echo "<tr class=\"$rowclass\">";
 631      echo "<th scope=\"row\" class=\"optioncell\"><label for=\"q$question->id\"><b class=\"qnumtopcell\">$qnum</b> &nbsp; ";
 632      echo "<span class=\"questioncell\">$question->text</span></label></th>\n";
 633      echo "<td class=\"questioncell smalltext\">\n";
 634  
 635  
 636      if ($question->type == 0) {           // Plain text field
 637          echo "<textarea rows=\"3\" cols=\"30\" class=\"form-control\" name=\"q$question->id\" id=\"q$question->id\">$question->options</textarea>";
 638  
 639      } else if ($question->type > 0) {     // Choose one of a number
 640          $strchoose = get_string("choose");
 641          echo "<select name=\"q$question->id\" id=\"q$question->id\" class=\"custom-select\">";
 642          echo "<option value=\"0\" selected=\"selected\">$strchoose...</option>";
 643          $options = explode( ",", $question->options);
 644          foreach ($options as $key => $val) {
 645              $key++;
 646              echo "<option value=\"$key\">$val</option>";
 647          }
 648          echo "</select>";
 649  
 650      } else if ($question->type < 0) {     // Choose several of a number
 651          $options = explode( ",", $question->options);
 652          echo $OUTPUT->notification("This question type not supported yet");
 653      }
 654  
 655      echo "</td></tr></table>";
 656  
 657  }
 658  
 659  /**
 660   *
 661   * @param int $qnum
 662   * @return string
 663   */
 664  function survey_question_rowclass($qnum) {
 665  
 666      if ($qnum) {
 667          return $qnum % 2 ? 'r0' : 'r1';
 668      } else {
 669          return 'r0';
 670      }
 671  }
 672  
 673  /**
 674   * @global object
 675   * @global int
 676   * @global int
 677   * @param string $url
 678   */
 679  function survey_print_graph($url) {
 680      global $CFG, $SURVEY_GHEIGHT, $SURVEY_GWIDTH;
 681  
 682      echo "<img class='resultgraph' height=\"$SURVEY_GHEIGHT\" width=\"$SURVEY_GWIDTH\"".
 683           " src=\"$CFG->wwwroot/mod/survey/graph.php?$url\" alt=\"".get_string("surveygraph", "survey")."\" />";
 684  }
 685  
 686  /**
 687   * List the actions that correspond to a view of this module.
 688   * This is used by the participation report.
 689   *
 690   * Note: This is not used by new logging system. Event with
 691   *       crud = 'r' and edulevel = LEVEL_PARTICIPATING will
 692   *       be considered as view action.
 693   *
 694   * @return array
 695   */
 696  function survey_get_view_actions() {
 697      return array('download','view all','view form','view graph','view report');
 698  }
 699  
 700  /**
 701   * List the actions that correspond to a post of this module.
 702   * This is used by the participation report.
 703   *
 704   * Note: This is not used by new logging system. Event with
 705   *       crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
 706   *       will be considered as post action.
 707   *
 708   * @return array
 709   */
 710  function survey_get_post_actions() {
 711      return array('submit');
 712  }
 713  
 714  
 715  /**
 716   * Implementation of the function for printing the form elements that control
 717   * whether the course reset functionality affects the survey.
 718   *
 719   * @param object $mform form passed by reference
 720   */
 721  function survey_reset_course_form_definition(&$mform) {
 722      $mform->addElement('header', 'surveyheader', get_string('modulenameplural', 'survey'));
 723      $mform->addElement('checkbox', 'reset_survey_answers', get_string('deleteallanswers','survey'));
 724      $mform->addElement('checkbox', 'reset_survey_analysis', get_string('deleteanalysis','survey'));
 725      $mform->disabledIf('reset_survey_analysis', 'reset_survey_answers', 'checked');
 726  }
 727  
 728  /**
 729   * Course reset form defaults.
 730   * @return array
 731   */
 732  function survey_reset_course_form_defaults($course) {
 733      return array('reset_survey_answers'=>1, 'reset_survey_analysis'=>1);
 734  }
 735  
 736  /**
 737   * Actual implementation of the reset course functionality, delete all the
 738   * survey responses for course $data->courseid.
 739   *
 740   * @global object
 741   * @param $data the data submitted from the reset course.
 742   * @return array status array
 743   */
 744  function survey_reset_userdata($data) {
 745      global $DB;
 746  
 747      $componentstr = get_string('modulenameplural', 'survey');
 748      $status = array();
 749  
 750      $surveyssql = "SELECT ch.id
 751                       FROM {survey} ch
 752                      WHERE ch.course=?";
 753      $params = array($data->courseid);
 754  
 755      if (!empty($data->reset_survey_answers)) {
 756          $DB->delete_records_select('survey_answers', "survey IN ($surveyssql)", $params);
 757          $DB->delete_records_select('survey_analysis', "survey IN ($surveyssql)", $params);
 758          $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallanswers', 'survey'), 'error'=>false);
 759      }
 760  
 761      if (!empty($data->reset_survey_analysis)) {
 762          $DB->delete_records_select('survey_analysis', "survey IN ($surveyssql)", $params);
 763          $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallanswers', 'survey'), 'error'=>false);
 764      }
 765  
 766      // No date shifting.
 767      // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
 768      // See MDL-9367.
 769  
 770      return $status;
 771  }
 772  
 773  /**
 774   * @uses FEATURE_GROUPS
 775   * @uses FEATURE_GROUPINGS
 776   * @uses FEATURE_MOD_INTRO
 777   * @uses FEATURE_COMPLETION_TRACKS_VIEWS
 778   * @uses FEATURE_GRADE_HAS_GRADE
 779   * @uses FEATURE_GRADE_OUTCOMES
 780   * @param string $feature FEATURE_xx constant for requested feature
 781   * @return mixed True if module supports feature, false if not, null if doesn't know
 782   */
 783  function survey_supports($feature) {
 784      switch($feature) {
 785          case FEATURE_GROUPS:                  return true;
 786          case FEATURE_GROUPINGS:               return true;
 787          case FEATURE_MOD_INTRO:               return true;
 788          case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
 789          case FEATURE_COMPLETION_HAS_RULES:    return true;
 790          case FEATURE_GRADE_HAS_GRADE:         return false;
 791          case FEATURE_GRADE_OUTCOMES:          return false;
 792          case FEATURE_BACKUP_MOODLE2:          return true;
 793          case FEATURE_SHOW_DESCRIPTION:        return true;
 794  
 795          default: return null;
 796      }
 797  }
 798  
 799  /**
 800   * This function extends the settings navigation block for the site.
 801   *
 802   * It is safe to rely on PAGE here as we will only ever be within the module
 803   * context when this is called
 804   *
 805   * @param navigation_node $settings
 806   * @param navigation_node $surveynode
 807   */
 808  function survey_extend_settings_navigation($settings, $surveynode) {
 809      global $PAGE;
 810  
 811      if (has_capability('mod/survey:readresponses', $PAGE->cm->context)) {
 812          $responsesnode = $surveynode->add(get_string("responsereports", "survey"));
 813  
 814          $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'summary'));
 815          $responsesnode->add(get_string("summary", "survey"), $url);
 816  
 817          $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'scales'));
 818          $responsesnode->add(get_string("scales", "survey"), $url);
 819  
 820          $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'questions'));
 821          $responsesnode->add(get_string("question", "survey"), $url);
 822  
 823          $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'students'));
 824          $responsesnode->add(get_string('participants'), $url);
 825  
 826          if (has_capability('mod/survey:download', $PAGE->cm->context)) {
 827              $url = new moodle_url('/mod/survey/report.php', array('id' => $PAGE->cm->id, 'action'=>'download'));
 828              $surveynode->add(get_string('downloadresults', 'survey'), $url);
 829          }
 830      }
 831  }
 832  
 833  /**
 834   * Return a list of page types
 835   * @param string $pagetype current page type
 836   * @param stdClass $parentcontext Block's parent context
 837   * @param stdClass $currentcontext Current context of block
 838   */
 839  function survey_page_type_list($pagetype, $parentcontext, $currentcontext) {
 840      $module_pagetype = array('mod-survey-*'=>get_string('page-mod-survey-x', 'survey'));
 841      return $module_pagetype;
 842  }
 843  
 844  /**
 845   * Mark the activity completed (if required) and trigger the course_module_viewed event.
 846   *
 847   * @param  stdClass $survey     survey object
 848   * @param  stdClass $course     course object
 849   * @param  stdClass $cm         course module object
 850   * @param  stdClass $context    context object
 851   * @param  string $viewed       which page viewed
 852   * @since Moodle 3.0
 853   */
 854  function survey_view($survey, $course, $cm, $context, $viewed) {
 855  
 856      // Trigger course_module_viewed event.
 857      $params = array(
 858          'context' => $context,
 859          'objectid' => $survey->id,
 860          'courseid' => $course->id,
 861          'other' => array('viewed' => $viewed)
 862      );
 863  
 864      $event = \mod_survey\event\course_module_viewed::create($params);
 865      $event->add_record_snapshot('course_modules', $cm);
 866      $event->add_record_snapshot('course', $course);
 867      $event->add_record_snapshot('survey', $survey);
 868      $event->trigger();
 869  
 870      // Completion.
 871      $completion = new completion_info($course);
 872      $completion->set_module_viewed($cm);
 873  }
 874  
 875  /**
 876   * Helper function for ordering a set of questions by the given ids.
 877   *
 878   * @param  array $questions     array of questions objects
 879   * @param  array $questionorder array of questions ids indicating the correct order
 880   * @return array                list of questions ordered
 881   * @since Moodle 3.0
 882   */
 883  function survey_order_questions($questions, $questionorder) {
 884  
 885      $finalquestions = array();
 886      foreach ($questionorder as $qid) {
 887          $finalquestions[] = $questions[$qid];
 888      }
 889      return $finalquestions;
 890  }
 891  
 892  /**
 893   * Translate the question texts and options.
 894   *
 895   * @param  stdClass $question question object
 896   * @return stdClass question object with all the text fields translated
 897   * @since Moodle 3.0
 898   */
 899  function survey_translate_question($question) {
 900  
 901      if ($question->text) {
 902          $question->text = get_string($question->text, "survey");
 903      }
 904  
 905      if ($question->shorttext) {
 906          $question->shorttext = get_string($question->shorttext, "survey");
 907      }
 908  
 909      if ($question->intro) {
 910          $question->intro = get_string($question->intro, "survey");
 911      }
 912  
 913      if ($question->options) {
 914          $question->options = get_string($question->options, "survey");
 915      }
 916      return $question;
 917  }
 918  
 919  /**
 920   * Returns the questions for a survey (ordered).
 921   *
 922   * @param  stdClass $survey survey object
 923   * @return array list of questions ordered
 924   * @since Moodle 3.0
 925   * @throws  moodle_exception
 926   */
 927  function survey_get_questions($survey) {
 928      global $DB;
 929  
 930      $questionids = explode(',', $survey->questions);
 931      if (! $questions = $DB->get_records_list("survey_questions", "id", $questionids)) {
 932          throw new moodle_exception('cannotfindquestion', 'survey');
 933      }
 934  
 935      return survey_order_questions($questions, $questionids);
 936  }
 937  
 938  /**
 939   * Returns subquestions for a given question (ordered).
 940   *
 941   * @param  stdClass $question questin object
 942   * @return array list of subquestions ordered
 943   * @since Moodle 3.0
 944   */
 945  function survey_get_subquestions($question) {
 946      global $DB;
 947  
 948      $questionids = explode(',', $question->multi);
 949      $questions = $DB->get_records_list("survey_questions", "id", $questionids);
 950  
 951      return survey_order_questions($questions, $questionids);
 952  }
 953  
 954  /**
 955   * Save the answer for the given survey
 956   *
 957   * @param  stdClass $survey   a survey object
 958   * @param  array $answersrawdata the answers to be saved
 959   * @param  stdClass $course   a course object (required for trigger the submitted event)
 960   * @param  stdClass $context  a context object (required for trigger the submitted event)
 961   * @since Moodle 3.0
 962   */
 963  function survey_save_answers($survey, $answersrawdata, $course, $context) {
 964      global $DB, $USER;
 965  
 966      $answers = array();
 967  
 968      // Sort through the data and arrange it.
 969      // This is necessary because some of the questions may have two answers, eg Question 1 -> 1 and P1.
 970      foreach ($answersrawdata as $key => $val) {
 971          if ($key != "userid" && $key != "id") {
 972              if (substr($key, 0, 1) == "q") {
 973                  $key = clean_param(substr($key, 1), PARAM_ALPHANUM);   // Keep everything but the 'q', number or P number.
 974              }
 975              if (substr($key, 0, 1) == "P") {
 976                  $realkey = (int) substr($key, 1);
 977                  $answers[$realkey][1] = $val;
 978              } else {
 979                  $answers[$key][0] = $val;
 980              }
 981          }
 982      }
 983  
 984      // Now store the data.
 985      $timenow = time();
 986      $answerstoinsert = array();
 987      foreach ($answers as $key => $val) {
 988          if ($key != 'sesskey') {
 989              $newdata = new stdClass();
 990              $newdata->time = $timenow;
 991              $newdata->userid = $USER->id;
 992              $newdata->survey = $survey->id;
 993              $newdata->question = $key;
 994              if (!empty($val[0])) {
 995                  $newdata->answer1 = $val[0];
 996              } else {
 997                  $newdata->answer1 = "";
 998              }
 999              if (!empty($val[1])) {
1000                  $newdata->answer2 = $val[1];
1001              } else {
1002                  $newdata->answer2 = "";
1003              }
1004  
1005              $answerstoinsert[] = $newdata;
1006          }
1007      }
1008  
1009      if (!empty($answerstoinsert)) {
1010          $DB->insert_records("survey_answers", $answerstoinsert);
1011      }
1012  
1013      // Update completion state.
1014      $cm = get_coursemodule_from_instance('survey', $survey->id, $course->id);
1015      $completion = new completion_info($course);
1016      if (isloggedin() && !isguestuser() && $completion->is_enabled($cm) && $survey->completionsubmit) {
1017          $completion->update_state($cm, COMPLETION_COMPLETE);
1018      }
1019  
1020      $params = array(
1021          'context' => $context,
1022          'courseid' => $course->id,
1023          'other' => array('surveyid' => $survey->id)
1024      );
1025      $event = \mod_survey\event\response_submitted::create($params);
1026      $event->trigger();
1027  }
1028  
1029  /**
1030   * Obtains the automatic completion state for this survey based on the condition
1031   * in feedback settings.
1032   *
1033   * @param object $course Course
1034   * @param object $cm Course-module
1035   * @param int $userid User ID
1036   * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1037   * @return bool True if completed, false if not, $type if conditions not set.
1038   */
1039  function survey_get_completion_state($course, $cm, $userid, $type) {
1040      global $DB;
1041  
1042      // Get survey details.
1043      $survey = $DB->get_record('survey', array('id' => $cm->instance), '*', MUST_EXIST);
1044  
1045      // If completion option is enabled, evaluate it and return true/false.
1046      if ($survey->completionsubmit) {
1047          $params = array('userid' => $userid, 'survey' => $survey->id);
1048          return $DB->record_exists('survey_answers', $params);
1049      } else {
1050          // Completion option is not enabled so just return $type.
1051          return $type;
1052      }
1053  }
1054  
1055  /**
1056   * Check if the module has any update that affects the current user since a given time.
1057   *
1058   * @param  cm_info $cm course module data
1059   * @param  int $from the time to check updates from
1060   * @param  array $filter  if we need to check only specific updates
1061   * @return stdClass an object with the different type of areas indicating if they were updated or not
1062   * @since Moodle 3.2
1063   */
1064  function survey_check_updates_since(cm_info $cm, $from, $filter = array()) {
1065      global $DB, $USER;
1066  
1067      $updates = new stdClass();
1068      if (!has_capability('mod/survey:participate', $cm->context)) {
1069          return $updates;
1070      }
1071      $updates = course_check_module_updates_since($cm, $from, array(), $filter);
1072  
1073      $updates->answers = (object) array('updated' => false);
1074      $select = 'survey = ? AND userid = ? AND time > ?';
1075      $params = array($cm->instance, $USER->id, $from);
1076      $answers = $DB->get_records_select('survey_answers', $select, $params, '', 'id');
1077      if (!empty($answers)) {
1078          $updates->answers->updated = true;
1079          $updates->answers->itemids = array_keys($answers);
1080      }
1081  
1082      // Now, teachers should see other students updates.
1083      if (has_capability('mod/survey:readresponses', $cm->context)) {
1084          $select = 'survey = ? AND time > ?';
1085          $params = array($cm->instance, $from);
1086  
1087          if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
1088              $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
1089              if (empty($groupusers)) {
1090                  return $updates;
1091              }
1092              list($insql, $inparams) = $DB->get_in_or_equal($groupusers);
1093              $select .= ' AND userid ' . $insql;
1094              $params = array_merge($params, $inparams);
1095          }
1096  
1097          $updates->useranswers = (object) array('updated' => false);
1098          $answers = $DB->get_records_select('survey_answers', $select, $params, '', 'id');
1099          if (!empty($answers)) {
1100              $updates->useranswers->updated = true;
1101              $updates->useranswers->itemids = array_keys($answers);
1102          }
1103      }
1104      return $updates;
1105  }
1106  
1107  /**
1108   * This function receives a calendar event and returns the action associated with it, or null if there is none.
1109   *
1110   * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
1111   * is not displayed on the block.
1112   *
1113   * @param calendar_event $event
1114   * @param \core_calendar\action_factory $factory
1115   * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
1116   * @return \core_calendar\local\event\entities\action_interface|null
1117   */
1118  function mod_survey_core_calendar_provide_event_action(calendar_event $event,
1119                                                        \core_calendar\action_factory $factory,
1120                                                        int $userid = 0) {
1121      global $USER;
1122  
1123      if (empty($userid)) {
1124          $userid = $USER->id;
1125      }
1126  
1127      $cm = get_fast_modinfo($event->courseid, $userid)->instances['survey'][$event->instance];
1128      $context = context_module::instance($cm->id);
1129  
1130      if (!has_capability('mod/survey:participate', $context, $userid)) {
1131          return null;
1132      }
1133  
1134      $completion = new \completion_info($cm->get_course());
1135  
1136      $completiondata = $completion->get_data($cm, false, $userid);
1137  
1138      if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
1139          return null;
1140      }
1141  
1142      return $factory->create_instance(
1143          get_string('view'),
1144          new \moodle_url('/mod/survey/view.php', ['id' => $cm->id]),
1145          1,
1146          true
1147      );
1148  }
1149  
1150  /**
1151   * Add a get_coursemodule_info function in case any survey type wants to add 'extra' information
1152   * for the course (see resource).
1153   *
1154   * Given a course_module object, this function returns any "extra" information that may be needed
1155   * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
1156   *
1157   * @param stdClass $coursemodule The coursemodule object (record).
1158   * @return cached_cm_info An object on information that the courses
1159   *                        will know about (most noticeably, an icon).
1160   */
1161  function survey_get_coursemodule_info($coursemodule) {
1162      global $DB;
1163  
1164      $dbparams = ['id' => $coursemodule->instance];
1165      $fields = 'id, name, intro, introformat, completionsubmit';
1166      if (!$survey = $DB->get_record('survey', $dbparams, $fields)) {
1167          return false;
1168      }
1169  
1170      $result = new cached_cm_info();
1171      $result->name = $survey->name;
1172  
1173      if ($coursemodule->showdescription) {
1174          // Convert intro to html. Do not filter cached version, filters run at display time.
1175          $result->content = format_module_intro('survey', $survey, $coursemodule->id, false);
1176      }
1177  
1178      // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
1179      if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
1180          $result->customdata['customcompletionrules']['completionsubmit'] = $survey->completionsubmit;
1181      }
1182  
1183      return $result;
1184  }
1185  
1186  /**
1187   * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
1188   *
1189   * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
1190   * @return array $descriptions the array of descriptions for the custom rules.
1191   */
1192  function mod_survey_get_completion_active_rule_descriptions($cm) {
1193      // Values will be present in cm_info, and we assume these are up to date.
1194      if (empty($cm->customdata['customcompletionrules'])
1195          || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
1196          return [];
1197      }
1198  
1199      $descriptions = [];
1200      foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
1201          switch ($key) {
1202              case 'completionsubmit':
1203                  if (!empty($val)) {
1204                      $descriptions[] = get_string('completionsubmit', 'survey');
1205                  }
1206                  break;
1207              default:
1208                  break;
1209          }
1210      }
1211      return $descriptions;
1212  }