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.

Differences Between: [Versions 311 and 401] [Versions 311 and 402] [Versions 311 and 403]

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  /**
  18   * Survey external API
  19   *
  20   * @package    mod_survey
  21   * @category   external
  22   * @copyright  2015 Juan Leyva <juan@moodle.com>
  23   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  24   * @since      Moodle 3.0
  25   */
  26  
  27  defined('MOODLE_INTERNAL') || die;
  28  
  29  require_once($CFG->libdir . '/externallib.php');
  30  require_once($CFG->dirroot . '/mod/survey/lib.php');
  31  
  32  /**
  33   * Survey external functions
  34   *
  35   * @package    mod_survey
  36   * @category   external
  37   * @copyright  2015 Juan Leyva <juan@moodle.com>
  38   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  39   * @since      Moodle 3.0
  40   */
  41  class mod_survey_external extends external_api {
  42  
  43      /**
  44       * Describes the parameters for get_surveys_by_courses.
  45       *
  46       * @return external_function_parameters
  47       * @since Moodle 3.0
  48       */
  49      public static function get_surveys_by_courses_parameters() {
  50          return new external_function_parameters (
  51              array(
  52                  'courseids' => new external_multiple_structure(
  53                      new external_value(PARAM_INT, 'course id'), 'Array of course ids', VALUE_DEFAULT, array()
  54                  ),
  55              )
  56          );
  57      }
  58  
  59      /**
  60       * Returns a list of surveys in a provided list of courses,
  61       * if no list is provided all surveys that the user can view will be returned.
  62       *
  63       * @param array $courseids the course ids
  64       * @return array of surveys details
  65       * @since Moodle 3.0
  66       */
  67      public static function get_surveys_by_courses($courseids = array()) {
  68          global $CFG, $USER, $DB;
  69  
  70          $returnedsurveys = array();
  71          $warnings = array();
  72  
  73          $params = self::validate_parameters(self::get_surveys_by_courses_parameters(), array('courseids' => $courseids));
  74  
  75          $mycourses = array();
  76          if (empty($params['courseids'])) {
  77              $mycourses = enrol_get_my_courses();
  78              $params['courseids'] = array_keys($mycourses);
  79          }
  80  
  81          // Ensure there are courseids to loop through.
  82          if (!empty($params['courseids'])) {
  83  
  84              list($courses, $warnings) = external_util::validate_courses($params['courseids'], $mycourses);
  85  
  86              // Get the surveys in this course, this function checks users visibility permissions.
  87              // We can avoid then additional validate_context calls.
  88              $surveys = get_all_instances_in_courses("survey", $courses);
  89              foreach ($surveys as $survey) {
  90                  $context = context_module::instance($survey->coursemodule);
  91                  // Entry to return.
  92                  $surveydetails = array();
  93                  // First, we return information that any user can see in the web interface.
  94                  $surveydetails['id'] = $survey->id;
  95                  $surveydetails['coursemodule']      = $survey->coursemodule;
  96                  $surveydetails['course']            = $survey->course;
  97                  $surveydetails['name']              = external_format_string($survey->name, $context->id);
  98  
  99                  if (has_capability('mod/survey:participate', $context)) {
 100                      $trimmedintro = trim($survey->intro);
 101                      if (empty($trimmedintro)) {
 102                          $tempo = $DB->get_field("survey", "intro", array("id" => $survey->template));
 103                          $survey->intro = get_string($tempo, "survey");
 104                      }
 105  
 106                      // Format intro.
 107                      $options = array('noclean' => true);
 108                      list($surveydetails['intro'], $surveydetails['introformat']) =
 109                          external_format_text($survey->intro, $survey->introformat, $context->id, 'mod_survey', 'intro', null,
 110                              $options);
 111                      $surveydetails['introfiles'] = external_util::get_area_files($context->id, 'mod_survey', 'intro', false,
 112                                                                                      false);
 113  
 114                      $surveydetails['template']  = $survey->template;
 115                      $surveydetails['days']      = $survey->days;
 116                      $surveydetails['questions'] = $survey->questions;
 117                      $surveydetails['surveydone'] = survey_already_done($survey->id, $USER->id) ? 1 : 0;
 118  
 119                  }
 120  
 121                  if (has_capability('moodle/course:manageactivities', $context)) {
 122                      $surveydetails['timecreated']   = $survey->timecreated;
 123                      $surveydetails['timemodified']  = $survey->timemodified;
 124                      $surveydetails['section']       = $survey->section;
 125                      $surveydetails['visible']       = $survey->visible;
 126                      $surveydetails['groupmode']     = $survey->groupmode;
 127                      $surveydetails['groupingid']    = $survey->groupingid;
 128                  }
 129                  $returnedsurveys[] = $surveydetails;
 130              }
 131          }
 132          $result = array();
 133          $result['surveys'] = $returnedsurveys;
 134          $result['warnings'] = $warnings;
 135          return $result;
 136      }
 137  
 138      /**
 139       * Describes the get_surveys_by_courses return value.
 140       *
 141       * @return external_single_structure
 142       * @since Moodle 3.0
 143       */
 144      public static function get_surveys_by_courses_returns() {
 145          return new external_single_structure(
 146              array(
 147                  'surveys' => new external_multiple_structure(
 148                      new external_single_structure(
 149                          array(
 150                              'id' => new external_value(PARAM_INT, 'Survey id'),
 151                              'coursemodule' => new external_value(PARAM_INT, 'Course module id'),
 152                              'course' => new external_value(PARAM_INT, 'Course id'),
 153                              'name' => new external_value(PARAM_RAW, 'Survey name'),
 154                              'intro' => new external_value(PARAM_RAW, 'The Survey intro', VALUE_OPTIONAL),
 155                              'introformat' => new external_format_value('intro', VALUE_OPTIONAL),
 156                              'introfiles' => new external_files('Files in the introduction text', VALUE_OPTIONAL),
 157                              'template' => new external_value(PARAM_INT, 'Survey type', VALUE_OPTIONAL),
 158                              'days' => new external_value(PARAM_INT, 'Days', VALUE_OPTIONAL),
 159                              'questions' => new external_value(PARAM_RAW, 'Question ids', VALUE_OPTIONAL),
 160                              'surveydone' => new external_value(PARAM_INT, 'Did I finish the survey?', VALUE_OPTIONAL),
 161                              'timecreated' => new external_value(PARAM_INT, 'Time of creation', VALUE_OPTIONAL),
 162                              'timemodified' => new external_value(PARAM_INT, 'Time of last modification', VALUE_OPTIONAL),
 163                              'section' => new external_value(PARAM_INT, 'Course section id', VALUE_OPTIONAL),
 164                              'visible' => new external_value(PARAM_INT, 'Visible', VALUE_OPTIONAL),
 165                              'groupmode' => new external_value(PARAM_INT, 'Group mode', VALUE_OPTIONAL),
 166                              'groupingid' => new external_value(PARAM_INT, 'Group id', VALUE_OPTIONAL),
 167                          ), 'Surveys'
 168                      )
 169                  ),
 170                  'warnings' => new external_warnings(),
 171              )
 172          );
 173      }
 174  
 175      /**
 176       * Returns description of method parameters
 177       *
 178       * @return external_function_parameters
 179       * @since Moodle 3.0
 180       */
 181      public static function view_survey_parameters() {
 182          return new external_function_parameters(
 183              array(
 184                  'surveyid' => new external_value(PARAM_INT, 'survey instance id')
 185              )
 186          );
 187      }
 188  
 189      /**
 190       * Trigger the course module viewed event and update the module completion status.
 191       *
 192       * @param int $surveyid the survey instance id
 193       * @return array of warnings and status result
 194       * @since Moodle 3.0
 195       * @throws moodle_exception
 196       */
 197      public static function view_survey($surveyid) {
 198          global $DB, $USER;
 199  
 200          $params = self::validate_parameters(self::view_survey_parameters(),
 201                                              array(
 202                                                  'surveyid' => $surveyid
 203                                              ));
 204          $warnings = array();
 205  
 206          // Request and permission validation.
 207          $survey = $DB->get_record('survey', array('id' => $params['surveyid']), '*', MUST_EXIST);
 208          list($course, $cm) = get_course_and_cm_from_instance($survey, 'survey');
 209  
 210          $context = context_module::instance($cm->id);
 211          self::validate_context($context);
 212          require_capability('mod/survey:participate', $context);
 213  
 214          $viewed = survey_already_done($survey->id, $USER->id) ? 'graph' : 'form';
 215  
 216          // Trigger course_module_viewed event and completion.
 217          survey_view($survey, $course, $cm, $context, $viewed);
 218  
 219          $result = array();
 220          $result['status'] = true;
 221          $result['warnings'] = $warnings;
 222          return $result;
 223      }
 224  
 225      /**
 226       * Returns description of method result value
 227       *
 228       * @return external_description
 229       * @since Moodle 3.0
 230       */
 231      public static function view_survey_returns() {
 232          return new external_single_structure(
 233              array(
 234                  'status' => new external_value(PARAM_BOOL, 'status: true if success'),
 235                  'warnings' => new external_warnings()
 236              )
 237          );
 238      }
 239  
 240      /**
 241       * Returns description of method parameters
 242       *
 243       * @return external_function_parameters
 244       * @since Moodle 3.0
 245       */
 246      public static function get_questions_parameters() {
 247          return new external_function_parameters(
 248              array(
 249                  'surveyid' => new external_value(PARAM_INT, 'survey instance id')
 250              )
 251          );
 252      }
 253  
 254      /**
 255       * Get the complete list of questions for the survey, including subquestions.
 256       *
 257       * @param int $surveyid the survey instance id
 258       * @return array of warnings and the question list
 259       * @since Moodle 3.0
 260       * @throws moodle_exception
 261       */
 262      public static function get_questions($surveyid) {
 263          global $DB, $USER;
 264  
 265          $params = self::validate_parameters(self::get_questions_parameters(),
 266                                              array(
 267                                                  'surveyid' => $surveyid
 268                                              ));
 269          $warnings = array();
 270  
 271          // Request and permission validation.
 272          $survey = $DB->get_record('survey', array('id' => $params['surveyid']), '*', MUST_EXIST);
 273          list($course, $cm) = get_course_and_cm_from_instance($survey, 'survey');
 274  
 275          $context = context_module::instance($cm->id);
 276          self::validate_context($context);
 277          require_capability('mod/survey:participate', $context);
 278  
 279          $mainquestions = survey_get_questions($survey);
 280  
 281          foreach ($mainquestions as $question) {
 282              if ($question->type >= 0) {
 283                  // Parent is used in subquestions.
 284                  $question->parent = 0;
 285                  $questions[] = survey_translate_question($question);
 286  
 287                  // Check if the question has subquestions.
 288                  if ($question->multi) {
 289                      $subquestions = survey_get_subquestions($question);
 290                      foreach ($subquestions as $sq) {
 291                          $sq->parent = $question->id;
 292                          $questions[] = survey_translate_question($sq);
 293                      }
 294                  }
 295              }
 296          }
 297  
 298          $result = array();
 299          $result['questions'] = $questions;
 300          $result['warnings'] = $warnings;
 301          return $result;
 302      }
 303  
 304      /**
 305       * Returns description of method result value
 306       *
 307       * @return external_description
 308       * @since Moodle 3.0
 309       */
 310      public static function get_questions_returns() {
 311          return new external_single_structure(
 312              array(
 313                  'questions' => new external_multiple_structure(
 314                      new external_single_structure(
 315                          array(
 316                              'id' => new external_value(PARAM_INT, 'Question id'),
 317                              'text' => new external_value(PARAM_RAW, 'Question text'),
 318                              'shorttext' => new external_value(PARAM_RAW, 'Question short text'),
 319                              'multi' => new external_value(PARAM_RAW, 'Subquestions ids'),
 320                              'intro' => new external_value(PARAM_RAW, 'The question intro'),
 321                              'type' => new external_value(PARAM_INT, 'Question type'),
 322                              'options' => new external_value(PARAM_RAW, 'Question options'),
 323                              'parent' => new external_value(PARAM_INT, 'Parent question (for subquestions)'),
 324                          ), 'Questions'
 325                      )
 326                  ),
 327                  'warnings' => new external_warnings()
 328              )
 329          );
 330      }
 331  
 332      /**
 333       * Describes the parameters for submit_answers.
 334       *
 335       * @return external_function_parameters
 336       * @since Moodle 3.0
 337       */
 338      public static function submit_answers_parameters() {
 339          return new external_function_parameters(
 340              array(
 341                  'surveyid' => new external_value(PARAM_INT, 'Survey id'),
 342                  'answers' => new external_multiple_structure(
 343                      new external_single_structure(
 344                          array(
 345                              'key' => new external_value(PARAM_RAW, 'Answer key'),
 346                              'value' => new external_value(PARAM_RAW, 'Answer value')
 347                          )
 348                      )
 349                  ),
 350              )
 351          );
 352      }
 353  
 354      /**
 355       * Submit the answers for a given survey.
 356       *
 357       * @param int $surveyid the survey instance id
 358       * @param array $answers the survey answers
 359       * @return array of warnings and status result
 360       * @since Moodle 3.0
 361       * @throws moodle_exception
 362       */
 363      public static function submit_answers($surveyid, $answers) {
 364          global $DB, $USER;
 365  
 366          $params = self::validate_parameters(self::submit_answers_parameters(),
 367                                              array(
 368                                                  'surveyid' => $surveyid,
 369                                                  'answers' => $answers
 370                                              ));
 371          $warnings = array();
 372  
 373          // Request and permission validation.
 374          $survey = $DB->get_record('survey', array('id' => $params['surveyid']), '*', MUST_EXIST);
 375          list($course, $cm) = get_course_and_cm_from_instance($survey, 'survey');
 376  
 377          $context = context_module::instance($cm->id);
 378          self::validate_context($context);
 379          require_capability('mod/survey:participate', $context);
 380  
 381          if (survey_already_done($survey->id, $USER->id)) {
 382              throw new moodle_exception("alreadysubmitted", "survey");
 383          }
 384  
 385          // Build the answers array. Data is cleaned inside the survey_save_answers function.
 386          $answers = array();
 387          foreach ($params['answers'] as $answer) {
 388              $key = $answer['key'];
 389              $answers[$key] = $answer['value'];
 390          }
 391  
 392          survey_save_answers($survey, $answers, $course, $context);
 393  
 394          $result = array();
 395          $result['status'] = true;
 396          $result['warnings'] = $warnings;
 397          return $result;
 398      }
 399  
 400      /**
 401       * Returns description of method result value
 402       *
 403       * @return external_description
 404       * @since Moodle 3.0
 405       */
 406      public static function submit_answers_returns() {
 407          return new external_single_structure(
 408              array(
 409                  'status' => new external_value(PARAM_BOOL, 'status: true if success'),
 410                  'warnings' => new external_warnings()
 411              )
 412          );
 413      }
 414  
 415  }