Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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
namespace mod_questionnaire\responsetype;
18
 
19
/**
20
 * Class for single response types.
21
 *
22
 * @author Mike Churchward
23
 * @copyright 2016 onward Mike Churchward (mike.churchward@poetopensource.org)
24
 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
25
 * @package mod_questionnaire
26
 */
27
class single extends responsetype {
28
    /**
29
     * Provide the necessary response data table name. Should probably always be used with late static binding 'static::' form
30
     * rather than 'self::' form to allow for class extending.
31
     *
32
     * @return string response table name.
33
     */
34
    public static function response_table() {
35
        return 'questionnaire_resp_single';
36
    }
37
 
38
    /**
39
     * Provide an array of answer objects from web form data for the question.
40
     *
41
     * @param \stdClass $responsedata All of the responsedata as an object.
42
     * @param \mod_questionnaire\question\question $question
43
     * @return array \mod_questionnaire\responsetype\answer\answer An array of answer objects.
44
     * @throws \coding_exception
45
     */
46
    public static function answers_from_webform($responsedata, $question) {
47
        $answers = [];
48
        if (isset($responsedata->{'q'.$question->id}) && isset($question->choices[$responsedata->{'q'.$question->id}])) {
49
            $record = new \stdClass();
50
            $record->responseid = $responsedata->rid;
51
            $record->questionid = $question->id;
52
            $record->choiceid = $responsedata->{'q'.$question->id};
53
            // If this choice is an "other" choice, look for the added input.
54
            if ($question->choices[$responsedata->{'q'.$question->id}]->is_other_choice()) {
55
                $cname = 'q' . $question->id .
56
                    \mod_questionnaire\question\choice::id_other_choice_name($responsedata->{'q'.$question->id});
57
                $record->value = isset($responsedata->{$cname}) ? $responsedata->{$cname} : '';
58
            }
59
            $answers[$responsedata->{'q'.$question->id}] = answer\answer::create_from_data($record);
60
        }
61
        return $answers;
62
    }
63
 
64
    /**
65
     * Provide an array of answer objects from mobile data for the question.
66
     *
67
     * @param \stdClass $responsedata All of the responsedata as an object.
68
     * @param \mod_questionnaire\question\question $question
69
     * @return array \mod_questionnaire\responsetype\answer\answer An array of answer objects.
70
     */
71
    public static function answers_from_appdata($responsedata, $question) {
72
        $answers = [];
73
        $qname = 'q'.$question->id;
74
        if (isset($responsedata->{$qname}[0]) && !empty($responsedata->{$qname}[0])) {
75
            $record = new \stdClass();
76
            $record->responseid = $responsedata->rid;
77
            $record->questionid = $question->id;
78
            $record->choiceid = $responsedata->{$qname}[0];
79
            // If this choice is an "other" choice, look for the added input.
80
            if ($question->choices[$record->choiceid]->is_other_choice()) {
81
                $cname = \mod_questionnaire\question\choice::id_other_choice_name($record->choiceid);
82
                $record->value =
83
                    isset($responsedata->{$qname}[$cname]) ? $responsedata->{$qname}[$cname] : '';
84
            } else {
85
                $record->value = '';
86
            }
87
            $answers[] = answer\answer::create_from_data($record);
88
        }
89
        return $answers;
90
    }
91
 
92
    /**
93
     * Insert a provided response to the question.
94
     *
95
     * @param object $responsedata All of the responsedata as an object.
96
     * @return int|bool - on error the subtype should call set_error and return false.
97
     */
98
    public function insert_response($responsedata) {
99
        global $DB;
100
 
101
        if (!$responsedata instanceof \mod_questionnaire\responsetype\response\response) {
102
            $response = \mod_questionnaire\responsetype\response\response::response_from_webform($responsedata, [$this->question]);
103
        } else {
104
            $response = $responsedata;
105
        }
106
 
107
        $resid = false;
108
        if (!empty($response) && isset($response->answers[$this->question->id])) {
109
            foreach ($response->answers[$this->question->id] as $answer) {
110
                if (isset($this->question->choices[$answer->choiceid])) {
111
                    if ($this->question->choices[$answer->choiceid]->is_other_choice()) {
112
                        // If no input specified, ignore this choice.
113
                        if (empty($answer->value) || preg_match("/^[\s]*$/", $answer->value)) {
114
                            continue;
115
                        }
116
                        $record = new \stdClass();
117
                        $record->response_id = $response->id;
118
                        $record->question_id = $this->question->id;
119
                        $record->choice_id = $answer->choiceid;
120
                        $record->response = clean_text($answer->value);
121
                        $DB->insert_record('questionnaire_response_other', $record);
122
                    }
123
                    // Record the choice selection.
124
                    $record = new \stdClass();
125
                    $record->response_id = $response->id;
126
                    $record->question_id = $this->question->id;
127
                    $record->choice_id = $answer->choiceid;
128
                    $resid = $DB->insert_record(static::response_table(), $record);
129
                }
130
            }
131
        }
132
        return $resid;
133
    }
134
 
135
    /**
136
     * Provide the result information for the specified result records.
137
     *
138
     * @param int|array $rids - A single response id, or array.
139
     * @param boolean $anonymous - Whether or not responses are anonymous.
140
     * @return array - Array of data records.
141
     */
142
    public function get_results($rids=false, $anonymous=false) {
143
        global $DB;
144
 
145
        $rsql = '';
146
        $params = array($this->question->id);
147
        if (!empty($rids)) {
148
            list($rsql, $rparams) = $DB->get_in_or_equal($rids);
149
            $params = array_merge($params, $rparams);
150
            $rsql = ' AND response_id ' . $rsql;
151
        }
152
 
153
        // Added qc.id to preserve original choices ordering.
154
        $sql = 'SELECT rt.id, qc.id as cid, qc.content ' .
155
               'FROM {questionnaire_quest_choice} qc, ' .
156
               '{'.static::response_table().'} rt ' .
157
               'WHERE qc.question_id= ? AND qc.content NOT LIKE \'!other%\' AND ' .
158
                     'rt.question_id=qc.question_id AND rt.choice_id=qc.id' . $rsql . ' ' .
159
               'ORDER BY qc.id';
160
 
161
        $rows = $DB->get_records_sql($sql, $params);
162
 
163
        // Handle 'other...'.
164
        $sql = 'SELECT rt.id, rt.response, qc.content ' .
165
               'FROM {questionnaire_response_other} rt, ' .
166
                    '{questionnaire_quest_choice} qc ' .
167
               'WHERE rt.question_id= ? AND rt.choice_id=qc.id' . $rsql . ' ' .
168
               'ORDER BY qc.id';
169
 
170
        if ($recs = $DB->get_records_sql($sql, $params)) {
171
            $i = 1;
172
            foreach ($recs as $rec) {
173
                $rows['other'.$i] = new \stdClass();
174
                $rows['other'.$i]->content = $rec->content;
175
                $rows['other'.$i]->response = $rec->response;
176
                $i++;
177
            }
178
        }
179
 
180
        return $rows;
181
    }
182
 
183
    /**
184
     * Provide the feedback scores for all requested response id's. This should be provided only by questions that provide feedback.
185
     * @param array $rids
186
     * @return array | boolean
187
     */
188
    public function get_feedback_scores(array $rids) {
189
        global $DB;
190
 
191
        $rsql = '';
192
        $params = [$this->question->id];
193
        if (!empty($rids)) {
194
            list($rsql, $rparams) = $DB->get_in_or_equal($rids);
195
            $params = array_merge($params, $rparams);
196
            $rsql = ' AND response_id ' . $rsql;
197
        }
198
        $params[] = 'y';
199
 
200
        $sql = 'SELECT response_id as rid, c.value AS score ' .
201
            'FROM {'.$this->response_table().'} r ' .
202
            'INNER JOIN {questionnaire_quest_choice} c ON r.choice_id = c.id ' .
203
            'WHERE r.question_id= ? ' . $rsql . ' ' .
204
            'ORDER BY response_id ASC';
205
        return $DB->get_records_sql($sql, $params);
206
    }
207
 
208
    /**
209
     * Provide a template for results screen if defined.
210
     * @param bool $pdf
211
     * @return mixed The template string or false/
212
     */
213
    public function results_template($pdf = false) {
214
        if ($pdf) {
215
            return 'mod_questionnaire/resultspdf_choice';
216
        } else {
217
            return 'mod_questionnaire/results_choice';
218
        }
219
    }
220
 
221
    /**
222
     * Return the JSON structure required for the template.
223
     *
224
     * @param bool $rids
225
     * @param string $sort
226
     * @param bool $anonymous
227
     * @return string
228
     */
229
    public function display_results($rids=false, $sort='', $anonymous=false) {
230
        global $DB;
231
 
232
        $rows = $this->get_results($rids, $anonymous);
233
        if (is_array($rids)) {
234
            $prtotal = 1;
235
        } else if (is_int($rids)) {
236
            $prtotal = 0;
237
        }
238
        $numresps = count($rids);
239
 
240
        $responsecountsql = 'SELECT COUNT(DISTINCT r.response_id) ' .
241
            'FROM {' . $this->response_table() . '} r ' .
242
            'WHERE r.question_id = ? ';
243
        $numrespondents = $DB->count_records_sql($responsecountsql, [$this->question->id]);
244
 
245
        if ($rows) {
246
            $counts = [];
247
            foreach ($rows as $idx => $row) {
248
                if (strpos($idx, 'other') === 0) {
249
                    $answer = $row->response;
250
                    $ccontent = $row->content;
251
                    $content = \mod_questionnaire\question\choice::content_other_choice_display($ccontent);
252
                    $content .= ' ' . clean_text($answer);
253
                    $textidx = $content;
254
                    $counts[$textidx] = !empty($counts[$textidx]) ? ($counts[$textidx] + 1) : 1;
255
                } else {
256
                    $contents = questionnaire_choice_values($row->content);
257
                    $textidx = $contents->text.$contents->image;
258
                    $counts[$textidx] = !empty($counts[$textidx]) ? ($counts[$textidx] + 1) : 1;
259
                }
260
            }
261
            $pagetags = $this->get_results_tags($counts, $numresps, $numrespondents, $prtotal, $sort);
262
        } else {
263
            $pagetags = new \stdClass();
264
        }
265
        return $pagetags;
266
    }
267
 
268
    /**
269
     * Return an array of answers by question/choice for the given response. Must be implemented by the subclass.
270
     * Array is indexed by question, and contains an array by choice code of selected choices.
271
     *
272
     * @param int $rid The response id.
273
     * @return array
274
     */
275
    public static function response_select($rid) {
276
        global $DB;
277
 
278
        $values = [];
279
        $sql = 'SELECT a.id, q.id as qid, q.content, c.content as ccontent, c.id as cid, o.response ' .
280
            'FROM {'.static::response_table().'} a ' .
281
            'INNER JOIN {questionnaire_question} q ON a.question_id = q.id ' .
282
            'INNER JOIN {questionnaire_quest_choice} c ON a.choice_id = c.id ' .
283
            'LEFT JOIN {questionnaire_response_other} o ON a.response_id = o.response_id AND c.id = o.choice_id ' .
284
            'WHERE a.response_id = ? ';
285
        $records = $DB->get_records_sql($sql, [$rid]);
286
        foreach ($records as $row) {
287
            $newrow['content'] = $row->content;
288
            $newrow['ccontent'] = $row->ccontent;
289
            $newrow['responses'] = [];
290
            $newrow['responses'][$row->cid] = $row->cid;
291
            if (\mod_questionnaire\question\choice::content_is_other_choice($row->ccontent)) {
292
                $newrow['responses'][\mod_questionnaire\question\choice::id_other_choice_name($row->cid)] = $row->response;
293
            }
294
            $values[$row->qid] = $newrow;
295
        }
296
 
297
        return $values;
298
    }
299
 
300
    /**
301
     * Return an array of answer objects by question for the given response id.
302
     * THIS SHOULD REPLACE response_select.
303
     *
304
     * @param int $rid The response id.
305
     * @return array array answer
306
     * @throws \dml_exception
307
     */
308
    public static function response_answers_by_question($rid) {
309
        global $DB;
310
 
311
        $answers = [];
312
        $sql = 'SELECT r.id as id, r.response_id as responseid, r.question_id as questionid, r.choice_id as choiceid, ' .
313
            'o.response as value ' .
314
            'FROM {' . static::response_table() .'} r ' .
315
            'LEFT JOIN {questionnaire_response_other} o ON r.response_id = o.response_id AND r.question_id = o.question_id AND ' .
316
            'r.choice_id = o.choice_id ' .
317
            'WHERE r.response_id = ? ';
318
        $records = $DB->get_records_sql($sql, [$rid]);
319
        foreach ($records as $record) {
320
            $answers[$record->questionid][$record->choiceid] = answer\answer::create_from_data($record);
321
        }
322
 
323
        return $answers;
324
    }
325
 
326
    /**
327
     * Return sql and params for getting responses in bulk.
328
     * @param int|array $questionnaireids One id, or an array of ids.
329
     * @param bool|int $responseid
330
     * @param bool|int $userid
331
     * @param bool|int $groupid
332
     * @param int $showincompletes
333
     * @return array
334
     * author Guy Thomas
335
     */
336
    public function get_bulk_sql($questionnaireids, $responseid = false, $userid = false, $groupid = false, $showincompletes = 0) {
337
        global $DB;
338
 
339
        $sql = $this->bulk_sql();
340
        if (($groupid !== false) && ($groupid > 0)) {
341
            $groupsql = ' INNER JOIN {groups_members} gm ON gm.groupid = ? AND gm.userid = qr.userid ';
342
            $gparams = [$groupid];
343
        } else {
344
            $groupsql = '';
345
            $gparams = [];
346
        }
347
 
348
        if (is_array($questionnaireids)) {
349
            list($qsql, $params) = $DB->get_in_or_equal($questionnaireids);
350
        } else {
351
            $qsql = ' = ? ';
352
            $params = [$questionnaireids];
353
        }
354
        if ($showincompletes == 1) {
355
            $showcompleteonly = '';
356
        } else {
357
            $showcompleteonly = 'AND qr.complete = ? ';
358
            $params[] = 'y';
359
        }
360
 
361
        $sql .= "
362
            AND qr.questionnaireid $qsql $showcompleteonly
363
      LEFT JOIN {questionnaire_response_other} qro ON qro.response_id = qr.id AND qro.choice_id = qrs.choice_id
364
      LEFT JOIN {user} u ON u.id = qr.userid
365
      $groupsql
366
        ";
367
        $params = array_merge($params, $gparams);
368
 
369
        if ($responseid) {
370
            $sql .= " WHERE qr.id = ?";
371
            $params[] = $responseid;
372
        } else if ($userid) {
373
            $sql .= " WHERE qr.userid = ?";
374
            $params[] = $userid;
375
        }
376
 
377
        return [$sql, $params];
378
    }
379
 
380
    /**
381
     * Return sql for getting responses in bulk.
382
     * @author Guy Thomas
383
     * @return string
384
     */
385
    protected function bulk_sql() {
386
        global $DB;
387
 
388
        $userfields = $this->user_fields_sql();
389
        $alias = 'qrs';
390
        $extraselect = 'qrs.choice_id, ' . $DB->sql_order_by_text('qro.response', 1000) . ' AS response, 0 AS rankvalue';
391
 
392
        return "
393
            SELECT " . $DB->sql_concat_join("'_'", ['qr.id', "'".$this->question->helpname()."'", $alias.'.id']) . " AS id,
394
                   qr.submitted, qr.complete, qr.grade, qr.userid, $userfields, qr.id AS rid, $alias.question_id,
395
                   $extraselect
396
              FROM {questionnaire_response} qr
397
              JOIN {".static::response_table()."} $alias ON $alias.response_id = qr.id
398
        ";
399
    }
400
}