Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

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