Passed
Push — 1.10.x ( 90da1a...1f0c91 )
by
unknown
68:49 queued 15:43
created

SurveyManager::get_complete_survey_structure()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * Class SurveyManager
6
 * @package chamilo.survey
7
 * @author Patrick Cool <[email protected]>, Ghent University:
8
 * cleanup, refactoring and rewriting large parts (if not all) of the code
9
 * @author Julio Montoya <[email protected]>, Personality Test modification
10
 * and rewriting large parts of the code
11
 * @author cfasanando
12
 * @todo move this file to inc/lib
13
 * @todo use consistent naming for the functions (save vs store for instance)
14
 */
15
class SurveyManager
16
{
17
    /**
18
     * @param $code
19
     *
20
     * @return string
21
     */
22
    public static function generate_unique_code($code)
23
    {
24
        if (empty($code)) {
25
            return false;
26
        }
27
        $course_id = api_get_course_int_id();
28
        $table_survey = Database::get_course_table(TABLE_SURVEY);
29
        $code = Database::escape_string($code);
30
        $num = 0;
31
        $new_code = $code;
32
        while (true) {
33
            $sql = "SELECT * FROM $table_survey
34
                    WHERE code = '$new_code' AND c_id = $course_id";
35
            $result = Database::query($sql);
36
            if (Database::num_rows($result)) {
37
                $num++;
38
                $new_code = $code . $num;
39
            } else {
40
                break;
41
            }
42
        }
43
        return $code.$num;
44
    }
45
46
    /**
47
     * Deletes all survey invitations of a user
48
     * @param int $user_id
49
     *
50
     * @return boolean
51
     * @assert ('') === false
52
     */
53
    public static function delete_all_survey_invitations_by_user($user_id)
54
    {
55
        $user_id = intval($user_id);
56
57
        if (empty($user_id)) {
58
            return false;
59
        }
60
        $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
61
        $table_survey = Database :: get_course_table(TABLE_SURVEY);
62
63
        $sql = "SELECT survey_invitation_id, survey_code
64
                FROM $table_survey_invitation WHERE user = '$user_id' AND c_id <> 0 ";
65
        $result = Database::query($sql);
66
        while ($row = Database::fetch_array($result ,'ASSOC')){
67
            $survey_invitation_id = $row['survey_invitation_id'];
68
            $survey_code = $row['survey_code'];
69
            $sql2 = "DELETE FROM $table_survey_invitation
70
                    WHERE survey_invitation_id = '$survey_invitation_id' AND c_id <> 0";
71
            if (Database::query($sql2)) {
72
                $sql3 = "UPDATE $table_survey SET
73
                            invited = invited-1
74
                        WHERE c_id <> 0 AND code ='$survey_code'";
75
                Database::query($sql3);
76
            }
77
        }
78
    }
79
80
    /**
81
     *
82
     * @param string $course_code
83
     * @param int $session_id
84
     * @return type
85
     * @assert ('') === false
86
     */
87
    public static function get_surveys($course_code, $session_id = 0)
88
    {
89
        $table_survey = Database :: get_course_table(TABLE_SURVEY);
90
        if (empty($course_code)) {
91
            return false;
92
        }
93
        $course_info = api_get_course_info($course_code);
94
        $session_condition = api_get_session_condition($session_id, true, true);
95
96
        $sql = "SELECT * FROM $table_survey
97
                WHERE c_id = {$course_info['real_id']} $session_condition ";
98
        $result = Database::query($sql);
99
        $result = Database::store_result($result, 'ASSOC');
0 ignored issues
show
Bug introduced by
It seems like $result can be null; however, store_result() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
100
        return $result;
101
    }
102
103
    /**
104
     * Retrieves all the survey information
105
     *
106
     * @param integer $survey_id the id of the survey
107
     * @param boolean $shared this parameter determines if
108
     * we have to get the information of a survey from the central (shared) database or from the
109
     * 		  course database
110
     * @param string course code optional
111
     *
112
     * @author Patrick Cool <[email protected]>, Ghent University
113
     * @version February 2007
114
     * @assert ('') === false
115
     *
116
     * @todo this is the same function as in create_new_survey.php
117
     */
118
    public static function get_survey($survey_id, $shared = 0, $course_code = '', $simple_return = false)
119
    {
120
        // Table definition
121
        if (!empty($course_code)) {
122
            $my_course_id = $course_code;
123
        } else if (isset($_GET['course'])) {
124
            $my_course_id = Security::remove_XSS($_GET['course']);
125
        } else {
126
            $my_course_id = api_get_course_id();
127
        }
128
        $my_course_info = api_get_course_info($my_course_id);
129
        $table_survey = Database :: get_course_table(TABLE_SURVEY);
130
131
        if ($shared != 0) {
132
            $table_survey	= Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
133
            $sql = "SELECT * FROM $table_survey
134
                    WHERE survey_id='".intval($survey_id)."' ";
135
        } else {
136
            $sql = "SELECT * FROM $table_survey
137
		            WHERE
138
		                survey_id='".intval($survey_id)."' AND
139
		                c_id = ".$my_course_info['real_id'];
140
        }
141
142
        $result = Database::query($sql);
143
        $return = array();
144
145
        if (Database::num_rows($result)> 0) {
146
            $return = Database::fetch_array($result,'ASSOC');
147
            if ($simple_return) {
148
                return $return;
149
            }
150
            // We do this (temporarily) to have the array match the quickform elements immediately
151
            // idealiter the fields in the db match the quickform fields
152
            $return['survey_code'] = $return['code'];
153
            $return['survey_title'] = $return['title'];
154
            $return['survey_subtitle'] = $return['subtitle'];
155
            $return['survey_language'] = $return['lang'];
156
            $return['start_date'] = $return['avail_from'];
157
            $return['end_date'] = $return['avail_till'];
158
            $return['survey_share'] = $return['is_shared'];
159
            $return['survey_introduction'] = $return['intro'];
160
            $return['survey_thanks'] = $return['surveythanks'];
161
            $return['survey_type'] = $return['survey_type'];
162
            $return['one_question_per_page'] = $return['one_question_per_page'];
163
            $return['show_form_profile'] = $return['show_form_profile'];
164
            $return['input_name_list'] = isset($return['input_name_list']) ? $return['input_name_list'] : null;
165
            $return['shuffle'] = $return['shuffle'];
166
            $return['parent_id'] = $return['parent_id'];
167
            $return['survey_version'] = $return['survey_version'];
168
            $return['anonymous'] = $return['anonymous'];
169
        }
170
171
        return $return;
172
    }
173
174
    /**
175
     * This function stores a survey in the database.
176
     *
177
     * @param array $values
178
     *
179
     * @return array $return the type of return message that has to be displayed and the message in it
180
     *
181
     * @author Patrick Cool <[email protected]>, Ghent University
182
     * @version February 2007
183
     */
184
    public static function store_survey($values)
185
    {
186
        $_user = api_get_user_info();
187
        $course_id = api_get_course_int_id();
188
        $session_id = api_get_session_id();
189
        $courseCode = api_get_course_id();
190
        $table_survey 	= Database :: get_course_table(TABLE_SURVEY);
191
        $shared_survey_id = 0;
192
193
        if (!isset($values['survey_id'])) {
194
            // Check if the code doesn't soon exists in this language
195
            $sql = 'SELECT 1 FROM '.$table_survey.'
196
			        WHERE
197
			            c_id = '.$course_id.' AND
198
			            code="'.Database::escape_string($values['survey_code']).'" AND
199
			            lang="'.Database::escape_string($values['survey_language']).'"';
200
            $rs = Database::query($sql);
201 View Code Duplication
            if (Database::num_rows($rs) > 0) {
202
                Display::addFlash(
203
                    Display::return_message(
204
                        get_lang('ThisSurveyCodeSoonExistsInThisLanguage'),
205
                        'error'
206
                    )
207
                );
208
                $return['type'] = 'error';
209
                $return['id'] = isset($values['survey_id']) ? $values['survey_id'] : 0;
210
211
                return $return;
212
            }
213
214
            if (!isset($values['anonymous'])) {
215
                $values['anonymous'] = 0;
216
            }
217
218
            $values['anonymous'] = intval($values['anonymous']);
219
            $additional['columns'] = '';
220
            $extraParams = [];
221
222
            if ($values['anonymous'] == 0) {
223
                // Input_name_list
224
                $values['show_form_profile'] = isset($values['show_form_profile']) ? $values['show_form_profile'] : 0;
225
                $extraParams['show_form_profile'] = $values['show_form_profile'];
226
227
                if ($values['show_form_profile'] == 1) {
228
                    // Input_name_list
229
                    $fields = explode(',', $values['input_name_list']);
230
                    $field_values = '';
231
                    foreach ($fields as & $field) {
232
                        if ($field != '') {
233
                            if ($values[$field] == '') {
234
                                $values[$field] = 0;
235
                            }
236
                            $field_values.= $field.':'.$values[$field].'@';
237
                        }
238
                    }
239
                    $extraParams['form_fields'] = $field_values;
240
                } else {
241
                    $extraParams['form_fields'] = '';
242
                }
243
            } else {
244
                // Input_name_list
245
                $extraParams['show_form_profile'] = 0;
246
                $extraParams['form_fields'] = '';
247
            }
248
249
            if ($values['survey_type'] == 1) {
250
                $extraParams['survey_type'] = 1;
251
                $extraParams['shuffle'] = $values['shuffle'];
252
                $extraParams['one_question_per_page'] = $values['one_question_per_page'];
253
                $extraParams['parent_id'] = $values['parent_id'];
254
255
                // Logic for versioning surveys
256
                if (!empty($values['parent_id'])) {
257
                    $versionValue = '';
258
                    $sql = 'SELECT survey_version
259
                            FROM '.$table_survey.'
260
					        WHERE
261
					            c_id = '.$course_id.' AND
262
					            parent_id = '.intval($values['parent_id']).'
263
                            ORDER BY survey_version DESC
264
                            LIMIT 1';
265
                    $rs = Database::query($sql);
266
                    if (Database::num_rows($rs) === 0) {
267
                        $sql = 'SELECT survey_version FROM '.$table_survey.'
268
						        WHERE
269
						            c_id = '.$course_id.' AND
270
						            survey_id = '.intval($values['parent_id']);
271
                        $rs = Database::query($sql);
272
                        $getversion = Database::fetch_array($rs, 'ASSOC');
273
                        if (empty($getversion['survey_version'])) {
274
                            $versionValue = ++$getversion['survey_version'];
275
                        } else {
276
                            $versionValue = $getversion['survey_version'];
277
                        }
278
                    } else {
279
                        $row = Database::fetch_array($rs, 'ASSOC');
280
                        $pos = api_strpos($row['survey_version']);
0 ignored issues
show
Bug introduced by
The call to api_strpos() misses a required argument $needle.

This check looks for function calls that miss required arguments.

Loading history...
281
                        if ($pos === false) {
282
                            $row['survey_version'] = $row['survey_version'] + 1;
283
                            $versionValue = $row['survey_version'];
284
                        } else {
285
                            $getlast = explode('\.', $row['survey_version']);
286
                            $lastversion = array_pop($getlast);
287
                            $lastversion = $lastversion + 1;
288
                            $add = implode('.', $getlast);
289
                            if ($add != '') {
290
                                $insertnewversion = $add.'.'.$lastversion;
291
                            } else {
292
                                $insertnewversion = $lastversion;
293
                            }
294
                            $versionValue = $insertnewversion;
295
                        }
296
                    }
297
                    $extraParams['survey_version'] = $versionValue;
298
                }
299
            }
300
301
            $params = [
302
                'c_id' => $course_id,
303
                'code' => strtolower(CourseManager::generate_course_code($values['survey_code'])),
304
                'title' => $values['survey_title'],
305
                'subtitle' => $values['survey_subtitle'],
306
                'author' => $_user['user_id'],
307
                'lang' => $values['survey_language'],
308
                'avail_from' => $values['start_date'],
309
                'avail_till' => $values['end_date'],
310
                'is_shared' => $shared_survey_id,
311
                'template' => 'template',
312
                'intro' => $values['survey_introduction'],
313
                'surveythanks' => $values['survey_thanks'],
314
                'creation_date' => api_get_utc_datetime(),
315
                'anonymous' => $values['anonymous'],
316
                'session_id' => api_get_session_id(),
317
                'visible_results' => $values['visible_results']
318
            ];
319
320
            $params = array_merge($params, $extraParams);
321
            $survey_id = Database::insert($table_survey, $params);
322 View Code Duplication
            if ($survey_id > 0) {
323
324
                $sql = "UPDATE $table_survey SET survey_id = $survey_id
325
                        WHERE iid = $survey_id";
326
                Database::query($sql);
327
328
                // Insert into item_property
329
                api_item_property_update(
330
                    api_get_course_info(),
331
                    TOOL_SURVEY,
332
                    $survey_id,
333
                    'SurveyAdded',
334
                    api_get_user_id()
335
                );
336
            }
337
338
            if ($values['survey_type'] == 1 && !empty($values['parent_id'])) {
339
                SurveyManager::copy_survey($values['parent_id'], $survey_id);
340
            }
341
342
            Display::addFlash(
343
                Display::return_message(
344
                    get_lang('SurveyCreatedSuccesfully'),
345
                    'success'
346
                )
347
            );
348
            $return['id'] = $survey_id;
349
        } else {
350
            // Check whether the code doesn't soon exists in this language
351
            $sql = 'SELECT 1 FROM '.$table_survey.'
352
			        WHERE
353
			            c_id = '.$course_id.' AND
354
			            code = "'.Database::escape_string($values['survey_code']).'" AND
355
			            lang = "'.Database::escape_string($values['survey_language']).'" AND
356
			            survey_id !='.intval($values['survey_id']);
357
            $rs = Database::query($sql);
358 View Code Duplication
            if (Database::num_rows($rs) > 0) {
359
                Display::addFlash(
360
                    Display::return_message(
361
                        get_lang('ThisSurveyCodeSoonExistsInThisLanguage'),
362
                        'error'
363
                    )
364
                );
365
                $return['type'] = 'error';
366
                $return['id'] = isset($values['survey_id']) ? $values['survey_id'] : 0;
367
                return $return;
368
            }
369
370
            if (!isset($values['anonymous']) ||
371
                (isset($values['anonymous']) && $values['anonymous'] == '')
372
            ) {
373
                $values['anonymous'] = 0;
374
            }
375
376
            $values['shuffle'] = isset($values['shuffle']) ? $values['shuffle'] : null;
377
            $values['one_question_per_page'] = isset($values['one_question_per_page']) ? $values['one_question_per_page'] : null;
378
            $values['show_form_profile'] = isset($values['show_form_profile']) ? $values['show_form_profile'] : null;
379
380
            $extraParams = [];
381
            $extraParams['shuffle'] = $values['shuffle'];
382
            $extraParams['one_question_per_page'] = $values['one_question_per_page'];
383
            $extraParams['shuffle'] = $values['shuffle'];
384
385
            if ($values['anonymous'] == 0) {
386
                $extraParams['show_form_profile'] = $values['show_form_profile'];
387
                if ($values['show_form_profile'] == 1) {
388
                    $fields = explode(',',$values['input_name_list']);
389
                    $field_values = '';
390
                    foreach ($fields as &$field) {
391
                        if ($field != '') {
392
                            if (!isset($values[$field]) ||
393
                                (isset($values[$field]) && $values[$field] == '')
394
                            ) {
395
                                $values[$field] = 0;
396
                            }
397
                            $field_values.= $field.':'.$values[$field].'@';
398
                        }
399
                    }
400
                    $extraParams['form_fields'] = $field_values;
401
                } else {
402
                    $extraParams['form_fields'] = '';
403
                }
404
            } else {
405
                $extraParams['show_form_profile'] = 0;
406
                $extraParams['form_fields'] = '';
407
            }
408
409
            $params = [
410
                'title' => $values['survey_title'],
411
                'subtitle' => $values['survey_subtitle'],
412
                'author' => $_user['user_id'],
413
                'lang' => $values['survey_language'],
414
                'avail_from' => $values['start_date'],
415
                'avail_till' => $values['end_date'],
416
                'is_shared' => $shared_survey_id,
417
                'template' => 'template',
418
                'intro' => $values['survey_introduction'],
419
                'surveythanks' => $values['survey_thanks'],
420
                'anonymous' => $values['anonymous'],
421
                'session_id' => api_get_session_id(),
422
                'visible_results' => $values['visible_results'],
423
            ];
424
425
            $params = array_merge($params, $extraParams);
426
            Database::update(
427
                $table_survey,
428
                $params,
429
                [
430
                    'c_id = ? AND survey_id = ?' => [
431
                        $course_id,
432
                        $values['survey_id'],
433
                    ],
434
                ]
435
            );
436
437
            // Update into item_property (update)
438
            api_item_property_update(
439
                api_get_course_info(),
440
                TOOL_SURVEY,
441
                $values['survey_id'],
442
                'SurveyUpdated',
443
                api_get_user_id()
444
            );
445
446
            Display::addFlash(
447
                Display::return_message(
448
                    get_lang('SurveyUpdatedSuccesfully'),
449
                    'confirmation'
450
                )
451
            );
452
453
            $return['id'] = $values['survey_id'];
454
        }
455
456
        $survey_id = intval($return['id']);
457
458
        // Gradebook
459
        $gradebook_option = false;
460
        if (isset($values['survey_qualify_gradebook'])) {
461
            $gradebook_option = $values['survey_qualify_gradebook'] > 0;
462
        }
463
464
        $gradebook_link_type = 8;
465
466
        $link_info = GradebookUtils::is_resource_in_course_gradebook(
467
            $courseCode,
468
            $gradebook_link_type,
469
            $survey_id,
470
            $session_id
471
        );
472
473
        $gradebook_link_id = isset($link_info['id']) ? $link_info['id'] : false;
474
475
        if ($gradebook_option) {
476
            if ($survey_id > 0) {
477
                $title_gradebook = ''; // Not needed here.
478
                $description_gradebook = ''; // Not needed here.
479
                $survey_weight = floatval($_POST['survey_weight']);
480
                $max_score = 1;
481
482
                if (!$gradebook_link_id) {
483
                    GradebookUtils::add_resource_to_course_gradebook(
484
                        $values['category_id'],
485
                        $courseCode,
486
                        $gradebook_link_type,
487
                        $survey_id,
488
                        $title_gradebook,
489
                        $survey_weight,
490
                        $max_score,
491
                        $description_gradebook,
492
                        1,
493
                        $session_id
494
                    );
495
                } else {
496
                    GradebookUtils::update_resource_from_course_gradebook(
497
                        $gradebook_link_id,
498
                        $courseCode,
499
                        $survey_weight
500
                    );
501
                }
502
            }
503
        } else {
504
            // Delete everything of the gradebook for this $linkId
505
            GradebookUtils::remove_resource_from_course_gradebook($gradebook_link_id);
506
507
            //comenting this line to correctly return the function msg
508
            //exit;
509
        }
510
511
        return $return;
512
    }
513
514
    /**
515
     * This function stores a shared survey in the central database.
516
     *
517
     * @param array $values
518
     * @return array $return the type of return message that has to be displayed and the message in it
519
     *
520
     * @author Patrick Cool <[email protected]>, Ghent University
521
     * @version February 2007
522
     */
523
    public function store_shared_survey($values)
524
    {
525
        $_user = api_get_user_info();
526
        $_course = api_get_course_info();
527
528
        // Table definitions
529
        $table_survey	= Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY);
530
531
        if (!$values['survey_id'] ||
532
            !is_numeric($values['survey_id']) ||
533
            $values['survey_share']['survey_share'] == 'true'
534
        ) {
535
            $sql = "INSERT INTO $table_survey (code, title, subtitle, author, lang, template, intro, surveythanks, creation_date, course_code) VALUES (
536
                    '".Database::escape_string($values['survey_code'])."',
537
                    '".Database::escape_string($values['survey_title'])."',
538
                    '".Database::escape_string($values['survey_subtitle'])."',
539
                    '".intval($_user['user_id'])."',
540
                    '".Database::escape_string($values['survey_language'])."',
541
                    '".Database::escape_string('template')."',
542
                    '".Database::escape_string($values['survey_introduction'])."',
543
                    '".Database::escape_string($values['survey_thanks'])."',
544
                    '".api_get_utc_datetime()."',
545
                    '".$_course['id']."')";
546
            Database::query($sql);
547
            $return	= Database::insert_id();
548
549
            $sql = "UPDATE $table_survey SET survey_id = $return WHERE iid = $return";
550
            Database::query($sql);
551
552
        } else {
553
            $sql = "UPDATE $table_survey SET
554
                        code 			= '".Database::escape_string($values['survey_code'])."',
555
                        title 			= '".Database::escape_string($values['survey_title'])."',
556
                        subtitle 		= '".Database::escape_string($values['survey_subtitle'])."',
557
                        author 			= '".intval($_user['user_id'])."',
558
                        lang 			= '".Database::escape_string($values['survey_language'])."',
559
                        template 		= '".Database::escape_string('template')."',
560
                        intro			= '".Database::escape_string($values['survey_introduction'])."',
561
                        surveythanks	= '".Database::escape_string($values['survey_thanks'])."'
562
					WHERE survey_id = '".Database::escape_string($values['survey_share']['survey_share'])."'";
563
            Database::query($sql);
564
            $return	= $values['survey_share']['survey_share'];
565
        }
566
567
        return $return;
568
    }
569
570
    /**
571
     * This function deletes a survey (and also all the question in that survey
572
     *
573
     * @param int $survey_id id of the survey that has to be deleted
574
     * @return true
575
     *
576
     * @author Patrick Cool <[email protected]>, Ghent University
577
     * @version January 2007
578
     */
579
    public static function delete_survey($survey_id, $shared = false, $course_id = '')
580
    {
581
        // Database table definitions
582
        if (empty($course_id)) {
583
            $course_id = api_get_course_int_id();
584
        }
585
586
        $survey_id = intval($survey_id);
587
588
        if (empty($survey_id)) {
589
            return false;
590
        }
591
592
        $course_info = api_get_course_info_by_id($course_id);
593
        $course_id   = $course_info['real_id'];
594
595
        $table_survey = Database :: get_course_table(TABLE_SURVEY);
596
        $table_survey_question_group = Database :: get_course_table(TABLE_SURVEY_QUESTION_GROUP);
597
598
        if ($shared) {
599
            $table_survey = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY);
600
            // Deleting the survey
601
            $sql = "DELETE FROM $table_survey
602
                    WHERE survey_id='".$survey_id."'";
603
            Database::query($sql);
604
        } else {
605
            $sql = "DELETE FROM $table_survey
606
                    WHERE c_id = $course_id AND survey_id='".$survey_id."'";
607
            Database::query($sql);
608
        }
609
610
        // Deleting groups of this survey
611
        $sql = "DELETE FROM $table_survey_question_group
612
                WHERE c_id = $course_id AND survey_id='".$survey_id."'";
613
        Database::query($sql);
614
615
        // Deleting the questions of the survey
616
        SurveyManager::delete_all_survey_questions($survey_id, $shared);
617
618
        // Update into item_property (delete)
619
        api_item_property_update(
620
            $course_info,
621
            TOOL_SURVEY,
622
            $survey_id,
623
            'SurveyDeleted',
624
            api_get_user_id()
625
        );
626
        return true;
627
    }
628
629
    /**
630
     * @param int $survey_id
631
     * @param int $new_survey_id
632
     * @param int $targetCourseId
633
     *
634
     * @return bool
635
     */
636
    public static function copy_survey($survey_id, $new_survey_id = null, $targetCourseId = null)
637
    {
638
        $course_id = api_get_course_int_id();
639
        if (!$targetCourseId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $targetCourseId of type integer|null is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
640
            $targetCourseId = $course_id;
641
        }
642
643
        // Database table definitions
644
        $table_survey = Database::get_course_table(TABLE_SURVEY);
645
        $table_survey_question_group = Database::get_course_table(TABLE_SURVEY_QUESTION_GROUP);
646
        $table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
647
        $table_survey_options = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
648
        $survey_id = intval($survey_id);
649
650
        // Get groups
651
        $survey_data = self::get_survey($survey_id, 0, null, true);
652
        if (empty($survey_data)) {
653
            return true;
654
        }
655
656
        if (empty($new_survey_id)) {
657
            $params = $survey_data;
658
            $params['code'] = self::generate_unique_code($params['code']);
659
            $params['c_id'] = $targetCourseId;
660
            unset($params['survey_id']);
661
            $params['session_id'] = api_get_session_id();
662
            $params['title'] = $params['title'] . ' ' . get_lang('Copy');
663
            unset($params['iid']);
664
            Database::insert($table_survey, $params);
665
            $new_survey_id = Database::insert_id();
666
667 View Code Duplication
            if ($new_survey_id) {
668
                $sql = "UPDATE $table_survey SET survey_id = $new_survey_id
669
                        WHERE iid = $new_survey_id";
670
                Database::query($sql);
671
672
                // Insert into item_property
673
                api_item_property_update(
674
                    api_get_course_info(),
675
                    TOOL_SURVEY,
676
                    $new_survey_id,
677
                    'SurveyAdded',
678
                    api_get_user_id()
679
                );
680
            }
681
        } else {
682
            $new_survey_id = intval($new_survey_id);
683
        }
684
685
        $sql = "SELECT * FROM $table_survey_question_group
686
                WHERE c_id = $course_id AND  survey_id='".$survey_id."'";
687
        $res = Database::query($sql);
688
        while($row = Database::fetch_array($res, 'ASSOC')) {
689
            $params = array(
690
                'c_id' =>  $targetCourseId,
691
                'name' => $row['name'],
692
                'description' => $row['description'],
693
                'survey_id' => $new_survey_id
694
            );
695
            $insertId = Database::insert($table_survey_question_group, $params);
696
697
            $sql = "UPDATE $table_survey_question_group SET id = iid
698
                    WHERE iid = $insertId";
699
            Database::query($sql);
700
701
            $group_id[$row['id']] = $insertId;
702
        }
703
704
        // Get questions
705
        $sql = "SELECT * FROM $table_survey_question
706
                WHERE c_id = $course_id AND survey_id='".$survey_id."'";
707
        $res = Database::query($sql);
708
        while ($row = Database::fetch_array($res, 'ASSOC')) {
709
            $params = array(
710
                'c_id' =>  $targetCourseId,
711
                'survey_id' => $new_survey_id,
712
                'survey_question' => $row['survey_question'],
713
                'survey_question_comment' => $row['survey_question_comment'],
714
                'type' => $row['type'],
715
                'display' => $row['display'],
716
                'sort' => $row['sort'],
717
                'shared_question_id' =>  $row['shared_question_id'],
718
                'max_value' =>  $row['max_value'],
719
                'survey_group_pri' =>  $row['survey_group_pri'],
720
                'survey_group_sec1' =>  $row['survey_group_sec1'],
721
                'survey_group_sec2' => $row['survey_group_sec2']
722
            );
723
            $insertId = Database::insert($table_survey_question, $params);
724
            $sql = "UPDATE $table_survey_question SET question_id = iid WHERE iid = $insertId";
725
            Database::query($sql);
726
727
            $question_id[$row['question_id']] = $insertId;
728
        }
729
730
        // Get questions options
731
        $sql = "SELECT * FROM $table_survey_options
732
                WHERE c_id = $course_id AND survey_id='".$survey_id."'";
733
734
        $res = Database::query($sql);
735
        while ($row = Database::fetch_array($res ,'ASSOC')) {
736
            $params = array(
737
                'c_id' =>  $targetCourseId,
738
                'question_id' => $question_id[$row['question_id']],
739
                'survey_id' => $new_survey_id,
740
                'option_text' => $row['option_text'],
741
                'sort' => $row['sort'],
742
                'value' => $row['value']
743
            );
744
            $insertId = Database::insert($table_survey_options, $params);
745
746
            $sql = "UPDATE $table_survey_options SET question_option_id = $insertId
747
                    WHERE iid = $insertId";
748
            Database::query($sql);
749
        }
750
751
        return $new_survey_id;
752
    }
753
754
    /**
755
     * This function duplicates a survey (and also all the question in that survey
756
     *
757
     * @param int $survey_id id of the survey that has to be duplicated
758
     * @param int $courseId id of the course which survey has to be duplicated
759
     * @return true
760
     *
761
     * @author Eric Marguin <[email protected]>, Elixir Interactive
762
     * @version October 2007
763
     */
764
    public static function empty_survey($survey_id, $courseId = null)
765
    {
766
        // Database table definitions
767
        $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
768
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
769
        $table_survey = Database :: get_course_table(TABLE_SURVEY);
770
771
        $course_id = $courseId ? $courseId : api_get_course_int_id();
772
773
        $datas = SurveyManager::get_survey($survey_id);
774
        $session_where = '';
775
        if (api_get_session_id() != 0) {
776
            $session_where = ' AND session_id = "'.api_get_session_id().'" ';
777
        }
778
779
        $sql = 'DELETE FROM '.$table_survey_invitation.'
780
		        WHERE
781
		            c_id = '.$course_id.' AND
782
		            survey_code = "'.Database::escape_string($datas['code']).'" '.$session_where.' ';
783
        Database::query($sql);
784
785
        $sql = 'DELETE FROM '.$table_survey_answer.'
786
		        WHERE c_id = '.$course_id.' AND survey_id='.intval($survey_id);
787
        Database::query($sql);
788
789
        $sql = 'UPDATE '.$table_survey.' SET invited=0, answered=0
790
		        WHERE c_id = '.$course_id.' AND survey_id='.intval($survey_id);
791
        Database::query($sql);
792
793
        return true;
794
    }
795
796
    /**
797
     * This function recalculates the number of people who have taken the survey (=filled at least one question)
798
     *
799
     * @param int $survey_id the id of the survey somebody
0 ignored issues
show
Bug introduced by
There is no parameter named $survey_id. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
800
     * @return true
801
     *
802
     * @author Patrick Cool <[email protected]>, Ghent University
803
     * @version February 2007
804
     */
805
    public static function update_survey_answered($survey_data, $user, $survey_code)
806
    {
807
        // Database table definitions
808
        $table_survey = Database :: get_course_table(TABLE_SURVEY);
809
        $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
810
811
        $survey_id = $survey_data['survey_id'];
812
        $course_id = $survey_data['c_id'];
813
        $session_id = $survey_data['session_id'];
814
815
        // Getting a list with all the people who have filled the survey
816
        $people_filled = SurveyManager::get_people_who_filled_survey($survey_id, false, $course_id);
817
818
        $number = intval(count($people_filled));
819
820
        // Storing this value in the survey table
821
        $sql = "UPDATE $table_survey
822
		        SET answered = $number
823
		        WHERE
824
                    c_id = $course_id AND
825
		            survey_id = ".intval($survey_id);
826
        Database::query($sql);
827
828
        // Storing that the user has finished the survey.
829
        $sql = "UPDATE $table_survey_invitation SET answered='1'
830
                WHERE
831
                    c_id = $course_id AND
832
                    session_id='".$session_id."' AND
833
                    user='".Database::escape_string($user)."' AND
834
                    survey_code='".Database::escape_string($survey_code)."'";
835
        Database::query($sql);
836
    }
837
838
    /***
839
     * SURVEY QUESTION FUNCTIONS
840
     */
841
842
    /**
843
     * This function return the "icon" of the question type
844
     *
845
     * @author Patrick Cool <[email protected]>, Ghent University
846
     * @version February 2007
847
     */
848
    public static function icon_question($type)
849
    {
850
        // the possible question types
851
        $possible_types = array(
852
            'personality',
853
            'yesno',
854
            'multiplechoice',
855
            'multipleresponse',
856
            'open',
857
            'dropdown',
858
            'comment',
859
            'pagebreak',
860
            'percentage',
861
            'score',
862
        );
863
864
        // the images array
865
        $icon_question = array(
866
            'yesno' => 'yesno.png',
867
            'personality' => 'yesno.png',
868
            'multiplechoice' => 'mcua.png',
869
            'multipleresponse' => 'mcma.png',
870
            'open' => 'open_answer.png',
871
            'dropdown' => 'dropdown.png',
872
            'percentage' => 'percentagequestion.png',
873
            'score' => 'scorequestion.png',
874
            'comment' => 'commentquestion.png',
875
            'pagebreak' => 'page_end.png',
876
        );
877
878
        if (in_array($type, $possible_types)) {
879
            return $icon_question[$type];
880
        } else {
881
            return false;
882
        }
883
    }
884
885
    /**
886
     * This function retrieves all the information of a question
887
     *
888
     * @param integer $question_id the id of the question
889
     * @return array
890
     *
891
     * @author Patrick Cool <[email protected]>, Ghent University
892
     * @version January 2007
893
     *
894
     * @todo one sql call should do the trick
895
     */
896
    public static function get_question($question_id, $shared = false)
897
    {
898
        // Table definitions
899
        $tbl_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
900
        $table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
901
        $course_id = api_get_course_int_id();
902
903
        $sql = "SELECT * FROM $tbl_survey_question
904
                WHERE c_id = $course_id AND question_id='".intval($question_id)."'
905
                ORDER BY `sort` ";
906
907
        $sqlOption = "  SELECT * FROM $table_survey_question_option
908
                        WHERE c_id = $course_id AND question_id='".intval($question_id)."'
909
                        ORDER BY `sort` ";
910
911
        if ($shared) {
912
            $tbl_survey_question = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
913
            $table_survey_question_option = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
914
915
            $sql = "SELECT * FROM $tbl_survey_question
916
                    WHERE question_id='".intval($question_id)."'
917
                    ORDER BY `sort` ";
918
            $sqlOption = "SELECT * FROM $table_survey_question_option
919
                          WHERE question_id='".intval($question_id)."'
920
                          ORDER BY `sort` ";
921
        }
922
923
        // Getting the information of the question
924
925
        $result = Database::query($sql);
926
        $row = Database::fetch_array($result,'ASSOC');
927
928
        $return['survey_id'] = $row['survey_id'];
929
        $return['question_id'] = $row['question_id'];
930
        $return['type'] = $row['type'];
931
        $return['question'] = $row['survey_question'];
932
        $return['horizontalvertical'] = $row['display'];
933
        $return['shared_question_id'] = $row['shared_question_id'];
934
        $return['maximum_score'] = $row['max_value'];
935
936
        if ($row['survey_group_pri'] != 0) {
937
            $return['assigned'] = $row['survey_group_pri'];
938
            $return['choose'] = 1;
939 View Code Duplication
        } else {
940
            $return['assigned1'] = $row['survey_group_sec1'];
941
            $return['assigned2'] = $row['survey_group_sec2'];
942
            $return['choose'] = 2;
943
        }
944
945
        // Getting the information of the question options
946
947
        $result = Database::query($sqlOption);
948 View Code Duplication
        while ($row = Database::fetch_array($result, 'ASSOC')) {
949
            /** @todo this should be renamed to options instead of answers */
950
            $return['answers'][] = $row['option_text'];
951
            $return['values'][] = $row['value'];
952
953
            /** @todo this can be done more elegantly (used in reporting) */
954
            $return['answersid'][] = $row['question_option_id'];
955
        }
956
957
        return $return;
958
    }
959
960
    /**
961
     * This function gets all the question of any given survey
962
     *
963
     * @param integer $survey_id the id of the survey
964
     * @return array containing all the questions of the survey
965
     *
966
     * @author Patrick Cool <[email protected]>, Ghent University
967
     * @version February 2007
968
     *
969
     * @todo one sql call should do the trick
970
     */
971
    public static function get_questions($survey_id, $course_id = '')
972
    {
973
        // Table definitions
974
        $tbl_survey_question 			= Database :: get_course_table(TABLE_SURVEY_QUESTION);
975
        $table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
976
977
        if (empty($course_id)) {
978
            $course_id = api_get_course_int_id();
979
        }
980
981
        $return = array();
982
983
        // Getting the information of the question
984
        $sql = "SELECT * FROM $tbl_survey_question
985
		        WHERE c_id = $course_id AND survey_id='".intval($survey_id)."'";
986
        $result = Database::query($sql);
987
        $return = array();
988
        while ($row = Database::fetch_array($result, 'ASSOC')) {
989
            $return[$row['question_id']]['survey_id'] = $row['survey_id'];
990
            $return[$row['question_id']]['question_id'] = $row['question_id'];
991
            $return[$row['question_id']]['type'] = $row['type'];
992
            $return[$row['question_id']]['question'] = $row['survey_question'];
993
            $return[$row['question_id']]['horizontalvertical'] = $row['display'];
994
            $return[$row['question_id']]['maximum_score'] = $row['max_value'];
995
            $return[$row['question_id']]['sort'] = $row['sort'];
996
        }
997
998
        // Getting the information of the question options
999
        $sql = "SELECT * FROM $table_survey_question_option
1000
		        WHERE c_id = $course_id AND survey_id='".intval($survey_id)."'";
1001
        $result = Database::query($sql);
1002
        while ($row = Database::fetch_array($result, 'ASSOC')) {
1003
            $return[$row['question_id']]['answers'][] = $row['option_text'];
1004
        }
1005
1006
        return $return;
1007
    }
1008
1009
    /**
1010
     * This function saves a question in the database.
1011
     * This can be either an update of an existing survey or storing a new survey
1012
     * @param array $survey_data
1013
     * @param array $form_content all the information of the form
1014
     *
1015
     * @author Patrick Cool <[email protected]>, Ghent University
1016
     * @version January 2007
1017
     */
1018
    public static function save_question($survey_data, $form_content)
1019
    {
1020
        $return_message = '';
1021
1022
        if (strlen($form_content['question']) > 1) {
1023
            // Checks length of the question
1024
            $empty_answer = false;
1025
1026
            if ($survey_data['survey_type'] == 1) {
1027
                if (empty($form_content['choose'])) {
1028
                    $return_message = 'PleaseChooseACondition';
1029
                    return $return_message;
1030
                }
1031
1032
                if (($form_content['choose'] == 2) &&
1033
                    ($form_content['assigned1'] == $form_content['assigned2'])
1034
                ) {
1035
                    $return_message = 'ChooseDifferentCategories';
1036
                    return $return_message;
1037
                }
1038
            }
1039
1040
            if ($form_content['type'] != 'percentage') {
1041
                if (isset($form_content['answers'])) {
1042
                    for ($i = 0; $i < count($form_content['answers']); $i++) {
1043
                        if (strlen($form_content['answers'][$i]) < 1) {
1044
                            $empty_answer = true;
1045
                            break;
1046
                        }
1047
                    }
1048
                }
1049
            }
1050
1051
            if ($form_content['type'] == 'score') {
1052
                if (strlen($form_content['maximum_score']) < 1) {
1053
                    $empty_answer = true;
1054
                }
1055
            }
1056
            $additional = array();
1057
            $course_id = api_get_course_int_id();
1058
1059
            if (!$empty_answer) {
1060
                // Table definitions
1061
                $tbl_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
1062
1063
                // Getting all the information of the survey
1064
                $survey_data = SurveyManager::get_survey($form_content['survey_id']);
1065
1066
                // Storing the question in the shared database
1067
                if (is_numeric($survey_data['survey_share']) && $survey_data['survey_share'] != 0) {
1068
                    $shared_question_id = SurveyManager::save_shared_question($form_content, $survey_data);
1069
                    $form_content['shared_question_id'] = $shared_question_id;
1070
                }
1071
1072
                // Storing a new question
1073
                if ($form_content['question_id'] == '' || !is_numeric($form_content['question_id'])) {
1074
                    // Finding the max sort order of the questions in the given survey
1075
                    $sql = "SELECT max(sort) AS max_sort
1076
					        FROM $tbl_survey_question
1077
                            WHERE c_id = $course_id AND survey_id='".intval($form_content['survey_id'])."'";
1078
                    $result = Database::query($sql);
1079
                    $row = Database::fetch_array($result,'ASSOC');
1080
                    $max_sort = $row['max_sort'];
1081
1082
                    // Some variables defined for survey-test type
1083
                    $extraParams = [];
1084
                    if (isset($_POST['choose'])) {
1085
                        if ($_POST['choose'] == 1) {
1086
                            $extraParams['survey_group_pri'] = $_POST['assigned'];
1087 View Code Duplication
                        } elseif ($_POST['choose'] == 2) {
1088
                            $extraParams['survey_group_sec1'] = $_POST['assigned1'];
1089
                            $extraParams['survey_group_sec2'] = $_POST['assigned2'];
1090
                        }
1091
                    }
1092
1093
                    $questionComment = isset($form_content['question_comment']) ? $form_content['question_comment'] : '';
1094
                    $maxScore = isset($form_content['maximum_score']) ? $form_content['maximum_score'] : '';
1095
                    $display = isset($form_content['horizontalvertical']) ? $form_content['horizontalvertical'] : '';
1096
1097
                    $params = [
1098
                        'c_id' => $course_id,
1099
                        'survey_id' => $form_content['survey_id'],
1100
                        'survey_question' => $form_content['question'],
1101
                        'survey_question_comment' => $questionComment,
1102
                        'type' => $form_content['type'],
1103
                        'display' => $display,
1104
                        'sort' => $max_sort + 1,
1105
                        'shared_question_id' => $form_content['shared_question_id'],
1106
                        'max_value' => $maxScore,
1107
                    ];
1108
1109
                    $params = array_merge($params, $extraParams);
1110
                    $question_id = Database::insert($tbl_survey_question, $params);
1111
                    if ($question_id) {
1112
1113
                        $sql = "UPDATE $tbl_survey_question SET question_id = $question_id
1114
                                WHERE iid = $question_id";
1115
                        Database::query($sql);
1116
1117
                        $form_content['question_id'] = $question_id;
1118
                        $return_message = 'QuestionAdded';
1119
                    }
1120
                } else {
1121
                    // Updating an existing question
1122
1123
                    $extraParams = [];
1124
1125
                    if (isset($_POST['choose'])) {
1126
                        if ($_POST['choose'] == 1) {
1127
                            $extraParams['survey_group_pri'] = $_POST['assigned'];
1128
                            $extraParams['survey_group_sec1'] = 0;
1129
                            $extraParams['survey_group_sec2'] = 0;
1130 View Code Duplication
                        } elseif ($_POST['choose'] == 2) {
1131
                            $extraParams['survey_group_pri'] = 0;
1132
                            $extraParams['survey_group_sec1'] = $_POST['assigned1'];
1133
                            $extraParams['survey_group_sec2'] = $_POST['assigned2'];
1134
                        }
1135
                    }
1136
1137
                    $maxScore = isset($form_content['maximum_score']) ? $form_content['maximum_score'] : null;
1138
                    $questionComment = isset($form_content['question_comment']) ? $form_content['question_comment'] : null;
1139
1140
                    // Adding the question to the survey_question table
1141
                    $params = [
1142
                        'survey_question' => $form_content['question'],
1143
                        'survey_question_comment' => $questionComment,
1144
                        'display' => $form_content['horizontalvertical'],
1145
                    ];
1146
1147
                    $params = array_merge($params, $extraParams);
1148
1149
                    Database::update(
1150
                        $tbl_survey_question,
1151
                        $params,
1152
                        [
1153
                            'c_id = ? AND question_id = ?' => [
1154
                                $course_id,
1155
                                $form_content['question_id'],
1156
                            ],
1157
                        ]
1158
                    );
1159
1160
                    $return_message = 'QuestionUpdated';
1161
                }
1162
1163
                if (!empty($form_content['survey_id'])) {
1164
                    //Updating survey
1165
                    api_item_property_update(
1166
                        api_get_course_info(),
1167
                        TOOL_SURVEY,
1168
                        $form_content['survey_id'],
1169
                        'SurveyUpdated',
1170
                        api_get_user_id()
1171
                    );
1172
                }
1173
1174
                // Storing the options of the question
1175
                SurveyManager::save_question_options($form_content, $survey_data);
1176
            } else {
1177
                $return_message = 'PleasFillAllAnswer';
1178
            }
1179
        } else {
1180
            $return_message = 'PleaseEnterAQuestion';
1181
        }
1182
1183
        if (!empty($return_message)) {
1184
            Display::addFlash(Display::return_message(get_lang($return_message)));
1185
        }
1186
        return $return_message;
1187
    }
1188
1189
    /**
1190
    * This function saves the question in the shared database
1191
    *
1192
    * @param array $form_content all the information of the form
1193
    * @param array $survey_data all the information of the survey
1194
    *
1195
    * @author Patrick Cool <[email protected]>, Ghent University
1196
    * @version February 2007
1197
    *
1198
    * @todo editing of a shared question
1199
    */
1200
    public function save_shared_question($form_content, $survey_data)
1201
    {
1202
        $_course = api_get_course_info();
1203
1204
        // Table definitions
1205
        $tbl_survey_question = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
1206
1207
        // Storing a new question
1208
        if ($form_content['shared_question_id'] == '' ||
1209
            !is_numeric($form_content['shared_question_id'])
1210
        ) {
1211
            // Finding the max sort order of the questions in the given survey
1212
            $sql = "SELECT max(sort) AS max_sort FROM $tbl_survey_question
1213
                    WHERE survey_id='".intval($survey_data['survey_share'])."'
1214
                    AND code='".Database::escape_string($_course['id'])."'";
1215
            $result = Database::query($sql);
1216
            $row = Database::fetch_array($result,'ASSOC');
1217
            $max_sort = $row['max_sort'];
1218
1219
            // Adding the question to the survey_question table
1220
            $sql = "INSERT INTO $tbl_survey_question (survey_id, survey_question, survey_question_comment, type, display, sort, code) VALUES (
1221
                    '".Database::escape_string($survey_data['survey_share'])."',
1222
                    '".Database::escape_string($form_content['question'])."',
1223
                    '".Database::escape_string($form_content['question_comment'])."',
1224
                    '".Database::escape_string($form_content['type'])."',
1225
                    '".Database::escape_string($form_content['horizontalvertical'])."',
1226
                    '".Database::escape_string($max_sort+1)."',
1227
                    '".Database::escape_string($_course['id'])."')";
1228
            Database::query($sql);
1229
            $shared_question_id = Database::insert_id();
1230
        }  else {
1231
            // Updating an existing question
1232
            // adding the question to the survey_question table
1233
            $sql = "UPDATE $tbl_survey_question SET
1234
                        survey_question = '".Database::escape_string($form_content['question'])."',
1235
                        survey_question_comment = '".Database::escape_string($form_content['question_comment'])."',
1236
                        display = '".Database::escape_string($form_content['horizontalvertical'])."'
1237
                    WHERE
1238
                        question_id = '".intval($form_content['shared_question_id'])."' AND
1239
                        code = '".Database::escape_string($_course['id'])."'";
1240
            Database::query($sql);
1241
            $shared_question_id = $form_content['shared_question_id'];
1242
        }
1243
1244
        return $shared_question_id;
1245
    }
1246
1247
    /**
1248
     * This functions moves a question of a survey up or down
1249
     *
1250
     * @param string $direction
1251
     * @param integer $survey_question_id
1252
     * @param integer $survey_id
1253
     *
1254
     * @author Patrick Cool <[email protected]>, Ghent University
1255
     * @version January 2007
1256
     */
1257
    public static function move_survey_question($direction, $survey_question_id, $survey_id)
1258
    {
1259
        // Table definition
1260
        $table_survey_question 	= Database :: get_course_table(TABLE_SURVEY_QUESTION);
1261
        $course_id = api_get_course_int_id();
1262
1263
        if ($direction == 'moveup') {
1264
            $sort = 'DESC';
1265
        }
1266
        if ($direction == 'movedown') {
1267
            $sort = 'ASC';
1268
        }
1269
1270
        // Finding the two questions that needs to be swapped
1271
        $sql = "SELECT * FROM $table_survey_question
1272
		        WHERE c_id = $course_id AND survey_id='".Database::escape_string($survey_id)."'
1273
		        ORDER BY sort $sort";
1274
        $result = Database::query($sql);
1275
        $found = false;
1276
        while ($row = Database::fetch_array($result, 'ASSOC')) {
1277
            if ($found) {
1278
                $question_id_two = $row['question_id'];
1279
                $question_sort_two = $row['sort'];
1280
                $found = false;
1281
            }
1282
            if ($row['question_id'] == $survey_question_id) {
1283
                $found = true;
1284
                $question_id_one = $row['question_id'];
1285
                $question_sort_one = $row['sort'];
1286
            }
1287
        }
1288
1289
        $sql1 = "UPDATE $table_survey_question SET sort = '".Database::escape_string($question_sort_two)."'
1290
		        WHERE c_id = $course_id AND  question_id='".intval($question_id_one)."'";
1291
        Database::query($sql1);
1292
        $sql2 = "UPDATE $table_survey_question SET sort = '".Database::escape_string($question_sort_one)."'
1293
		        WHERE c_id = $course_id AND question_id='".intval($question_id_two)."'";
1294
        Database::query($sql2);
1295
    }
1296
1297
    /**
1298
     * This function deletes all the questions of a given survey
1299
     * This function is normally only called when a survey is deleted
1300
     *
1301
     * @param int $survey_id the id of the survey that has to be deleted
1302
     * @return true
1303
     *
1304
     * @author Patrick Cool <[email protected]>, Ghent University
1305
     * @version January 2007
1306
     */
1307
    public static function delete_all_survey_questions($survey_id, $shared = false)
1308
    {
1309
        $course_id = api_get_course_int_id();
1310
1311
        // Table definitions
1312
        $table_survey_question 	= Database :: get_course_table(TABLE_SURVEY_QUESTION);
1313
        $course_condition = " c_id = $course_id AND ";
1314
        if ($shared) {
1315
            $course_condition = "";
1316
            $table_survey_question 	= Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
1317
        }
1318
1319
        $sql = "DELETE FROM $table_survey_question
1320
		        WHERE $course_condition survey_id='".intval($survey_id)."'";
1321
1322
        // Deleting the survey questions
1323
1324
        Database::query($sql);
1325
1326
        // Deleting all the options of the questions of the survey
1327
        SurveyManager::delete_all_survey_questions_options($survey_id, $shared);
1328
1329
        // Deleting all the answers on this survey
1330
        SurveyManager::delete_all_survey_answers($survey_id);
1331
    }
1332
1333
    /**
1334
     * This function deletes a survey question and all its options
1335
     *
1336
     * @param integer $survey_id the id of the survey
1337
     * @param integer $question_id the id of the question
1338
     * @param integer $shared
1339
     *
1340
     * @todo also delete the answers to this question
1341
     *
1342
     * @author Patrick Cool <[email protected]>, Ghent University
1343
     * @version March 2007
1344
     */
1345
    public static function delete_survey_question($survey_id, $question_id, $shared = false)
1346
    {
1347
        $course_id = api_get_course_int_id();
1348
        // Table definitions
1349
        $table_survey_question 	= Database :: get_course_table(TABLE_SURVEY_QUESTION);
1350
        if ($shared) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $shared of type false|integer is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
1351
            SurveyManager::delete_shared_survey_question($survey_id, $question_id);
1352
        }
1353
1354
        // Deleting the survey questions
1355
        $sql = "DELETE FROM $table_survey_question
1356
		        WHERE
1357
		            c_id = $course_id AND
1358
		            survey_id='".intval($survey_id)."' AND
1359
		            question_id='".intval($question_id)."'";
1360
        Database::query($sql);
1361
1362
        // Deleting the options of the question of the survey
1363
        SurveyManager::delete_survey_question_option($survey_id, $question_id, $shared);
1364
    }
1365
1366
    /**
1367
     * This function deletes a shared survey question from the main database and all its options
1368
     *
1369
     * @param int $question_id the id of the question
1370
     * @param int $shared
0 ignored issues
show
Bug introduced by
There is no parameter named $shared. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
1371
     *
1372
     * @todo delete all the options of this question
1373
     *
1374
     * @author Patrick Cool <[email protected]>, Ghent University
1375
     * @version March 2007
1376
     */
1377
    public static function delete_shared_survey_question($survey_id, $question_id)
1378
    {
1379
        // Table definitions
1380
        $table_survey_question 	      = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
1381
        $table_survey_question_option = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
1382
1383
        // First we have to get the shared_question_id
1384
        $question_data = SurveyManager::get_question($question_id);
1385
1386
        // Deleting the survey questions
1387
        $sql = "DELETE FROM $table_survey_question
1388
		        WHERE question_id='".intval($question_data['shared_question_id'])."'";
1389
        Database::query($sql);
1390
1391
        // Deleting the options of the question of the survey question
1392
        $sql = "DELETE FROM $table_survey_question_option
1393
		        WHERE question_id='".intval($question_data['shared_question_id'])."'";
1394
        Database::query($sql);
1395
    }
1396
1397
    /**
1398
     * This function stores the options of the questions in the table
1399
     *
1400
     * @param array $form_content
1401
     * @author Patrick Cool <[email protected]>, Ghent University
1402
     * @version January 2007
1403
     *
1404
     * @todo writing the update statement when editing a question
1405
     */
1406
    public static function save_question_options($form_content, $survey_data)
1407
    {
1408
        $course_id = api_get_course_int_id();
1409
        // A percentage question type has options 1 -> 100
1410
        if ($form_content['type'] == 'percentage') {
1411
            for($i = 1; $i < 101; $i++) {
1412
                $form_content['answers'][] = $i;
1413
            }
1414
        }
1415
1416
        if (is_numeric($survey_data['survey_share']) && $survey_data['survey_share'] != 0) {
1417
            SurveyManager::save_shared_question_options($form_content, $survey_data);
1418
        }
1419
1420
        // Table definition
1421
        $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
1422
1423
        // We are editing a question so we first have to remove all the existing options from the database
1424
        if (is_numeric($form_content['question_id'])) {
1425
            $sql = "DELETE FROM $table_survey_question_option
1426
			        WHERE c_id = $course_id AND question_id = '".intval($form_content['question_id'])."'";
1427
            Database::query($sql);
1428
        }
1429
1430
        $counter = 1;
1431
        if (isset($form_content['answers']) && is_array($form_content['answers'])) {
1432
            for ($i = 0; $i < count($form_content['answers']); $i++) {
1433
                $values = isset($form_content['values']) ? $form_content['values'][$i] : '';
1434
1435
                $params = [
1436
                    'c_id' => $course_id,
1437
                    'question_id' => $form_content['question_id'],
1438
                    'survey_id' => $form_content['survey_id'],
1439
                    'option_text' => $form_content['answers'][$i],
1440
                    'value' => $values,
1441
                    'sort' => $counter,
1442
                ];
1443
                $insertId = Database::insert($table_survey_question_option, $params);
1444
                if ($insertId) {
1445
1446
                    $sql = "UPDATE $table_survey_question_option
1447
                            SET question_option_id = $insertId
1448
                            WHERE iid = $insertId";
1449
                    Database::query($sql);
1450
1451
                    $counter++;
1452
                }
1453
            }
1454
        }
1455
    }
1456
1457
    /**
1458
     * This function stores the options of the questions in the shared table
1459
     *
1460
     * @param array $form_content
1461
     *
1462
     * @author Patrick Cool <[email protected]>, Ghent University
1463
     * @version February 2007
1464
     *
1465
     * @todo writing the update statement when editing a question
1466
     */
1467
    public function save_shared_question_options($form_content, $survey_data)
1468
    {
1469
        if (is_array($form_content) && is_array($form_content['answers'])) {
1470
            // Table definition
1471
            $table = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
1472
1473
            // We are editing a question so we first have to remove all the existing options from the database
1474
            $sql = "DELETE FROM $table
1475
                    WHERE question_id = '".Database::escape_string($form_content['shared_question_id'])."'";
1476
            Database::query($sql);
1477
1478
            $counter = 1;
1479
            foreach ($form_content['answers'] as & $answer) {
1480
                $params = [
1481
                    'question_id' => $form_content['shared_question_id'],
1482
                    'survey_id' => $survey_data['is_shared'],
1483
                    'option_text' => $answer,
1484
                    'sort' => $counter,
1485
                ];
1486
                Database::insert($table, $params);
1487
1488
                $counter++;
1489
            }
1490
        }
1491
    }
1492
1493
    /**
1494
     * This function deletes all the options of the questions of a given survey
1495
     * This function is normally only called when a survey is deleted
1496
     *
1497
     * @param $survey_id the id of the survey that has to be deleted
1498
     * @return true
1499
     *
1500
     * @author Patrick Cool <[email protected]>, Ghent University
1501
     * @version January 2007
1502
     */
1503 View Code Duplication
    public static function delete_all_survey_questions_options($survey_id, $shared = false)
1504
    {
1505
        // Table definitions
1506
        $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
1507
        $course_id = api_get_course_int_id();
1508
        $course_condition = " c_id = $course_id AND ";
1509
        if ($shared) {
1510
            $course_condition = "";
1511
            $table_survey_question_option = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
1512
        }
1513
1514
        $sql = "DELETE FROM $table_survey_question_option
1515
                WHERE $course_condition survey_id='".intval($survey_id)."'";
1516
1517
        // Deleting the options of the survey questions
1518
        Database::query($sql);
1519
        return true;
1520
    }
1521
1522
    /**
1523
     * This function deletes the options of a given question
1524
     *
1525
     * @param int $survey_id
1526
     * @param int $question_id
1527
     * @param int $shared
1528
     *
1529
     * @return bool
1530
     *
1531
     * @author Patrick Cool <[email protected]>, Ghent University
1532
     * @author Julio Montoya
1533
     * @version March 2007
1534
     */
1535 View Code Duplication
    public static function delete_survey_question_option($survey_id, $question_id, $shared = false)
1536
    {
1537
        $course_id = api_get_course_int_id();
1538
        $course_condition = " c_id = $course_id AND ";
1539
1540
        // Table definitions
1541
        $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
1542
        if ($shared) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $shared of type false|integer is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
1543
            $course_condition = "";
1544
            $table_survey_question_option = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
1545
        }
1546
1547
        // Deleting the options of the survey questions
1548
        $sql = "DELETE from $table_survey_question_option
1549
		        WHERE
1550
		            $course_condition survey_id='".intval($survey_id)."' AND
1551
		            question_id='".intval($question_id)."'";
1552
        Database::query($sql);
1553
        return true;
1554
    }
1555
1556
    /**
1557
     * SURVEY ANSWERS FUNCTIONS
1558
     */
1559
1560
    /**
1561
     * This function deletes all the answers anyone has given on this survey
1562
     * This function is normally only called when a survey is deleted
1563
     *
1564
     * @param $survey_id the id of the survey that has to be deleted
1565
     * @return true
1566
     *
1567
     * @todo write the function
1568
     *
1569
     * @author Patrick Cool <[email protected]>, Ghent University
1570
     * @version January 2007,december 2008
1571
     */
1572
    public static function delete_all_survey_answers($survey_id)
1573
    {
1574
        $course_id = api_get_course_int_id();
1575
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
1576
        $survey_id = intval($survey_id);
1577
        Database::query("DELETE FROM $table_survey_answer WHERE c_id = $course_id AND survey_id=$survey_id");
1578
        return true;
1579
    }
1580
1581
    /**
1582
     * @param int $user_id
1583
     * @param int $survey_id
1584
     * @param int $course_id
1585
     * @return bool
1586
     */
1587 View Code Duplication
    public static function is_user_filled_survey($user_id, $survey_id, $course_id)
1588
    {
1589
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
1590
1591
        $user_id	= intval($user_id);
1592
        $course_id	= intval($course_id);
1593
        $survey_id	= intval($survey_id);
1594
1595
        $sql = "SELECT DISTINCT user FROM $table_survey_answer
1596
                WHERE
1597
                    c_id		= $course_id AND
1598
                    user		= $user_id AND
1599
                    survey_id	= $survey_id";
1600
        $result = Database::query($sql);
1601
        if (Database::num_rows($result)) {
1602
            return true;
1603
        }
1604
        return false;
1605
    }
1606
1607
    /**
1608
     * This function gets all the persons who have filled the survey
1609
     *
1610
     * @param integer $survey_id
1611
     * @return array
1612
     *
1613
     * @author Patrick Cool <[email protected]>, Ghent University
1614
     * @version February 2007
1615
     */
1616
    public static function get_people_who_filled_survey($survey_id, $all_user_info = false, $course_id = null)
1617
    {
1618
        // Database table definition
1619
        $table_survey_answer = Database:: get_course_table(TABLE_SURVEY_ANSWER);
1620
        $table_user = Database:: get_main_table(TABLE_MAIN_USER);
1621
1622
        // Variable initialisation
1623
        $return = array();
1624
1625
        if (empty($course_id)) {
1626
            $course_id = api_get_course_int_id();
1627
        } else {
1628
            $course_id = intval($course_id);
1629
        }
1630
1631
        if ($all_user_info) {
1632
            $order_clause = api_sort_by_first_name() ? ' ORDER BY user.firstname, user.lastname' : ' ORDER BY user.lastname, user.firstname';
1633
            $sql = "SELECT DISTINCT
1634
			            answered_user.user as invited_user, user.firstname, user.lastname, user.user_id
1635
                    FROM $table_survey_answer answered_user
1636
                    LEFT JOIN $table_user as user ON answered_user.user = user.user_id
1637
                    WHERE
1638
                        answered_user.c_id = $course_id AND
1639
                        survey_id= '".Database::escape_string($survey_id)."' ".
1640
                $order_clause;
1641
        } else {
1642
            $sql = "SELECT DISTINCT user FROM $table_survey_answer
1643
			        WHERE c_id = $course_id AND survey_id= '".Database::escape_string($survey_id)."'  ";
1644
        }
1645
1646
        $res = Database::query($sql);
1647
        while ($row = Database::fetch_array($res, 'ASSOC')) {
1648
            if ($all_user_info) {
1649
                $return[] = $row;
1650
            } else {
1651
                $return[] = $row['user'];
1652
            }
1653
        }
1654
1655
        return $return;
1656
    }
1657
1658
    public static function survey_generation_hash_available()
1659
    {
1660
        if (extension_loaded('mcrypt')) {
1661
            return true;
1662
        }
1663
        return false;
1664
    }
1665
1666
    public static function generate_survey_hash($survey_id, $course_id, $session_id, $group_id)
1667
    {
1668
        $hash = hash('sha512', api_get_security_key().'_'.$course_id.'_'.$session_id.'_'.$group_id.'_'.$survey_id);
1669
        return $hash;
1670
    }
1671
1672
    public static function validate_survey_hash($survey_id, $course_id, $session_id, $group_id, $hash)
1673
    {
1674
        $survey_generated_hash = self::generate_survey_hash($survey_id, $course_id, $session_id, $group_id);
1675
        if ($survey_generated_hash == $hash) {
1676
            return true;
1677
        }
1678
        return false;
1679
    }
1680
1681
    public static function generate_survey_link($survey_id, $course_id, $session_id, $group_id)
1682
    {
1683
        $code = self::generate_survey_hash($survey_id, $course_id, $session_id, $group_id);
1684
        return api_get_path(WEB_CODE_PATH).'survey/link.php?h='.$code.'&i='.$survey_id.'&c='.intval($course_id).'&s='.intval($session_id).'&g='.$group_id;
1685
    }
1686
}
1687
1688
1689
/**
1690
 * This class offers a series of general utility functions for survey querying and display
1691
 * @package chamilo.survey
1692
 */
1693
class SurveyUtil
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
1694
{
1695
    /**
1696
     * Checks whether the given survey has a pagebreak question as the first or the last question.
1697
     * If so, break the current process, displaying an error message
1698
     * @param	integer	Survey ID (database ID)
1699
     * @param	boolean	Optional. Whether to continue the current process or exit when breaking condition found. Defaults to true (do not break).
1700
     * @return	void
1701
     */
1702
    static function check_first_last_question($survey_id, $continue = true)
1703
    {
1704
        // Table definitions
1705
        $tbl_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
1706
        $course_id = api_get_course_int_id();
1707
1708
        // Getting the information of the question
1709
        $sql = "SELECT * FROM $tbl_survey_question
1710
                WHERE c_id = $course_id AND survey_id='".Database::escape_string($survey_id)."'
1711
                ORDER BY sort ASC";
1712
        $result = Database::query($sql);
1713
        $total = Database::num_rows($result);
1714
        $counter = 1;
1715
        $error = false;
1716
        while ($row = Database::fetch_array($result, 'ASSOC')) {
1717 View Code Duplication
            if ($counter == 1 && $row['type'] == 'pagebreak') {
1718
1719
                Display::display_error_message(get_lang('PagebreakNotFirst'), false);
1720
                $error = true;
1721
            }
1722 View Code Duplication
            if ($counter == $total && $row['type'] == 'pagebreak') {
1723
                Display::display_error_message(get_lang('PagebreakNotLast'), false);
1724
                $error = true;
1725
            }
1726
            $counter++;
1727
        }
1728
1729
        if (!$continue && $error) {
1730
            Display::display_footer();
1731
            exit;
1732
        }
1733
    }
1734
1735
    /**
1736
     * This function removes an (or multiple) answer(s) of a user on a question of a survey
1737
     *
1738
     * @param mixed   The user id or email of the person who fills the survey
1739
     * @param integer The survey id
1740
     * @param integer The question id
1741
     * @param integer The option id
1742
     *
1743
     * @author Patrick Cool <[email protected]>, Ghent University
1744
     * @version January 2007
1745
     */
1746
    static function remove_answer($user, $survey_id, $question_id, $course_id) {
1747
        $course_id = intval($course_id);
1748
        // table definition
1749
        $table_survey_answer 		= Database :: get_course_table(TABLE_SURVEY_ANSWER);
1750
        $sql = "DELETE FROM $table_survey_answer
1751
				WHERE
1752
				    c_id = $course_id AND
1753
                    user = '".Database::escape_string($user)."' AND
1754
                    survey_id = '".intval($survey_id)."' AND
1755
                    question_id = '".intval($question_id)."'";
1756
        Database::query($sql);
1757
    }
1758
1759
    /**
1760
     * This function stores an answer of a user on a question of a survey
1761
     *
1762
     * @param mixed   The user id or email of the person who fills the survey
1763
     * @param integer Survey id
1764
     * @param integer Question id
1765
     * @param integer Option id
1766
     * @param string  Option value
1767
     * @param array	  Survey data settings
1768
     *
1769
     * @author Patrick Cool <[email protected]>, Ghent University
1770
     * @version January 2007
1771
     */
1772
    static function store_answer($user, $survey_id, $question_id, $option_id, $option_value, $survey_data)
1773
    {
1774
        // Table definition
1775
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
1776
1777
        // Make the survey anonymous
1778
        if ($survey_data['anonymous'] == 1) {
1779
            if (!isset($_SESSION['surveyuser'])) {
1780
                $user = md5($user.time());
1781
                $_SESSION['surveyuser'] = $user;
1782
            } else {
1783
                $user = $_SESSION['surveyuser'];
1784
            }
1785
        }
1786
1787
        $course_id = $survey_data['c_id'];
1788
1789
        $sql = "INSERT INTO $table_survey_answer (c_id, user, survey_id, question_id, option_id, value) VALUES (
1790
				$course_id,
1791
				'".Database::escape_string($user)."',
1792
				'".Database::escape_string($survey_id)."',
1793
				'".Database::escape_string($question_id)."',
1794
				'".Database::escape_string($option_id)."',
1795
				'".Database::escape_string($option_value)."'
1796
				)";
1797
        Database::query($sql);
1798
        $insertId = Database::insert_id();
1799
1800
        $sql = "UPDATE $table_survey_answer SET answer_id = $insertId WHERE iid = $insertId";
1801
        Database::query($sql);
1802
    }
1803
1804
    /**
1805
     * This function checks the parameters that are used in this page
1806
     *
1807
     * @return 	string 	The header, an error and the footer if any parameter fails, else it returns true
1808
     * @author Patrick Cool <[email protected]>, Ghent University
1809
     * @version February 2007
1810
     */
1811
    static function check_parameters($people_filled)
1812
    {
1813
        $error = false;
1814
1815
        // Getting the survey data
1816
        $survey_data = SurveyManager::get_survey($_GET['survey_id']);
1817
1818
        // $_GET['survey_id'] has to be numeric
1819
        if (!is_numeric($_GET['survey_id'])) {
1820
            $error = get_lang('IllegalSurveyId');
1821
        }
1822
1823
        // $_GET['action']
1824
        $allowed_actions = array(
1825
            'overview',
1826
            'questionreport',
1827
            'userreport',
1828
            'comparativereport',
1829
            'completereport',
1830
            'deleteuserreport'
1831
        );
1832
        if (isset($_GET['action']) && !in_array($_GET['action'], $allowed_actions)) {
1833
            $error = get_lang('ActionNotAllowed');
1834
        }
1835
1836
        // User report
1837
        if (isset($_GET['action']) && $_GET['action'] == 'userreport') {
1838
            if ($survey_data['anonymous'] == 0) {
1839
                foreach ($people_filled as $key => & $value) {
1840
                    $people_filled_userids[] = $value['invited_user'];
1841
                }
1842
            } else {
1843
                $people_filled_userids = $people_filled;
1844
            }
1845
1846
            if (isset($_GET['user']) && !in_array($_GET['user'], $people_filled_userids)) {
1847
                $error = get_lang('UnknowUser');
1848
            }
1849
        }
1850
1851
        // Question report
1852
        if (isset($_GET['action']) && $_GET['action'] == 'questionreport') {
1853
            if (isset($_GET['question']) && !is_numeric($_GET['question'])) {
1854
                $error = get_lang('UnknowQuestion');
1855
            }
1856
        }
1857
1858
        if ($error) {
1859
            $tool_name = get_lang('Reporting');
1860
            Display::display_header($tool_name);
1861
            Display::display_error_message(get_lang('Error').': '.$error, false);
1862
            Display::display_footer();
1863
            exit;
1864
        } else {
1865
            return true;
1866
        }
1867
    }
1868
1869
    /**
1870
     * This function deals with the action handling
1871
     * @return	void
1872
     * @author Patrick Cool <[email protected]>, Ghent University
1873
     * @version February 2007
1874
     */
1875
    public static function handle_reporting_actions($survey_data, $people_filled)
1876
    {
1877
        $action = isset($_GET['action']) ? $_GET['action'] : null;
1878
1879
        // Getting the number of question
1880
        $temp_questions_data = SurveyManager::get_questions($_GET['survey_id']);
1881
1882
        // Sorting like they should be displayed and removing the non-answer question types (comment and pagebreak)
1883
        $my_temp_questions_data = $temp_questions_data == null ? array() : $temp_questions_data;
1884
        $questions_data = array();
1885
1886
        foreach ($my_temp_questions_data as $key => & $value) {
1887
            if ($value['type'] != 'comment' && $value['type'] != 'pagebreak') {
1888
                $questions_data[$value['sort']] = $value;
1889
            }
1890
        }
1891
1892
        // Counting the number of questions that are relevant for the reporting
1893
        $survey_data['number_of_questions'] = count($questions_data);
1894
1895
        if ($action == 'questionreport') {
1896
            SurveyUtil::display_question_report($survey_data);
1897
        }
1898
        if ($action == 'userreport') {
1899
            SurveyUtil::display_user_report($people_filled, $survey_data);
1900
        }
1901
        if ($action == 'comparativereport') {
1902
            SurveyUtil::display_comparative_report();
1903
        }
1904
        if ($action == 'completereport') {
1905
            SurveyUtil::display_complete_report($survey_data);
1906
        }
1907
        if ($action == 'deleteuserreport') {
1908
            SurveyUtil::delete_user_report($_GET['survey_id'], $_GET['user']);
1909
        }
1910
    }
1911
1912
    /**
1913
     * This function deletes the report of an user who wants to retake the survey
1914
     * @param integer survey_id
1915
     * @param integer user_id
1916
     * @return void
1917
     * @author Christian Fasanando Flores <[email protected]>
1918
     * @version November 2008
1919
     */
1920
    function delete_user_report($survey_id, $user_id)
1921
    {
1922
        $table_survey_answer 		= Database :: get_course_table(TABLE_SURVEY_ANSWER);
1923
        $table_survey_invitation 	= Database :: get_course_table(TABLE_SURVEY_INVITATION);
1924
        $table_survey 				= Database :: get_course_table(TABLE_SURVEY);
1925
1926
        $course_id = api_get_course_int_id();
1927
1928
        if (!empty($survey_id) && !empty($user_id)) {
1929
            // delete data from survey_answer by user_id and survey_id
1930
            $sql = "DELETE FROM $table_survey_answer
1931
			        WHERE c_id = $course_id AND survey_id = '".(int)$survey_id."' AND user = '".(int)$user_id."'";
1932
            Database::query($sql);
1933
            // update field answered from survey_invitation by user_id and survey_id
1934
            $sql = "UPDATE $table_survey_invitation SET answered = '0'
1935
			        WHERE
1936
			            c_id = $course_id AND
1937
			            survey_code = (
1938
                            SELECT code FROM $table_survey
1939
                            WHERE
1940
                                c_id = $course_id AND
1941
                                survey_id = '".(int)$survey_id."'
1942
                        ) AND
1943
			            user = '".(int)$user_id."'";
1944
            $result = Database::query($sql);
1945
        }
1946
1947 View Code Duplication
        if ($result !== false) {
1948
            $message = get_lang('SurveyUserAnswersHaveBeenRemovedSuccessfully').'<br />
1949
					<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action=userreport&survey_id='.Security::remove_XSS($survey_id).'">'.get_lang('GoBack').'</a>';
1950
            Display::display_confirmation_message($message, false);
1951
        }
1952
    }
1953
1954
    /**
1955
     * This function displays the user report which is basically nothing more
1956
     * than a one-page display of all the questions
1957
     * of the survey that is filled with the answers of the person who filled the survey.
1958
     *
1959
     * @return 	string	html code of the one-page survey with the answers of the selected user
1960
     * @author Patrick Cool <[email protected]>, Ghent University
1961
     * @version February 2007 - Updated March 2008
1962
     */
1963
    public static function display_user_report($people_filled, $survey_data)
1964
    {
1965
        // Database table definitions
1966
        $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
1967
        $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
1968
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
1969
1970
        // Actions bar
1971
        echo '<div class="actions">';
1972
        echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.Security::remove_XSS($_GET['survey_id']).'">'.
1973
            Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('ReportingOverview'),'',ICON_SIZE_MEDIUM).'</a>';
1974
        if (isset($_GET['user'])) {
1975
            if (api_is_allowed_to_edit()) {
1976
                // The delete link
1977
                echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action=deleteuserreport&survey_id='.Security::remove_XSS($_GET['survey_id']).'&user='.Security::remove_XSS($_GET['user']).'" >'.
1978
                    Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_MEDIUM).'</a>';
1979
            }
1980
1981
            // Export the user report
1982
            echo '<a href="javascript: void(0);" onclick="document.form1a.submit();">'.
1983
                Display::return_icon('export_csv.png', get_lang('ExportAsCSV'),'',ICON_SIZE_MEDIUM).'</a> ';
1984
            echo '<a href="javascript: void(0);" onclick="document.form1b.submit();">'.
1985
                Display::return_icon('export_excel.png', get_lang('ExportAsXLS'),'',ICON_SIZE_MEDIUM).'</a> ';
1986
            echo '<form id="form1a" name="form1a" method="post" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.Security::remove_XSS($_GET['survey_id']).'&user_id='.Security::remove_XSS($_GET['user']).'">';
1987
            echo '<input type="hidden" name="export_report" value="export_report">';
1988
            echo '<input type="hidden" name="export_format" value="csv">';
1989
            echo '</form>';
1990
            echo '<form id="form1b" name="form1b" method="post" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.Security::remove_XSS($_GET['survey_id']).'&user_id='.Security::remove_XSS($_GET['user']).'">';
1991
            echo '<input type="hidden" name="export_report" value="export_report">';
1992
            echo '<input type="hidden" name="export_format" value="xls">';
1993
            echo '</form>';
1994
            echo '<form id="form2" name="form2" method="post" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.Security::remove_XSS($_GET['survey_id']).'">';
1995
        }
1996
        echo '</div>';
1997
1998
        // Step 1: selection of the user
1999
        echo "<script>
2000
        function jumpMenu(targ,selObj,restore) {
2001
            eval(targ+\".location='\"+selObj.options[selObj.selectedIndex].value+\"'\");
2002
            if (restore) selObj.selectedIndex=0;
2003
        }
2004
		</script>";
2005
        echo get_lang('SelectUserWhoFilledSurvey').'<br />';
2006
        echo '<select name="user" onchange="jumpMenu(\'parent\',this,0)">';
2007
        echo '<option value="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action='.Security::remove_XSS($_GET['action']).'&survey_id='.Security::remove_XSS($_GET['survey_id']).'">'.get_lang('SelectUser').'</option>';
2008
2009
        foreach ($people_filled as $key => & $person) {
2010
            if ($survey_data['anonymous'] == 0) {
2011
                $name = api_get_person_name($person['firstname'], $person['lastname']);
2012
                $id = $person['user_id'];
2013
                if ($id == '') {
2014
                    $id = $person['invited_user'];
2015
                    $name = $person['invited_user'];
2016
                }
2017
            } else {
2018
                $name  = get_lang('Anonymous') . ' ' . ($key + 1);
2019
                $id = $person;
2020
            }
2021
            echo '<option value="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action='.Security::remove_XSS($_GET['action']).'&survey_id='.Security::remove_XSS($_GET['survey_id']).'&user='.Security::remove_XSS($id).'" ';
2022
            if (isset($_GET['user']) && $_GET['user'] == $id) {
2023
                echo 'selected="selected"';
2024
            }
2025
            echo '>'.$name.'</option>';
2026
        }
2027
        echo '</select>';
2028
2029
        $course_id = api_get_course_int_id();
2030
        // Step 2: displaying the survey and the answer of the selected users
2031
        if (isset($_GET['user'])) {
2032
            Display::display_normal_message(
2033
                get_lang('AllQuestionsOnOnePage'),
2034
                false
2035
            );
2036
2037
            // Getting all the questions and options
2038
            $sql = "SELECT
2039
			            survey_question.question_id,
2040
			            survey_question.survey_id,
2041
			            survey_question.survey_question,
2042
			            survey_question.display,
2043
			            survey_question.max_value,
2044
			            survey_question.sort,
2045
			            survey_question.type,
2046
                        survey_question_option.question_option_id,
2047
                        survey_question_option.option_text,
2048
                        survey_question_option.sort as option_sort
2049
					FROM $table_survey_question survey_question
2050
					LEFT JOIN $table_survey_question_option survey_question_option
2051
					ON
2052
					    survey_question.question_id = survey_question_option.question_id AND
2053
					    survey_question_option.c_id = $course_id
2054
					WHERE
2055
					    survey_question.survey_id = '".Database::escape_string(
2056
                    $_GET['survey_id']
2057
                )."' AND
2058
                        survey_question.c_id = $course_id
2059
					ORDER BY survey_question.sort, survey_question_option.sort ASC";
2060
            $result = Database::query($sql);
2061 View Code Duplication
            while ($row = Database::fetch_array($result, 'ASSOC')) {
2062
                if ($row['type'] != 'pagebreak') {
2063
                    $questions[$row['sort']]['question_id'] = $row['question_id'];
2064
                    $questions[$row['sort']]['survey_id'] = $row['survey_id'];
2065
                    $questions[$row['sort']]['survey_question'] = $row['survey_question'];
2066
                    $questions[$row['sort']]['display'] = $row['display'];
2067
                    $questions[$row['sort']]['type'] = $row['type'];
2068
                    $questions[$row['sort']]['maximum_score'] = $row['max_value'];
2069
                    $questions[$row['sort']]['options'][$row['question_option_id']] = $row['option_text'];
2070
                }
2071
            }
2072
2073
            // Getting all the answers of the user
2074
            $sql = "SELECT * FROM $table_survey_answer
2075
			        WHERE
2076
                        c_id = $course_id AND
2077
                        survey_id = '".intval($_GET['survey_id'])."' AND
2078
                        user = '".Database::escape_string($_GET['user'])."'";
2079
            $result = Database::query($sql);
2080
            while ($row = Database::fetch_array($result, 'ASSOC')) {
2081
                $answers[$row['question_id']][] = $row['option_id'];
2082
                $all_answers[$row['question_id']][] = $row;
2083
            }
2084
2085
            // Displaying all the questions
2086
2087
            foreach ($questions as & $question) {
2088
                // If the question type is a scoring then we have to format the answers differently
2089
                switch ($question['type']) {
2090
                    case 'score':
2091
                        $finalAnswer = array();
2092
                        if (is_array($question) && is_array($all_answers)) {
2093
                            foreach ($all_answers[$question['question_id']] as $key => & $answer_array) {
2094
                                $finalAnswer[$answer_array['option_id']] = $answer_array['value'];
2095
                            }
2096
                        }
2097
                        break;
2098
                    case 'multipleresponse':
2099
                        $finalAnswer = isset($answers[$question['question_id']]) ? $answers[$question['question_id']] : '';
2100
                        break;
2101
                    default:
2102
                        $finalAnswer = '';
2103
                        if (isset($all_answers[$question['question_id']])) {
2104
                            $finalAnswer = $all_answers[$question['question_id']][0]['option_id'];
2105
                        }
2106
                        break;
2107
                }
2108
2109
                $ch_type = 'ch_'.$question['type'];
2110
                /** @var survey_question $display */
2111
                $display = new $ch_type;
2112
2113
                $url = api_get_self();
2114
                $form = new FormValidator('question', 'post', $url);
2115
                $form->addHtml('<div class="survey_question_wrapper"><div class="survey_question">');
2116
                $form->addHtml($question['survey_question']);
2117
                $display->render($form, $question, $finalAnswer);
2118
                $form->addHtml('</div></div>');
2119
                $form->display();
2120
            }
2121
        }
2122
    }
2123
2124
    /**
2125
     * This function displays the report by question.
2126
     *
2127
     * It displays a table with all the options of the question and the number of users who have answered positively on the option.
2128
     * The number of users who answered positive on a given option is expressed in an absolute number, in a percentage of the total
2129
     * and graphically using bars
2130
     * By clicking on the absolute number you get a list with the persons who have answered this.
2131
     * You can then click on the name of the person and you will then go to the report by user where you see all the
2132
     * answers of that user.
2133
     *
2134
     * @param 	array 	All the survey data
2135
     * @return 	string	html code that displays the report by question
2136
     * @todo allow switching between horizontal and vertical.
2137
     * @todo multiple response: percentage are probably not OK
2138
     * @todo the question and option text have to be shortened and should expand when the user clicks on it.
2139
     * @todo the pagebreak and comment question types should not be shown => removed from $survey_data before
2140
     * @author Patrick Cool <[email protected]>, Ghent University
2141
     * @version February 2007 - Updated March 2008
2142
     */
2143
    public static function display_question_report($survey_data)
2144
    {
2145
        $singlePage = isset($_GET['single_page']) ? intval($_GET['single_page']) : 0;
2146
        $course_id = api_get_course_int_id();
2147
        // Database table definitions
2148
        $table_survey_question 			= Database :: get_course_table(TABLE_SURVEY_QUESTION);
2149
        $table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
2150
        $table_survey_answer 			= Database :: get_course_table(TABLE_SURVEY_ANSWER);
2151
2152
        // Determining the offset of the sql statement (the n-th question of the survey)
2153
        $offset = !isset($_GET['question']) ? 0 : intval($_GET['question']);
2154
        $currentQuestion = isset($_GET['question']) ? intval($_GET['question']) : 0;
2155
        $questions = array();
2156
        $surveyId = intval($_GET['survey_id']);
2157
        $action = Security::remove_XSS($_GET['action']);
2158
2159
        echo '<div class="actions">';
2160
        echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.$surveyId.'">'.
2161
            Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('ReportingOverview'),'',ICON_SIZE_MEDIUM).'</a>';
2162
        echo '</div>';
2163
2164
        if ($survey_data['number_of_questions'] > 0) {
2165
            $limitStatement = null;
2166
            if (!$singlePage) {
2167
                echo '<div id="question_report_questionnumbers" class="pagination">';
2168
                /* echo '<ul><li class="disabled"><a href="#">'.get_lang('Question').'</a></li>'; */
2169
2170
                if ($currentQuestion != 0) {
2171
                    echo '<li><a href="' . api_get_path(WEB_CODE_PATH) . 'survey/reporting.php?action=' . $action . '&' . api_get_cidreq() . '&survey_id=' . $surveyId . '&question=' . ($offset - 1) . '">' . get_lang('PreviousQuestion') . '</a></li>';
2172
                }
2173
2174
                for ($i = 1; $i <= $survey_data['number_of_questions']; $i++) {
2175
                    if ($offset != $i - 1) {
2176
                        echo '<li><a href="' . api_get_path(WEB_CODE_PATH) . 'survey/reporting.php?action=' . $action . '&' . api_get_cidreq() . '&survey_id=' . $surveyId . '&question=' . ($i - 1) . '">' . $i . '</a></li>';
2177
                    } else {
2178
                        echo '<li class="disabled"s><a href="#">' . $i . '</a></li>';
2179
                    }
2180
                    /*if ($i < $survey_data['number_of_questions']) {
2181
                        echo ' | ';
2182
                    }*/
2183
                }
2184
                if ($currentQuestion < ($survey_data['number_of_questions'] - 1)) {
2185
                    echo '<li><a href="' . api_get_path(WEB_CODE_PATH) . 'survey/reporting.php?action=' . $action . '&' . api_get_cidreq() . '&survey_id=' . $surveyId . '&question=' . ($offset + 1) . '">' . get_lang('NextQuestion') . '</li></a>';
2186
                }
2187
                echo '</ul>';
2188
                echo '</div>';
2189
                $limitStatement = " LIMIT $offset, 1";
2190
            }
2191
2192
            // Getting the question information
2193
            $sql = "SELECT * FROM $table_survey_question
2194
			        WHERE
2195
			            c_id = $course_id AND
2196
                        survey_id='".Database::escape_string($_GET['survey_id'])."' AND
2197
                        type<>'pagebreak' AND type<>'comment'
2198
                    ORDER BY sort ASC
2199
                    $limitStatement";
2200
            $result = Database::query($sql);
2201
            //$question = Database::fetch_array($result);
2202
2203
            while ($row = Database::fetch_array($result)) {
2204
                $questions[$row['question_id']] = $row;
2205
            }
2206
2207
            // Navigate through the questions (next and previous)
2208
            /*if ($currentQuestion != 0 ) {
2209
                echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action='.Security::remove_XSS($_GET['action']).'&'.api_get_cidreq().'&survey_id='.Security::remove_XSS($_GET['survey_id']).'&question='.Security::remove_XSS($offset-1).'">'.
2210
                    Display::return_icon('action_prev.png', get_lang('PreviousQuestion'), array('align' => 'middle')).' '.get_lang('PreviousQuestion').'</a>  ';
2211
            } else {
2212
                echo Display::return_icon('action_prev.png', get_lang('PreviousQuestion'), array('align' => 'middle')).' '.get_lang('PreviousQuestion').' ';
2213
            }
2214
            echo ' | ';
2215
            if ($currentQuestion < ($survey_data['number_of_questions'] - 1)) {
2216
                echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action='.Security::remove_XSS($_GET['action']).'&'.api_get_cidreq().'&survey_id='.Security::remove_XSS($_GET['survey_id']).'&question='.Security::remove_XSS($offset+1).'">'.get_lang('NextQuestion').' '.Display::return_icon('action_next.png', get_lang('NextQuestion'), array('align' => 'middle')).'</a>';
2217
            } else {
2218
                echo get_lang('NextQuestion').' '.Display::return_icon('action_next.png', get_lang('NextQuestion'), array('align' => 'middle'));
2219
            }*/
2220
        }
2221
2222
        foreach ($questions as $question) {
2223
            $chartData = array();
2224
            $options = array();
2225
            echo '<div class="title-question">';
2226
            echo strip_tags(isset($question['survey_question']) ? $question['survey_question'] : null);
2227
            echo '</div>';
2228
2229
            if ($question['type'] == 'score') {
2230
                /** @todo This function should return the options as this is needed further in the code */
2231
                $options = SurveyUtil::display_question_report_score($survey_data, $question, $offset);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $options is correct as \SurveyUtil::display_que...ta, $question, $offset) (which targets SurveyUtil::display_question_report_score()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
2232
            } elseif ($question['type'] == 'open') {
2233
                /** @todo Also get the user who has answered this */
2234
                $sql = "SELECT * FROM $table_survey_answer
2235
                        WHERE
2236
                            c_id = $course_id AND
2237
                            survey_id='" . intval($_GET['survey_id']) . "' AND
2238
                            question_id = '" . intval($question['question_id']) . "'";
2239
                $result = Database::query($sql);
2240
                while ($row = Database::fetch_array($result)) {
2241
                    echo $row['option_id'] . '<hr noshade="noshade" size="1" />';
2242
                }
2243
            } else {
2244
                // Getting the options ORDER BY sort ASC
2245
                $sql = "SELECT * FROM $table_survey_question_option
2246
                        WHERE
2247
                            c_id = $course_id AND
2248
                            survey_id='" . intval($_GET['survey_id']) . "'
2249
                            AND question_id = '" . intval($question['question_id']) . "'
2250
                        ORDER BY sort ASC";
2251
                $result = Database::query($sql);
2252
                while ($row = Database::fetch_array($result)) {
2253
                    $options[$row['question_option_id']] = $row;
2254
                }
2255
                // Getting the answers
2256
                $sql = "SELECT *, count(answer_id) as total FROM $table_survey_answer
2257
                        WHERE
2258
                            c_id = $course_id AND
2259
                            survey_id='" . intval($_GET['survey_id']) . "'
2260
                            AND question_id = '" . intval($question['question_id']) . "'
2261
                        GROUP BY option_id, value";
2262
                $result = Database::query($sql);
2263
                $number_of_answers = array();
2264
                $data = array();
2265 View Code Duplication
                while ($row = Database::fetch_array($result)) {
2266
                    if (!isset($number_of_answers[$row['question_id']])) {
2267
                        $number_of_answers[$row['question_id']] = 0;
2268
                    }
2269
                    $number_of_answers[$row['question_id']] += $row['total'];
2270
                    $data[$row['option_id']] = $row;
2271
                }
2272
2273
                foreach ($options as $option) {
2274
                    $optionText = strip_tags($option['option_text']);
2275
                    $optionText = html_entity_decode($optionText);
2276
                    $votes = isset($data[$option['question_option_id']]['total']) ?
2277
                        $data[$option['question_option_id']]['total'] :
2278
                        '0';
2279
                    array_push($chartData, array('option' => $optionText, 'votes' => $votes));
2280
                }
2281
                $chartContainerId = 'chartContainer'.$question['question_id'];
2282
                echo '<div id="'.$chartContainerId.'" class="col-md-12">';
2283
                echo self::drawChart($chartData, false, $chartContainerId);
2284
2285
                // displaying the table: headers
2286
2287
                echo '<table class="display-survey table">';
2288
                echo '	<tr>';
2289
                echo '		<th>&nbsp;</th>';
2290
                echo '		<th>' . get_lang('AbsoluteTotal') . '</th>';
2291
                echo '		<th>' . get_lang('Percentage') . '</th>';
2292
                echo '		<th>' . get_lang('VisualRepresentation') . '</th>';
2293
                echo '	<tr>';
2294
2295
                // Displaying the table: the content
2296
                if (is_array($options)) {
2297
                    foreach ($options as $key => & $value) {
2298
                        $absolute_number = null;
2299
                        if (isset($data[$value['question_option_id']])) {
2300
                            $absolute_number = $data[$value['question_option_id']]['total'];
2301
                        }
2302
                        if ($question['type'] == 'percentage' && empty($absolute_number)) {
2303
                            continue;
2304
                        }
2305
                        if ($number_of_answers[$option['question_id']] == 0) {
2306
                            $answers_number = 0;
2307
                        } else {
2308
                            $answers_number = $absolute_number / $number_of_answers[$option['question_id']] * 100;
0 ignored issues
show
Bug introduced by
The variable $option seems to be defined by a foreach iteration on line 2273. Are you sure the iterator is never empty, otherwise this variable is not defined?

It seems like you are relying on a variable being defined by an iteration:

foreach ($a as $b) {
}

// $b is defined here only if $a has elements, for example if $a is array()
// then $b would not be defined here. To avoid that, we recommend to set a
// default value for $b.


// Better
$b = 0; // or whatever default makes sense in your context
foreach ($a as $b) {
}

// $b is now guaranteed to be defined here.
Loading history...
2309
                        }
2310
                        echo '	<tr>';
2311
                        echo '		<td class="center">' . $value['option_text'] . '</td>';
2312
                        echo '		<td class="center">';
2313
                        if ($absolute_number != 0) {
2314
                            echo '<a href="' . api_get_path(WEB_CODE_PATH) . 'survey/reporting.php?action=' . $action . '&survey_id=' . $surveyId . '&question=' . $offset . '&viewoption=' . $value['question_option_id'] . '">' . $absolute_number . '</a>';
2315
                        } else {
2316
                            echo '0';
2317
                        }
2318
2319
                        echo '      </td>';
2320
                        echo '		<td class="center">' . round($answers_number, 2) . ' %</td>';
2321
                        echo '		<td class="center">';
2322
                        $size = $answers_number * 2;
2323
                        if ($size > 0) {
2324
                            echo '<div style="border:1px solid #264269; background-color:#aecaf4; height:10px; width:' . $size . 'px">&nbsp;</div>';
2325
                        } else {
2326
                            echo '<div style="text-align: left;">' . get_lang("NoDataAvailable") . '</div>';
2327
                        }
2328
                        echo ' </td>';
2329
                        echo ' </tr>';
2330
                    }
2331
                }
2332
                // displaying the table: footer (totals)
2333
                echo '	<tr>';
2334
                echo '		<td class="total"><b>' . get_lang('Total') . '</b></td>';
2335
                echo '		<td class="total"><b>' . ($number_of_answers[$option['question_id']] == 0 ? '0' : $number_of_answers[$option['question_id']]) . '</b></td>';
2336
                echo '		<td class="total">&nbsp;</td>';
2337
                echo '		<td class="total">&nbsp;</td>';
2338
                echo '	</tr>';
2339
2340
                echo '</table>';
2341
2342
                echo '</div>';
2343
            }
2344
        }
2345
        if (isset($_GET['viewoption'])) {
2346
            echo '<div class="answered-people">';
2347
2348
            echo '<h4>'.get_lang('PeopleWhoAnswered').': '.strip_tags($options[Security::remove_XSS($_GET['viewoption'])]['option_text']).'</h4>';
2349
2350
            if (is_numeric($_GET['value'])) {
2351
                $sql_restriction = "AND value='".Database::escape_string($_GET['value'])."'";
2352
            }
2353
2354
            $sql = "SELECT user FROM $table_survey_answer
2355
                    WHERE
2356
                        c_id = $course_id AND
2357
                        option_id = '".Database::escape_string($_GET['viewoption'])."'
2358
                        $sql_restriction";
2359
            $result = Database::query($sql);
2360
            echo '<ul>';
2361 View Code Duplication
            while ($row = Database::fetch_array($result)) {
2362
                $user_info = api_get_user_info($row['user']);
2363
                echo '<li><a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action=userreport&survey_id='.$surveyId.'&user='.$row['user'].'">'.$user_info['complete_name'].'</a></li>';
2364
            }
2365
            echo '</ul>';
2366
            echo '</div>';
2367
        }
2368
    }
2369
2370
    /**
2371
     * Display score data about a survey question
2372
     * @param	array	Question info
2373
     * @param	integer	The offset of results shown
2374
     * @return	void 	(direct output)
2375
     */
2376
    public static function display_question_report_score($survey_data, $question, $offset)
2377
    {
2378
        // Database table definitions
2379
        $table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
2380
        $table_survey_answer 			= Database :: get_course_table(TABLE_SURVEY_ANSWER);
2381
2382
        $course_id = api_get_course_int_id();
2383
2384
        // Getting the options
2385
        $sql = "SELECT * FROM $table_survey_question_option
2386
                WHERE
2387
                    c_id = $course_id AND
2388
                    survey_id='".Database::escape_string($_GET['survey_id'])."' AND
2389
                    question_id = '".Database::escape_string($question['question_id'])."'
2390
                ORDER BY sort ASC";
2391
        $result = Database::query($sql);
2392
        while ($row = Database::fetch_array($result)) {
2393
            $options[$row['question_option_id']] = $row;
2394
        }
2395
2396
        // Getting the answers
2397
        $sql = "SELECT *, count(answer_id) as total FROM $table_survey_answer
2398
                WHERE
2399
                   c_id = $course_id AND
2400
                   survey_id='".Database::escape_string($_GET['survey_id'])."' AND
2401
                   question_id = '".Database::escape_string($question['question_id'])."'
2402
                GROUP BY option_id, value";
2403
        $result = Database::query($sql);
2404
        $number_of_answers = 0;
2405 View Code Duplication
        while ($row = Database::fetch_array($result)) {
2406
            $number_of_answers += $row['total'];
2407
            $data[$row['option_id']][$row['value']] = $row;
2408
        }
2409
2410
        $chartData = array();
2411
        foreach ($options as $option) {
2412
            $optionText = strip_tags($option['option_text']);
2413
            $optionText = html_entity_decode($optionText);
2414
            for ($i = 1; $i <= $question['max_value']; $i++) {
2415
                $votes = $data[$option['question_option_id']][$i]['total'];
2416
                if (empty($votes)) {
2417
                    $votes = '0';
2418
                }
2419
                array_push(
2420
                    $chartData,
2421
                    array(
2422
                        'serie' => $optionText,
2423
                        'option' => $i,
2424
                        'votes' => $votes
2425
                    )
2426
                );
2427
            }
2428
        }
2429
        echo '<div id="chartContainer" class="col-md-12">';
2430
        echo self::drawChart($chartData, true);
2431
        echo '</div>';
2432
2433
        // Displaying the table: headers
2434
        echo '<table class="data_table">';
2435
        echo '	<tr>';
2436
        echo '		<th>&nbsp;</th>';
2437
        echo '		<th>'.get_lang('Score').'</th>';
2438
        echo '		<th>'.get_lang('AbsoluteTotal').'</th>';
2439
        echo '		<th>'.get_lang('Percentage').'</th>';
2440
        echo '		<th>'.get_lang('VisualRepresentation').'</th>';
2441
        echo '	<tr>';
2442
        // Displaying the table: the content
2443
        foreach ($options as $key => & $value) {
2444
            for ($i = 1; $i <= $question['max_value']; $i++) {
2445
                $absolute_number = $data[$value['question_option_id']][$i]['total'];
2446
                echo '	<tr>';
2447
                echo '		<td>'.$value['option_text'].'</td>';
2448
                echo '		<td>'.$i.'</td>';
2449
                echo '		<td><a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action='.$action.'&survey_id='.Security::remove_XSS($_GET['survey_id']).'&question='.Security::remove_XSS($offset).'&viewoption='.$value['question_option_id'].'&value='.$i.'">'.$absolute_number.'</a></td>';
0 ignored issues
show
Bug introduced by
The variable $action does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
2450
                echo '		<td>'.round($absolute_number/$number_of_answers*100, 2).' %</td>';
2451
                echo '		<td>';
2452
                $size = ($absolute_number/$number_of_answers*100*2);
2453
                if ($size > 0) {
2454
                    echo '			<div style="border:1px solid #264269; background-color:#aecaf4; height:10px; width:'.$size.'px">&nbsp;</div>';
2455
                }
2456
                echo '		</td>';
2457
                echo '	</tr>';
2458
            }
2459
        }
2460
        // Displaying the table: footer (totals)
2461
        echo '	<tr>';
2462
        echo '		<td style="border-top:1px solid black"><b>'.get_lang('Total').'</b></td>';
2463
        echo '		<td style="border-top:1px solid black">&nbsp;</td>';
2464
        echo '		<td style="border-top:1px solid black"><b>'.$number_of_answers.'</b></td>';
2465
        echo '		<td style="border-top:1px solid black">&nbsp;</td>';
2466
        echo '		<td style="border-top:1px solid black">&nbsp;</td>';
2467
        echo '	</tr>';
2468
2469
        echo '</table>';
2470
    }
2471
2472
    /**
2473
     * This functions displays the complete reporting
2474
     * @return	string	HTML code
2475
     * @todo open questions are not in the complete report yet.
2476
     * @author Patrick Cool <[email protected]>, Ghent University
2477
     * @version February 2007
2478
     */
2479
    public static function display_complete_report($survey_data)
2480
    {
2481
        // Database table definitions
2482
        $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
2483
        $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
2484
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
2485
2486
        // Actions bar
2487
        echo '<div class="actions">';
2488
        echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.Security::remove_XSS($_GET['survey_id']).'">
2489
		'.Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('ReportingOverview'),'',ICON_SIZE_MEDIUM).'</a>';
2490
        echo '<a class="survey_export_link" href="javascript: void(0);" onclick="document.form1a.submit();">
2491
		'.Display::return_icon('export_csv.png',get_lang('ExportAsCSV'),'',ICON_SIZE_MEDIUM).'</a>';
2492
        echo '<a class="survey_export_link" href="javascript: void(0);" onclick="document.form1b.submit();">
2493
		'.Display::return_icon('export_excel.png',get_lang('ExportAsXLS'),'',ICON_SIZE_MEDIUM).'</a>';
2494
        echo '</div>';
2495
2496
        // The form
2497
        echo '<form id="form1a" name="form1a" method="post" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.Security::remove_XSS($_GET['survey_id']).'">';
2498
        echo '<input type="hidden" name="export_report" value="export_report">';
2499
        echo '<input type="hidden" name="export_format" value="csv">';
2500
        echo '</form>';
2501
        echo '<form id="form1b" name="form1b" method="post" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.Security::remove_XSS($_GET['survey_id']).'">';
2502
        echo '<input type="hidden" name="export_report" value="export_report">';
2503
        echo '<input type="hidden" name="export_format" value="xls">';
2504
        echo '</form>';
2505
2506
        echo '<form id="form2" name="form2" method="post" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.Security::remove_XSS($_GET['survey_id']).'">';
2507
2508
        // The table
2509
        echo '<br /><table class="data_table" border="1">';
2510
        // Getting the number of options per question
2511
        echo '	<tr>';
2512
        echo '		<th>';
2513
        if (isset($_POST['submit_question_filter']) && $_POST['submit_question_filter'] ||
2514
            isset($_POST['export_report']) && $_POST['export_report']) {
2515
            echo '<button class="cancel" type="submit" name="reset_question_filter" value="'.get_lang('ResetQuestionFilter').'">'.get_lang('ResetQuestionFilter').'</button>';
2516
        }
2517
        echo '<button class="save" type="submit" name="submit_question_filter" value="'.get_lang('SubmitQuestionFilter').'">'.get_lang('SubmitQuestionFilter').'</button>';
2518
        echo '</th>';
2519
2520
        $display_extra_user_fields = false;
2521
        if (!(isset($_POST['submit_question_filter']) && $_POST['submit_question_filter'] ||
2522
                isset($_POST['export_report']) && $_POST['export_report']) || !empty($_POST['fields_filter'])) {
2523
            // Show user fields section with a big th colspan that spans over all fields
2524
            $extra_user_fields = UserManager::get_extra_fields(0, 0, 5, 'ASC', false, true);
2525
            $num = count($extra_user_fields);
2526
            if ($num > 0 ) {
2527
                echo '<th '.($num>0?' colspan="'.$num.'"':'').'>';
2528
                echo '<label><input type="checkbox" name="fields_filter" value="1" checked="checked"/> ';
2529
                echo get_lang('UserFields');
2530
                echo '</label>';
2531
                echo '</th>';
2532
                $display_extra_user_fields = true;
2533
            }
2534
        }
2535
2536
        $course_id = api_get_course_int_id();
2537
2538
        // Get all the questions ordered by the "sort" column
2539
        // <hub> modify the query to display open questions too
2540
        //		$sql = "SELECT q.question_id, q.type, q.survey_question, count(o.question_option_id) as number_of_options
2541
        //				FROM $table_survey_question q LEFT JOIN $table_survey_question_option o
2542
        //				ON q.question_id = o.question_id
2543
        //				WHERE q.question_id = o.question_id
2544
        //				AND q.survey_id = '".Database::escape_string($_GET['survey_id'])."'
2545
        //				GROUP BY q.question_id
2546
        //				ORDER BY q.sort ASC";
2547
        $sql = "SELECT q.question_id, q.type, q.survey_question, count(o.question_option_id) as number_of_options
2548
				FROM $table_survey_question q LEFT JOIN $table_survey_question_option o
2549
				ON q.question_id = o.question_id
2550
				WHERE q.survey_id = '".Database::escape_string($_GET['survey_id'])."' AND
2551
				q.c_id = $course_id AND
2552
				o.c_id = $course_id
2553
				GROUP BY q.question_id
2554
				ORDER BY q.sort ASC";
2555
        // </hub>
2556
        $result = Database::query($sql);
2557
        while ($row = Database::fetch_array($result)) {
2558
            // We show the questions if
2559
            // 1. there is no question filter and the export button has not been clicked
2560
            // 2. there is a quesiton filter but the question is selected for display
2561
            //if (!($_POST['submit_question_filter'] || $_POST['export_report']) || in_array($row['question_id'], $_POST['questions_filter'])) {
2562
            if (!(isset($_POST['submit_question_filter']) && $_POST['submit_question_filter']) ||
2563
                (is_array($_POST['questions_filter']) &&
2564
                    in_array($row['question_id'], $_POST['questions_filter']))) {
2565
                // We do not show comment and pagebreak question types
2566
                if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
2567
                    echo ' <th';
2568
                    // <hub> modified tst to include percentage
2569
                    if ($row['number_of_options'] > 0 && $row['type'] != 'percentage') {
2570
                        // </hub>
2571
                        echo ' colspan="'.$row['number_of_options'].'"';
2572
                    }
2573
                    echo '>';
2574
2575
                    echo '<label><input type="checkbox" name="questions_filter[]" value="'.$row['question_id'].'" checked="checked"/> ';
2576
                    echo $row['survey_question'];
2577
                    echo '</label>';
2578
                    echo '</th>';
2579
                }
2580
                // No column at all if it's not a question
2581
            }
2582
            $questions[$row['question_id']] = $row;
2583
        }
2584
        echo '	</tr>';
2585
        // Getting all the questions and options
2586
        echo '	<tr>';
2587
        echo '		<th>&nbsp;</th>'; // the user column
2588
2589
        if (!(isset($_POST['submit_question_filter']) && $_POST['submit_question_filter'] ||
2590
                isset($_POST['export_report']) && $_POST['export_report']) || !empty($_POST['fields_filter'])) {
2591
            //show the fields names for user fields
2592
            foreach($extra_user_fields as & $field) {
2593
                echo '<th>'.$field[3].'</th>';
2594
            }
2595
        }
2596
2597
        // cells with option (none for open question)
2598
        $sql = "SELECT 	sq.question_id, sq.survey_id,
2599
						sq.survey_question, sq.display,
2600
						sq.sort, sq.type, sqo.question_option_id,
2601
						sqo.option_text, sqo.sort as option_sort
2602
				FROM $table_survey_question sq
2603
				LEFT JOIN $table_survey_question_option sqo
2604
				ON sq.question_id = sqo.question_id
2605
				WHERE
2606
				    sq.survey_id = '".Database::escape_string($_GET['survey_id'])."' AND
2607
                    sq.c_id = $course_id AND
2608
                    sqo.c_id = $course_id
2609
				ORDER BY sq.sort ASC, sqo.sort ASC";
2610
        $result = Database::query($sql);
2611
2612
        $display_percentage_header = 1;	// in order to display only once the cell option (and not 100 times)
2613
        while ($row = Database::fetch_array($result)) {
2614
            // We show the options if
2615
            // 1. there is no question filter and the export button has not been clicked
2616
            // 2. there is a question filter but the question is selected for display
2617
            //if (!($_POST['submit_question_filter'] || $_POST['export_report']) || in_array($row['question_id'], $_POST['questions_filter'])) {
2618
            if (!(isset($_POST['submit_question_filter']) && $_POST['submit_question_filter']) ||
2619
                (is_array($_POST['questions_filter']) && in_array($row['question_id'], $_POST['questions_filter']))
2620
            ) {
2621
                // <hub> modif 05-05-2010
2622
                // we do not show comment and pagebreak question types
2623
                if ($row['type'] == 'open') {
2624
                    echo '<th>&nbsp;-&nbsp;</th>';
2625
                    $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
2626
                    $display_percentage_header = 1;
2627
                } else if ($row['type'] == 'percentage' && $display_percentage_header) {
2628
                    echo '<th>&nbsp;%&nbsp;</th>';
2629
                    $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
2630
                    $display_percentage_header = 0;
2631
                } else if ($row['type'] == 'percentage') {
2632
                    $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
2633
                } else if ($row['type'] <> 'comment' AND $row['type'] <> 'pagebreak' AND $row['type'] <> 'percentage') {
2634
                    echo '<th>';
2635
                    echo $row['option_text'];
2636
                    echo '</th>';
2637
                    $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
2638
                    $display_percentage_header = 1;
2639
                }
2640
                //no column at all if the question was not a question
2641
                // </hub>
2642
            }
2643
        }
2644
2645
        echo '	</tr>';
2646
2647
        // Getting all the answers of the users
2648
        $old_user = '';
2649
        $answers_of_user = array();
2650
        $sql = "SELECT * FROM $table_survey_answer
2651
                WHERE
2652
                    c_id = $course_id AND
2653
                    survey_id='".intval($_GET['survey_id'])."'
2654
                ORDER BY user ASC";
2655
        $result = Database::query($sql);
2656
        $i = 1;
2657
        while ($row = Database::fetch_array($result)) {
2658
            if ($old_user != $row['user'] && $old_user != '') {
2659
                $userParam = $old_user;
2660
                if ($survey_data['anonymous'] != 0) {
2661
                    $userParam = $i;
2662
                    $i++;
2663
                }
2664
                SurveyUtil::display_complete_report_row(
2665
                    $survey_data,
2666
                    $possible_answers,
2667
                    $answers_of_user,
2668
                    $userParam,
2669
                    $questions,
2670
                    $display_extra_user_fields
2671
                );
2672
                $answers_of_user=array();
2673
            }
2674
            if (isset($questions[$row['question_id']]) && $questions[$row['question_id']]['type'] != 'open') {
2675
                $answers_of_user[$row['question_id']][$row['option_id']] = $row;
2676
            } else {
2677
                $answers_of_user[$row['question_id']][0] = $row;
2678
            }
2679
            $old_user = $row['user'];
2680
        }
2681
        $userParam = $old_user;
2682
        if ($survey_data['anonymous'] != 0) {
2683
            $userParam = $i;
2684
            $i++;
2685
        }
2686
        SurveyUtil::display_complete_report_row(
2687
            $survey_data,
2688
            $possible_answers,
2689
            $answers_of_user,
2690
            $userParam,
2691
            $questions,
2692
            $display_extra_user_fields
2693
        );
2694
        // This is to display the last user
2695
        echo '</table>';
2696
        echo '</form>';
2697
    }
2698
2699
    /**
2700
     * This function displays a row (= a user and his/her answers) in the table of the complete report.
2701
     *
2702
     * @param array $survey_data
2703
     * @param 	array	Possible options
2704
     * @param 	array 	User answers
2705
     * @param	mixed	User ID or user details string
2706
     * @param	boolean	Whether to show extra user fields or not
2707
     * @author Patrick Cool <[email protected]>, Ghent University
2708
     * @version February 2007 - Updated March 2008
2709
     */
2710
    static function display_complete_report_row(
2711
        $survey_data,
2712
        $possible_options,
2713
        $answers_of_user,
2714
        $user,
2715
        $questions,
2716
        $display_extra_user_fields = false
2717
    ) {
2718
        $user = Security::remove_XSS($user);
2719
        echo '<tr>';
2720
        if ($survey_data['anonymous'] == 0) {
2721
            if (intval($user) !== 0) {
2722
                $userInfo = api_get_user_info($user);
2723
                if (!empty($userInfo)) {
2724
                    $user_displayed = $userInfo['complete_name'];
2725
                } else {
2726
                    $user_displayed = '-';
2727
                }
2728
                echo '<th><a href="'.api_get_self().'?action=userreport&survey_id='.Security::remove_XSS($_GET['survey_id']).'&user='.$user.'">'.
2729
                    $user_displayed.'</a></th>'; // the user column
2730
            } else {
2731
                echo '<th>'.$user.'</th>'; // the user column
2732
            }
2733
        } else {
2734
            echo '<th>' . get_lang('Anonymous') . ' ' . $user . '</th>';
2735
        }
2736
2737
        if ($display_extra_user_fields) {
2738
            // Show user fields data, if any, for this user
2739
            $user_fields_values = UserManager::get_extra_user_data(intval($user), false, false, false, true);
2740
            foreach ($user_fields_values as & $value) {
2741
                echo '<td align="center">'.$value.'</td>';
2742
            }
2743
        }
2744
        if (is_array($possible_options)) {
2745
            // <hub> modified to display open answers and percentage
2746
            foreach ($possible_options as $question_id => & $possible_option) {
2747
                if ($questions[$question_id]['type'] == 'open') {
2748
                    echo '<td align="center">';
2749
                    echo $answers_of_user[$question_id]['0']['option_id'];
2750
                    echo '</td>';
2751
                } else {
2752
                    foreach ($possible_option as $option_id => & $value) {
2753
                        if ($questions[$question_id]['type'] == 'percentage') {
2754 View Code Duplication
                            if (!empty($answers_of_user[$question_id][$option_id])) {
2755
                                echo "<td align='center'>";
2756
                                echo $answers_of_user[$question_id][$option_id]['value'];
2757
                                echo "</td>";
2758
                            }
2759
                        }
2760
                        else {
2761
                            echo '<td align="center">';
2762
                            if (!empty($answers_of_user[$question_id][$option_id])) {
2763 View Code Duplication
                                if ($answers_of_user[$question_id][$option_id]['value'] != 0) {
2764
                                    echo $answers_of_user[$question_id][$option_id]['value'];
2765
                                }
2766
                                else {
2767
                                    echo 'v';
2768
                                }
2769
                            }
2770
                        } // </hub>
2771
                    }
2772
                }
2773
            }
2774
        }
2775
        echo '</tr>';
2776
    }
2777
2778
    /**
2779
     * Quite similar to display_complete_report(), returns an HTML string
2780
     * that can be used in a csv file
2781
     * @todo consider merging this function with display_complete_report
2782
     * @return	string	The contents of a csv file
2783
     * @author Patrick Cool <[email protected]>, Ghent University
2784
     * @version February 2007
2785
     */
2786
    public static function export_complete_report($survey_data, $user_id = 0)
2787
    {
2788
        // Database table definitions
2789
        $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
2790
        $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
2791
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
2792
2793
        // The first column
2794
        $return = ';';
2795
2796
        // Show extra fields blank space (enough for extra fields on next line)
2797
2798
        $extra_user_fields = UserManager::get_extra_fields(0, 0, 5, 'ASC', false, true);
2799
2800
        $num = count($extra_user_fields);
2801
        $return .= str_repeat(';', $num);
2802
2803
        $course_id = api_get_course_int_id();
2804
2805
        $sql = "SELECT
2806
                    questions.question_id,
2807
                    questions.type,
2808
                    questions.survey_question,
2809
                    count(options.question_option_id) as number_of_options
2810
				FROM $table_survey_question questions
2811
                LEFT JOIN $table_survey_question_option options
2812
				ON questions.question_id = options.question_id  AND options.c_id = $course_id
2813
				WHERE
2814
				    questions.survey_id = '".intval($_GET['survey_id'])."' AND
2815
                    questions.c_id = $course_id
2816
				GROUP BY questions.question_id
2817
				ORDER BY questions.sort ASC";
2818
        $result = Database::query($sql);
2819
        while ($row = Database::fetch_array($result)) {
2820
            // We show the questions if
2821
            // 1. there is no question filter and the export button has not been clicked
2822
            // 2. there is a quesiton filter but the question is selected for display
2823
            if (!($_POST['submit_question_filter']) ||
2824
                (is_array($_POST['questions_filter']) &&
2825
                    in_array($row['question_id'], $_POST['questions_filter']))
2826
            ) {
2827
                // We do not show comment and pagebreak question types
2828
                if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
2829
                    if ($row['number_of_options'] == 0 && $row['type'] == 'open') {
2830
                        $return .= str_replace("\r\n",'  ', api_html_entity_decode(strip_tags($row['survey_question']), ENT_QUOTES)).';';
2831
                    } else {
2832
                        for ($ii = 0; $ii < $row['number_of_options']; $ii++) {
2833
                            $return .= str_replace("\r\n",'  ', api_html_entity_decode(strip_tags($row['survey_question']), ENT_QUOTES)).';';
2834
                        }
2835
                    }
2836
                }
2837
            }
2838
        }
2839
        $return .= "\n";
2840
2841
        // Getting all the questions and options
2842
        $return .= ';';
2843
2844
        // Show the fields names for user fields
2845
        if (!empty($extra_user_fields)) {
2846
            foreach ($extra_user_fields as & $field) {
2847
                $return .= '"'.str_replace("\r\n",'  ',api_html_entity_decode(strip_tags($field[3]), ENT_QUOTES)).'";';
2848
            }
2849
        }
2850
2851
        $sql = "SELECT
2852
		            survey_question.question_id,
2853
		            survey_question.survey_id,
2854
		            survey_question.survey_question,
2855
		            survey_question.display,
2856
		            survey_question.sort,
2857
		            survey_question.type,
2858
                    survey_question_option.question_option_id,
2859
                    survey_question_option.option_text,
2860
                    survey_question_option.sort as option_sort
2861
				FROM $table_survey_question survey_question
2862
				LEFT JOIN $table_survey_question_option survey_question_option
2863
				ON
2864
				    survey_question.question_id = survey_question_option.question_id AND
2865
				    survey_question_option.c_id = $course_id
2866
				WHERE
2867
				    survey_question.survey_id = '".intval($_GET['survey_id'])."' AND
2868
				    survey_question.c_id = $course_id
2869
				ORDER BY survey_question.sort ASC, survey_question_option.sort ASC";
2870
        $result = Database::query($sql);
2871
        $possible_answers = array();
2872
        $possible_answers_type = array();
2873
        while ($row = Database::fetch_array($result)) {
2874
            // We show the options if
2875
            // 1. there is no question filter and the export button has not been clicked
2876
            // 2. there is a quesiton filter but the question is selected for display
2877
            if (!($_POST['submit_question_filter']) || (is_array($_POST['questions_filter']) &&
2878
                in_array($row['question_id'], $_POST['questions_filter']))
2879
            ) {
2880
                // We do not show comment and pagebreak question types
2881
                if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
2882
                    $row['option_text'] = str_replace(array("\r","\n"),array('',''),$row['option_text']);
2883
                    $return .= api_html_entity_decode(strip_tags($row['option_text']), ENT_QUOTES).';';
2884
                    $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
2885
                    $possible_answers_type[$row['question_id']] = $row['type'];
2886
                }
2887
            }
2888
        }
2889
        $return .= "\n";
2890
2891
        // Getting all the answers of the users
2892
        $old_user = '';
2893
        $answers_of_user = array();
2894
        $sql = "SELECT * FROM $table_survey_answer
2895
		        WHERE c_id = $course_id AND survey_id='".Database::escape_string($_GET['survey_id'])."'";
2896
        if ($user_id != 0) {
2897
            $sql .= "AND user='".Database::escape_string($user_id)."' ";
2898
        }
2899
        $sql .= "ORDER BY user ASC";
2900
2901
        $open_question_iterator = 1;
2902
        $result = Database::query($sql);
2903
        while ($row = Database::fetch_array($result)) {
2904
            if ($old_user != $row['user'] && $old_user != '') {
2905
                $return .= SurveyUtil::export_complete_report_row(
2906
                    $survey_data,
2907
                    $possible_answers,
2908
                    $answers_of_user,
2909
                    $old_user,
2910
                    true
2911
                );
2912
                $answers_of_user=array();
2913
            }
2914 View Code Duplication
            if($possible_answers_type[$row['question_id']] == 'open') {
2915
                $temp_id = 'open'.$open_question_iterator;
2916
                $answers_of_user[$row['question_id']][$temp_id] = $row;
2917
                $open_question_iterator++;
2918
            } else {
2919
                $answers_of_user[$row['question_id']][$row['option_id']] = $row;
2920
            }
2921
            $old_user = $row['user'];
2922
        }
2923
        // This is to display the last user
2924
        $return .= SurveyUtil::export_complete_report_row(
2925
            $survey_data,
2926
            $possible_answers,
2927
            $answers_of_user,
2928
            $old_user,
2929
            true
2930
        );
2931
2932
        return $return;
2933
    }
2934
2935
    /**
2936
     * Add a line to the csv file
2937
     *
2938
     * @param	array	Possible answers
2939
     * @param	array	User's answers
2940
     * @param 	mixed	User ID or user details as string - Used as a string in the result string
2941
     * @param	boolean	Whether to display user fields or not
2942
     * @return	string	One line of the csv file
2943
     * @author Patrick Cool <[email protected]>, Ghent University
2944
     * @version February 2007
2945
     */
2946
    static function export_complete_report_row(
2947
        $survey_data,
2948
        $possible_options,
2949
        $answers_of_user,
2950
        $user,
2951
        $display_extra_user_fields = false
2952
    ) {
2953
        $return = '';
2954
        if ($survey_data['anonymous'] == 0) {
2955
            if (intval($user) !== 0) {
2956
                $userInfo = api_get_user_info($user);
2957
2958
                if (!empty($userInfo)) {
2959
                    $user_displayed = $userInfo['complete_name'];
2960
                } else {
2961
                    $user_displayed = '-';
2962
                }
2963
                $return .= $user_displayed.';';
2964
            } else {
2965
                $return .= $user.';';
2966
            }
2967
        } else {
2968
            $return .= '-;'; // The user column
2969
        }
2970
2971 View Code Duplication
        if ($display_extra_user_fields) {
2972
            // Show user fields data, if any, for this user
2973
            $user_fields_values = UserManager::get_extra_user_data($user,false,false, false, true);
2974
            foreach ($user_fields_values as & $value) {
2975
                $return .= '"'.str_replace('"', '""', api_html_entity_decode(strip_tags($value), ENT_QUOTES)).'";';
2976
            }
2977
        }
2978
2979
        if (is_array($possible_options)) {
2980
            foreach ($possible_options as $question_id => $possible_option) {
2981
                if (is_array($possible_option) && count($possible_option) > 0) {
2982
                    foreach ($possible_option as $option_id => & $value) {
2983
                        $my_answer_of_user = ($answers_of_user[$question_id] == null) ? array() : $answers_of_user[$question_id];
2984
                        $key = array_keys($my_answer_of_user);
2985
                        if (substr($key[0], 0, 4) == 'open') {
2986
                            $return .= '"'.str_replace('"', '""', api_html_entity_decode(strip_tags($answers_of_user[$question_id][$key[0]]['option_id']), ENT_QUOTES)).'"';
2987
                        } elseif (!empty($answers_of_user[$question_id][$option_id])) {
2988
                            //$return .= 'v';
2989
                            if ($answers_of_user[$question_id][$option_id]['value'] != 0) {
2990
                                $return .= $answers_of_user[$question_id][$option_id]['value'];
2991
                            } else {
2992
                                $return .= 'v';
2993
                            }
2994
                        }
2995
                        $return .= ';';
2996
                    }
2997
                }
2998
            }
2999
        }
3000
        $return .= "\n";
3001
        return $return;
3002
    }
3003
3004
    /**
3005
     * Quite similar to display_complete_report(), returns an HTML string
3006
     * that can be used in a csv file
3007
     * @todo consider merging this function with display_complete_report
3008
     * @return	string	The contents of a csv file
3009
     * @author Patrick Cool <[email protected]>, Ghent University
3010
     * @version February 2007
3011
     */
3012
    static function export_complete_report_xls($survey_data, $filename, $user_id = 0)
3013
    {
3014
        $spreadsheet = new PHPExcel();
3015
        $spreadsheet->setActiveSheetIndex(0);
3016
        $worksheet = $spreadsheet->getActiveSheet();
3017
        $line = 0;
3018
        $column = 1; // Skip the first column (row titles)
3019
3020
        // Show extra fields blank space (enough for extra fields on next line)
3021
        //if (!empty($_REQUEST['fields_filter'])) {
3022
        // Show user fields section with a big th colspan that spans over all fields
3023
        $extra_user_fields = UserManager::get_extra_fields(0, 0, 5, 'ASC', false, true);
3024
        $num = count($extra_user_fields);
3025
        for ($i = 0; $i < $num; $i++) {
3026
            $worksheet->SetCellValueByColumnAndRow($line, $column, '');
3027
            $column++;
3028
        }
3029
        $display_extra_user_fields = true;
3030
        //}
3031
3032
        // Database table definitions
3033
        $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
3034
        $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
3035
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
3036
3037
        $course_id = api_get_course_int_id();
3038
3039
        // First line (questions)
3040
        $sql = "SELECT
3041
                    questions.question_id,
3042
                    questions.type,
3043
                    questions.survey_question,
3044
                    count(options.question_option_id) as number_of_options
3045
				FROM $table_survey_question questions
3046
				LEFT JOIN $table_survey_question_option options
3047
                ON questions.question_id = options.question_id AND options.c_id = $course_id
3048
				WHERE
3049
				    questions.survey_id = '".intval($_GET['survey_id'])."' AND
3050
				    questions.c_id = $course_id
3051
				GROUP BY questions.question_id
3052
				ORDER BY questions.sort ASC";
3053
        $result = Database::query($sql);
3054
        while ($row = Database::fetch_array($result)) {
3055
            // We show the questions if
3056
            // 1. there is no question filter and the export button has not been clicked
3057
            // 2. there is a quesiton filter but the question is selected for display
3058
            if (!($_POST['submit_question_filter']) || (is_array($_POST['questions_filter']) &&
3059
                in_array($row['question_id'], $_POST['questions_filter']))
3060
            ) {
3061
                // We do not show comment and pagebreak question types
3062
                if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
3063
                    if ($row['number_of_options'] == 0 && $row['type'] == 'open') {
3064
                        $worksheet->SetCellValueByColumnAndRow(
3065
                            $line,
3066
                            $column,
3067
                            api_html_entity_decode(
3068
                                strip_tags($row['survey_question']),
3069
                                ENT_QUOTES
3070
                            )
3071
                        );
3072
                        $column ++;
3073
                    } else {
3074
                        for ($ii = 0; $ii < $row['number_of_options']; $ii ++) {
3075
                            $worksheet->SetCellValueByColumnAndRow(
3076
                                $line,
3077
                                $column,
3078
                                api_html_entity_decode(
3079
                                    strip_tags($row['survey_question']),
3080
                                    ENT_QUOTES
3081
                                )
3082
                            );
3083
                            $column ++;
3084
                        }
3085
                    }
3086
                }
3087
            }
3088
        }
3089
        $line++;
3090
        $column = 1;
3091
3092
        // Show extra field values
3093
        if ($display_extra_user_fields) {
3094
            // Show the fields names for user fields
3095
            foreach ($extra_user_fields as & $field) {
3096
                $worksheet->SetCellValueByColumnAndRow(
3097
                    $line,
3098
                    $column,
3099
                    api_html_entity_decode(strip_tags($field[3]), ENT_QUOTES)
3100
                );
3101
                $column++;
3102
            }
3103
        }
3104
3105
        // Getting all the questions and options (second line)
3106
        $sql = "SELECT
3107
                    survey_question.question_id, survey_question.survey_id, survey_question.survey_question, survey_question.display, survey_question.sort, survey_question.type,
3108
                    survey_question_option.question_option_id, survey_question_option.option_text, survey_question_option.sort as option_sort
3109
				FROM $table_survey_question survey_question
3110
				LEFT JOIN $table_survey_question_option survey_question_option
3111
				ON survey_question.question_id = survey_question_option.question_id AND survey_question_option.c_id = $course_id
3112
				WHERE survey_question.survey_id = '".intval($_GET['survey_id'])."' AND
3113
				survey_question.c_id = $course_id
3114
				ORDER BY survey_question.sort ASC, survey_question_option.sort ASC";
3115
        $result = Database::query($sql);
3116
        $possible_answers = array();
3117
        $possible_answers_type = array();
3118
        while ($row = Database::fetch_array($result)) {
3119
            // We show the options if
3120
            // 1. there is no question filter and the export button has not been clicked
3121
            // 2. there is a quesiton filter but the question is selected for display
3122
            if (!($_POST['submit_question_filter']) ||
3123
                (is_array($_POST['questions_filter']) && in_array($row['question_id'], $_POST['questions_filter']))
3124
            ) {
3125
                // We do not show comment and pagebreak question types
3126
                if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
3127
                    $worksheet->SetCellValueByColumnAndRow(
3128
                        $line,
3129
                        $column,
3130
                        api_html_entity_decode(
3131
                            strip_tags($row['option_text']),
3132
                            ENT_QUOTES
3133
                        )
3134
                    );
3135
                    $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
3136
                    $possible_answers_type[$row['question_id']] = $row['type'];
3137
                    $column++;
3138
                }
3139
            }
3140
        }
3141
3142
        // Getting all the answers of the users
3143
        $line ++;
3144
        $column = 0;
3145
        $old_user = '';
3146
        $answers_of_user = array();
3147
        $sql = "SELECT * FROM $table_survey_answer
3148
                WHERE c_id = $course_id AND survey_id='".intval($_GET['survey_id'])."' ";
3149
        if ($user_id != 0) {
3150
            $sql .= "AND user='".intval($user_id)."' ";
3151
        }
3152
        $sql .=	"ORDER BY user ASC";
3153
3154
        $open_question_iterator = 1;
3155
        $result = Database::query($sql);
3156
        while ($row = Database::fetch_array($result)) {
3157
            if ($old_user != $row['user'] && $old_user != '') {
3158
                $return = SurveyUtil::export_complete_report_row_xls(
3159
                    $survey_data,
3160
                    $possible_answers,
3161
                    $answers_of_user,
3162
                    $old_user,
3163
                    true
3164
                );
3165
                foreach ($return as $elem) {
3166
                    $worksheet->SetCellValueByColumnAndRow($line, $column, $elem);
3167
                    $column++;
3168
                }
3169
                $answers_of_user = array();
3170
                $line++;
3171
                $column = 0;
3172
            }
3173 View Code Duplication
            if ($possible_answers_type[$row['question_id']] == 'open') {
3174
                $temp_id = 'open'.$open_question_iterator;
3175
                $answers_of_user[$row['question_id']][$temp_id] = $row;
3176
                $open_question_iterator++;
3177
            } else {
3178
                $answers_of_user[$row['question_id']][$row['option_id']] = $row;
3179
            }
3180
            $old_user = $row['user'];
3181
        }
3182
        $return = SurveyUtil::export_complete_report_row_xls(
3183
            $survey_data,
3184
            $possible_answers,
3185
            $answers_of_user,
3186
            $old_user,
3187
            true
3188
        );
3189
3190
        // this is to display the last user
3191
        foreach ($return as $elem) {
3192
            $worksheet->SetCellValueByColumnAndRow($line, $column, $elem);
3193
            $column++;
3194
        }
3195
3196
        $file = api_get_path(SYS_ARCHIVE_PATH).api_replace_dangerous_char($filename);
3197
        $writer = new PHPExcel_Writer_Excel2007($spreadsheet);
3198
        $writer->save($file);
3199
        DocumentManager::file_send_for_download($file, true, $filename);
3200
3201
        return null;
3202
    }
3203
3204
    /**
3205
     * Add a line to the csv file
3206
     *
3207
     * @param	array	Possible answers
3208
     * @param	array	User's answers
3209
     * @param 	mixed	User ID or user details as string - Used as a string in the result string
3210
     * @param	boolean	Whether to display user fields or not
3211
     * @return	string	One line of the csv file
3212
     */
3213
    public static function export_complete_report_row_xls(
3214
        $survey_data,
3215
        $possible_options,
3216
        $answers_of_user,
3217
        $user,
3218
        $display_extra_user_fields = false
3219
    ) {
3220
        $return = array();
3221
        if ($survey_data['anonymous'] == 0) {
3222
            if (intval($user) !== 0) {
3223
                $sql = 'SELECT firstname, lastname
3224
                        FROM '.Database::get_main_table(TABLE_MAIN_USER).'
3225
                        WHERE user_id='.intval($user);
3226
                $rs = Database::query($sql);
3227
                if($row = Database::fetch_array($rs)) {
3228
                    $user_displayed = api_get_person_name($row['firstname'], $row['lastname']);
3229
                } else {
3230
                    $user_displayed = '-';
3231
                }
3232
                $return[] = $user_displayed;
3233
            } else {
3234
                $return[] = $user;
3235
            }
3236
        } else {
3237
            $return[] = '-'; // The user column
3238
        }
3239
3240
        if ($display_extra_user_fields) {
3241
            //show user fields data, if any, for this user
3242
            $user_fields_values = UserManager::get_extra_user_data(intval($user),false,false, false, true);
3243
            foreach($user_fields_values as $value) {
3244
                $return[] = api_html_entity_decode(strip_tags($value), ENT_QUOTES);
3245
            }
3246
        }
3247
3248
        if (is_array($possible_options)) {
3249
            foreach ($possible_options as $question_id => & $possible_option) {
3250
                if (is_array($possible_option) && count($possible_option) > 0) {
3251
                    foreach ($possible_option as $option_id => & $value) {
3252
                        $my_answers_of_user = ($answers_of_user[$question_id]==null) ? array() : $answers_of_user[$question_id];
3253
                        $key = array_keys($my_answers_of_user);
3254
                        if (substr($key[0], 0, 4) == 'open') {
3255
                            $return[] = api_html_entity_decode(strip_tags($answers_of_user[$question_id][$key[0]]['option_id']), ENT_QUOTES);
3256
                        } elseif (!empty($answers_of_user[$question_id][$option_id])) {
3257
                            //$return .= 'v';
3258
                            if ($answers_of_user[$question_id][$option_id]['value'] != 0) {
3259
                                $return[] = $answers_of_user[$question_id][$option_id]['value'];
3260
                            } else {
3261
                                $return[] = 'v';
3262
                            }
3263
                        } else {
3264
                            $return[] = '';
3265
                        }
3266
                    }
3267
                }
3268
            }
3269
        }
3270
3271
        return $return;
3272
    }
3273
3274
    /**
3275
     * This function displays the comparative report which allows you to compare two questions
3276
     * A comparative report creates a table where one question is on the x axis and a second question is on the y axis.
3277
     * In the intersection is the number of people who have answerd positive on both options.
3278
     *
3279
     * @return	string	HTML code
3280
     *
3281
     * @author Patrick Cool <[email protected]>, Ghent University
3282
     * @version February 2007
3283
     */
3284
    public static function display_comparative_report()
3285
    {
3286
        // Allowed question types for comparative report
3287
        $allowed_question_types = array(
3288
            'yesno',
3289
            'multiplechoice',
3290
            'multipleresponse',
3291
            'dropdown',
3292
            'percentage',
3293
            'score',
3294
        );
3295
3296
        // Getting all the questions
3297
        $questions = SurveyManager::get_questions($_GET['survey_id']);
3298
3299
        // Actions bar
3300
        echo '<div class="actions">';
3301
        echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.intval($_GET['survey_id']).'">'.
3302
                Display::return_icon('back.png', get_lang('BackTo').' '.get_lang('ReportingOverview'),'',ICON_SIZE_MEDIUM).'</a>';
3303
        echo '</div>';
3304
3305
        // Displaying an information message that only the questions with predefined answers can be used in a comparative report
3306
        Display::display_normal_message(get_lang('OnlyQuestionsWithPredefinedAnswers'), false);
3307
3308
        // The form for selecting the axis of the table
3309
        echo '<form id="form1" name="form1" method="get" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.intval($_GET['survey_id']).'&xaxis='.Security::remove_XSS($_GET['xaxis']).'&y='.Security::remove_XSS($_GET['yaxis']).'">';
3310
        // Survey_id
3311
        echo '<input type="hidden" name="action" value="'.Security::remove_XSS($_GET['action']).'"/>';
3312
        echo '<input type="hidden" name="survey_id" value="'.Security::remove_XSS($_GET['survey_id']).'"/>';
3313
        // X axis
3314
        echo get_lang('SelectXAxis').': ';
3315
        echo '<select name="xaxis">';
3316
        echo '<option value="">---</option>';
3317 View Code Duplication
        foreach ($questions as $key => & $question) {
3318
            if (is_array($allowed_question_types)) {
3319
                if (in_array($question['type'], $allowed_question_types)) {
3320
                    echo '<option value="'.$question['question_id'].'"';
3321
                    if (isset($_GET['xaxis']) && $_GET['xaxis'] == $question['question_id']) {
3322
                        echo ' selected="selected"';
3323
                    }
3324
                    echo '">'.api_substr(strip_tags($question['question']), 0, 50).'</option>';
3325
                }
3326
            }
3327
3328
        }
3329
        echo '</select><br /><br />';
3330
        // Y axis
3331
        echo get_lang('SelectYAxis').': ';
3332
        echo '<select name="yaxis">';
3333
        echo '<option value="">---</option>';
3334 View Code Duplication
        foreach ($questions as $key => &$question) {
3335
            if (in_array($question['type'], $allowed_question_types)) {
3336
                echo '<option value="'.$question['question_id'].'"';
3337
                if (isset($_GET['yaxis']) && $_GET['yaxis'] == $question['question_id']) {
3338
                    echo ' selected="selected"';
3339
                }
3340
                echo '">'.api_substr(strip_tags($question['question']), 0, 50).'</option>';
3341
            }
3342
        }
3343
        echo '</select><br /><br />';
3344
        echo '<button class="save" type="submit" name="Submit" value="Submit">'.get_lang('CompareQuestions').'</button>';
3345
        echo '</form>';
3346
3347
        // Getting all the information of the x axis
3348 View Code Duplication
        if (isset($_GET['xaxis']) && is_numeric($_GET['xaxis'])) {
3349
            $question_x = SurveyManager::get_question($_GET['xaxis']);
3350
        }
3351
3352
        // Getting all the information of the y axis
3353 View Code Duplication
        if (isset($_GET['yaxis']) && is_numeric($_GET['yaxis'])) {
3354
            $question_y = SurveyManager::get_question($_GET['yaxis']);
3355
        }
3356
3357
        if (isset($_GET['xaxis']) && is_numeric($_GET['xaxis']) && isset($_GET['yaxis']) && is_numeric($_GET['yaxis'])) {
3358
            // Getting the answers of the two questions
3359
            $answers_x = SurveyUtil::get_answers_of_question_by_user($_GET['survey_id'], $_GET['xaxis']);
3360
            $answers_y = SurveyUtil::get_answers_of_question_by_user($_GET['survey_id'], $_GET['yaxis']);
3361
3362
            // Displaying the table
3363
            $tableHtml = '<table border="1" class="data_table">';
3364
3365
            $xOptions = array();
3366
            // The header
3367
            $tableHtml .=  '	<tr>';
3368
            for ($ii = 0; $ii <= count($question_x['answers']); $ii++) {
3369
                if ($ii == 0) {
3370
                    $tableHtml .=  '		<th>&nbsp;</th>';
3371
                } else {
3372
                    if ($question_x['type'] == 'score') {
3373
                        for ($x = 1; $x <= $question_x['maximum_score']; $x++) {
3374
                            $tableHtml .= '		<th>'.$question_x['answers'][($ii-1)].'<br />'.$x.'</th>';
3375
                        }
3376
                        $x = '';
3377
                    } else {
3378
                        $tableHtml .= '		<th>'.$question_x['answers'][($ii-1)].'</th>';
3379
                    }
3380
                    $optionText = strip_tags($question_x['answers'][$ii-1]);
3381
                    $optionText = html_entity_decode($optionText);
3382
                    array_push($xOptions, trim($optionText));
3383
                }
3384
            }
3385
            $tableHtml .=  '	</tr>';
3386
            $chartData = array();
3387
3388
            // The main part
3389
            for ($ij = 0; $ij < count($question_y['answers']); $ij++) {
3390
                $currentYQuestion = strip_tags($question_y['answers'][$ij]);
3391
                $currentYQuestion = html_entity_decode($currentYQuestion);
3392
                // The Y axis is a scoring question type so we have more rows than the options (actually options * maximum score)
3393
                if ($question_y['type'] == 'score') {
3394
                    for ($y = 1; $y <= $question_y['maximum_score']; $y++) {
3395
                        $tableHtml .=  '	<tr>';
3396
                        for ($ii = 0; $ii <= count($question_x['answers']); $ii++) {
3397
                            if ($question_x['type'] == 'score') {
3398 View Code Duplication
                                for ($x = 1; $x <= $question_x['maximum_score']; $x++) {
3399
                                    if ($ii == 0) {
3400
                                        $tableHtml .=  ' <th>'.$question_y['answers'][($ij)].' '.$y.'</th>';
3401
                                        break;
3402
                                    } else {
3403
                                        $tableHtml .=  ' <td align="center">';
3404
                                        $votes = SurveyUtil::comparative_check(
3405
                                            $answers_x,
3406
                                            $answers_y,
3407
                                            $question_x['answersid'][($ii - 1)],
3408
                                            $question_y['answersid'][($ij)],
3409
                                            $x,
3410
                                            $y
3411
                                        );
3412
                                        $tableHtml .=  $votes;
3413
                                        array_push(
3414
                                            $chartData,
3415
                                            array(
3416
                                                'serie' => array($currentYQuestion, $xOptions[$ii-1]),
3417
                                                'option' => $x,
3418
                                                'votes' => $votes
3419
                                            )
3420
                                        );
3421
                                        $tableHtml .=  '</td>';
3422
                                    }
3423
                                }
3424
                            } else {
3425
                                if ($ii == 0) {
3426
                                    $tableHtml .=  '<th>'.$question_y['answers'][$ij].' '.$y.'</th>';
3427
                                } else {
3428
                                    $tableHtml .=  '<td align="center">';
3429
                                    $votes = SurveyUtil::comparative_check(
3430
                                        $answers_x,
3431
                                        $answers_y,
3432
                                        $question_x['answersid'][($ii - 1)],
3433
                                        $question_y['answersid'][($ij)],
3434
                                        0,
3435
                                        $y
3436
                                    );
3437
                                    $tableHtml .= $votes;
3438
                                    array_push(
3439
                                        $chartData,
3440
                                        array(
3441
                                            'serie' => array($currentYQuestion, $xOptions[$ii-1]),
3442
                                            'option' => $y,
3443
                                            'votes' => $votes
3444
                                        )
3445
                                    );
3446
                                    $tableHtml .=  '</td>';
3447
                                }
3448
                            }
3449
                        }
3450
                        $tableHtml .=  '	</tr>';
3451
                    }
3452
                }
3453
                // The Y axis is NOT a score question type so the number of rows = the number of options
3454
                else {
3455
                    $tableHtml .=  '	<tr>';
3456
                    for ($ii = 0; $ii <= count($question_x['answers']); $ii++) {
3457
                        if ($question_x['type'] == 'score') {
3458 View Code Duplication
                            for ($x = 1; $x <= $question_x['maximum_score']; $x++) {
3459
                                if ($ii == 0) {
3460
                                    $tableHtml .=  '		<th>'.$question_y['answers'][$ij].'</th>';
3461
                                    break;
3462
                                } else {
3463
                                    $tableHtml .=  '		<td align="center">';
3464
                                    $votes =  SurveyUtil::comparative_check($answers_x, $answers_y, $question_x['answersid'][($ii-1)], $question_y['answersid'][($ij)], $x, 0);
3465
                                    $tableHtml .= $votes;
3466
                                    array_push(
3467
                                        $chartData,
3468
                                        array(
3469
                                            'serie' => array($currentYQuestion, $xOptions[$ii-1]),
3470
                                            'option' => $x,
3471
                                            'votes' => $votes
3472
                                        )
3473
                                    );
3474
                                    $tableHtml .=  '</td>';
3475
                                }
3476
                            }
3477
                        } else {
3478
                            if ($ii == 0) {
3479
                                $tableHtml .=  '		<th>'.$question_y['answers'][($ij)].'</th>';
3480
                            } else {
3481
                                $tableHtml .=  '		<td align="center">';
3482
                                $votes = SurveyUtil::comparative_check($answers_x, $answers_y, $question_x['answersid'][($ii-1)], $question_y['answersid'][($ij)]);
3483
                                $tableHtml .= $votes;
3484
                                array_push(
3485
                                    $chartData,
3486
                                    array(
3487
                                        'serie' => $xOptions[$ii-1],
3488
                                        'option' => $currentYQuestion,
3489
                                        'votes' => $votes
3490
                                    )
3491
                                );
3492
                                $tableHtml .=  '</td>';
3493
                            }
3494
                        }
3495
                    }
3496
                    $tableHtml .=  '	</tr>';
3497
                }
3498
            }
3499
            $tableHtml .=  '</table>';
3500
            echo '<div id="chartContainer" class="col-md-12">';
3501
            echo self::drawChart($chartData, true);
3502
            echo '</div>';
3503
            echo $tableHtml;
3504
        }
3505
    }
3506
3507
    /**
3508
     * Get all the answers of a question grouped by user
3509
     *
3510
     * @param	integer	Survey ID
3511
     * @param	integer	Question ID
3512
     * @return 	Array	Array containing all answers of all users, grouped by user
3513
     *
3514
     * @author Patrick Cool <[email protected]>, Ghent University
3515
     * @version February 2007 - Updated March 2008
3516
     */
3517
    public static function get_answers_of_question_by_user($survey_id, $question_id)
3518
    {
3519
        $course_id = api_get_course_int_id();
3520
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
3521
3522
        $sql = "SELECT * FROM $table_survey_answer
3523
                WHERE c_id = $course_id AND survey_id='".intval($survey_id)."'
3524
                AND question_id='".intval($question_id)."'
3525
                ORDER BY USER ASC";
3526
        $result = Database::query($sql);
3527
        while ($row = Database::fetch_array($result)) {
3528
            if ($row['value'] == 0) {
3529
                $return[$row['user']][] = $row['option_id'];
3530
            } else {
3531
                $return[$row['user']][] = $row['option_id'].'*'.$row['value'];
3532
            }
3533
        }
3534
        return $return;
3535
    }
3536
3537
    /**
3538
     * Count the number of users who answer positively on both options
3539
     *
3540
     * @param	array	All answers of the x axis
3541
     * @param	array	All answers of the y axis
3542
     * @param	integer x axis value (= the option_id of the first question)
3543
     * @param	integer y axis value (= the option_id of the second question)
3544
     * @return	integer Number of users who have answered positively to both options
3545
     *
3546
     * @author Patrick Cool <[email protected]>, Ghent University
3547
     * @version February 2007
3548
     */
3549
    public static function comparative_check($answers_x, $answers_y, $option_x, $option_y, $value_x = 0, $value_y = 0)
3550
    {
3551
        if ($value_x == 0) {
3552
            $check_x = $option_x;
3553
        } else {
3554
            $check_x = $option_x.'*'.$value_x;
3555
        }
3556
        if ($value_y == 0) {
3557
            $check_y = $option_y;
3558
        } else {
3559
            $check_y = $option_y.'*'.$value_y;
3560
        }
3561
3562
        $counter = 0;
3563
        if (is_array($answers_x)) {
3564
            foreach ($answers_x as $user => & $answers) {
3565
                // Check if the user has given $option_x as answer
3566
                if (in_array($check_x, $answers)) {
3567
                    // Check if the user has given $option_y as an answer
3568
                    if (!is_null($answers_y[$user]) && in_array($check_y, $answers_y[$user])) {
3569
                        $counter++;
3570
                    }
3571
                }
3572
            }
3573
        }
3574
3575
        return $counter;
3576
    }
3577
3578
    /**
3579
     * Get all the information about the invitations of a certain survey
3580
     *
3581
     * @return	array	Lines of invitation [user, code, date, empty element]
3582
     *
3583
     * @author Patrick Cool <[email protected]>, Ghent University
3584
     * @version January 2007
3585
     *
3586
     * @todo use survey_id parameter instead of $_GET
3587
     */
3588
    public static function get_survey_invitations_data()
3589
    {
3590
        $course_id = api_get_course_int_id();
3591
        // Database table definition
3592
        $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
3593
        $table_user = Database :: get_main_table(TABLE_MAIN_USER);
3594
3595
        $sql = "SELECT
3596
					survey_invitation.user as col1,
3597
					survey_invitation.invitation_code as col2,
3598
					survey_invitation.invitation_date as col3,
3599
					'' as col4
3600
					FROM $table_survey_invitation survey_invitation
3601
                LEFT JOIN $table_user user
3602
                ON survey_invitation.user = user.user_id
3603
                WHERE
3604
                    survey_invitation.c_id = $course_id AND
3605
                    survey_invitation.survey_id = '".intval($_GET['survey_id'])."' AND
3606
                    session_id='".api_get_session_id()."'  ";
3607
        $res = Database::query($sql);
3608
        while ($row = Database::fetch_array($res)) {
3609
            $survey_invitation_data[] = $row;
3610
        }
3611
3612
        return $survey_invitation_data;
3613
    }
3614
3615
    /**
3616
     * Get the total number of survey invitations for a given survey (through $_GET['survey_id'])
3617
     *
3618
     * @return	integer	Total number of survey invitations
3619
     *
3620
     * @todo use survey_id parameter instead of $_GET
3621
     *
3622
     * @author Patrick Cool <[email protected]>, Ghent University
3623
     * @version January 2007
3624
     */
3625 View Code Duplication
    public static function get_number_of_survey_invitations()
3626
    {
3627
        $course_id = api_get_course_int_id();
3628
3629
        // Database table definition
3630
        $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
3631
3632
        $sql = "SELECT count(user) AS total
3633
		        FROM $table_survey_invitation
3634
		        WHERE
3635
                    c_id = $course_id AND
3636
                    survey_id='".intval($_GET['survey_id'])."' AND
3637
                    session_id='".api_get_session_id()."' ";
3638
        $res = Database::query($sql);
3639
        $row = Database::fetch_array($res,'ASSOC');
3640
3641
        return $row['total'];
3642
    }
3643
3644
    /**
3645
     * Save the invitation mail
3646
     *
3647
     * @param string 	Text of the e-mail
3648
     * @param integer	Whether the mail contents are for invite mail (0, default) or reminder mail (1)
3649
     *
3650
     * @author Patrick Cool <[email protected]>, Ghent University
3651
     * @version January 2007
3652
     */
3653
    static function save_invite_mail($mailtext, $mail_subject, $reminder = 0)
3654
    {
3655
        $course_id = api_get_course_int_id();
3656
        // Database table definition
3657
        $table_survey = Database :: get_course_table(TABLE_SURVEY);
3658
3659
        // Reminder or not
3660
        if ($reminder == 0) {
3661
            $mail_field = 'invite_mail';
3662
        } else {
3663
            $mail_field = 'reminder_mail';
3664
        }
3665
3666
        $sql = "UPDATE $table_survey
3667
		        SET
3668
		        mail_subject='".Database::escape_string($mail_subject)."',
3669
		        $mail_field = '".Database::escape_string($mailtext)."'
3670
		        WHERE c_id = $course_id AND survey_id = '".intval($_GET['survey_id'])."'";
3671
        Database::query($sql);
3672
    }
3673
3674
    /**
3675
     * This function saves all the invitations of course users and additional users in the database
3676
     * and sends the invitations by email
3677
     *
3678
     * @param	array	Users array can be both a list of course uids AND a list of additional emailaddresses
3679
     * @param 	string	Title of the invitation, used as the title of the mail
3680
     * @param 	string	Text of the invitation, used as the text of the mail.
3681
     * 				 The text has to contain a **link** string or this will automatically be added to the end
3682
     *
3683
     * @author Patrick Cool <[email protected]>, Ghent University
3684
     * @author Julio Montoya - Adding auto-generated link support
3685
     * @version January 2007
3686
     *
3687
     */
3688
    public static function saveInvitations(
3689
        $users_array,
3690
        $invitation_title,
3691
        $invitation_text,
3692
        $reminder = 0,
3693
        $sendmail = 0,
3694
        $remindUnAnswered = 0
3695
    ) {
3696
        if (!is_array($users_array)) {
3697
            // Should not happen
3698
3699
            return 0;
3700
        }
3701
3702
        // Getting the survey information
3703
        $survey_data = SurveyManager::get_survey($_GET['survey_id']);
3704
        $survey_invitations = SurveyUtil::get_invitations($survey_data['survey_code']);
3705
        $already_invited = SurveyUtil::get_invited_users($survey_data['code']);
3706
3707
        // Remind unanswered is a special version of remind all reminder
3708
        $exclude_users = array();
3709
        if ($remindUnAnswered == 1) { // Remind only unanswered users
3710
            $reminder = 1;
3711
            $exclude_users = SurveyManager::get_people_who_filled_survey($_GET['survey_id']);
3712
        }
3713
3714
        $counter = 0;  // Nr of invitations "sent" (if sendmail option)
3715
        $course_id = api_get_course_int_id();
3716
        $session_id = api_get_session_id();
3717
3718
        $result = CourseManager::separateUsersGroups($users_array);
3719
3720
        $groupList = $result['groups'];
3721
        $users_array = $result['users'];
3722
3723
        foreach ($groupList as $groupId) {
3724
            $userGroupList = GroupManager::getStudents($groupId);
3725
            $userGroupIdList = array_column($userGroupList, 'user_id');
3726
            $users_array = array_merge($users_array, $userGroupIdList);
3727
3728
            $params = array(
3729
                'c_id' => $course_id,
3730
                'session_id' => $session_id,
3731
                'group_id' => $groupId,
3732
                'survey_code' => $survey_data['code']
3733
            );
3734
3735
            $invitationExists = self::invitationExists(
3736
                $course_id,
3737
                $session_id,
3738
                $groupId,
3739
                $survey_data['code']
3740
            );
3741
            if (empty($invitationExists)) {
3742
                self::save_invitation($params);
3743
            }
3744
        }
3745
3746
        $users_array = array_unique($users_array);
3747
3748
        foreach ($users_array as $key => $value) {
3749
            if (!isset($value) || $value == '') {
3750
                continue;
3751
            }
3752
3753
            // Skip user if reminding only unanswered people
3754
            if (in_array($value, $exclude_users)) {
3755
                continue;
3756
            }
3757
3758
            // Get the unique invitation code if we already have it
3759
            if ($reminder == 1 && array_key_exists($value, $survey_invitations)) {
3760
                $invitation_code = $survey_invitations[$value]['invitation_code'];
3761
            } else {
3762
                $invitation_code = md5($value.microtime());
3763
            }
3764
            $new_user = false; // User not already invited
3765
            // Store the invitation if user_id not in $already_invited['course_users'] OR email is not in $already_invited['additional_users']
3766
            $addit_users_array = isset($already_invited['additional_users']) && !empty($already_invited['additional_users']) ? explode(';', $already_invited['additional_users']) : array();
3767
3768
            $my_alredy_invited = $already_invited['course_users'] == null ? array() : $already_invited['course_users'];
3769
            if ((is_numeric($value) && !in_array($value, $my_alredy_invited)) ||
3770
                (!is_numeric($value) && !in_array($value, $addit_users_array))
3771
            ) {
3772
                $new_user = true;
3773
                if (!array_key_exists($value, $survey_invitations)) {
3774
                    $params = array(
3775
                        'c_id' => $course_id,
3776
                        'session_id' => $session_id,
3777
                        'user' => $value,
3778
                        'survey_code' => $survey_data['code'],
3779
                        'invitation_code' => $invitation_code,
3780
                        'invitation_date' => api_get_utc_datetime()
3781
                    );
3782
                    self::save_invitation($params);
3783
                }
3784
            }
3785
3786
            // Send the email if checkboxed
3787
            if (($new_user || $reminder == 1) && $sendmail != 0) {
3788
                // Make a change for absolute url
3789
                if (isset($invitation_text)) {
3790
                    $invitation_text = api_html_entity_decode($invitation_text, ENT_QUOTES);
3791
                    $invitation_text = str_replace('src="../../', 'src="'.api_get_path(WEB_PATH), $invitation_text);
3792
                    $invitation_text = trim(stripslashes($invitation_text));
3793
                }
3794
                SurveyUtil::send_invitation_mail($value, $invitation_code, $invitation_title, $invitation_text);
3795
                $counter++;
3796
            }
3797
        }
3798
3799
        return $counter; // Number of invitations sent
3800
    }
3801
3802
    /**
3803
     * @param $params
3804
     * @return bool|int
3805
     */
3806
    public static function save_invitation($params)
3807
    {
3808
        // Database table to store the invitations data
3809
        $table = Database::get_course_table(TABLE_SURVEY_INVITATION);
3810
        if (!empty($params['c_id']) &&
3811
            (!empty($params['user']) || !empty($params['group_id'])) &&
3812
            !empty($params['survey_code'])
3813
        ) {
3814
            $insertId = Database::insert($table, $params);
3815
            if ($insertId) {
3816
3817
                $sql = "UPDATE $table SET survey_invitation_id = $insertId
3818
                        WHERE iid = $insertId";
3819
                Database::query($sql);
3820
            }
3821
            return $insertId;
3822
        }
3823
        return false;
3824
    }
3825
3826
    /**
3827
     * @param int $courseId
3828
     * @param int $sessionId
3829
     * @param int $groupId
3830
     * @param string $surveyCode
3831
     * @return int
3832
     */
3833
    public static function invitationExists($courseId, $sessionId, $groupId, $surveyCode)
3834
    {
3835
        $table = Database::get_course_table(TABLE_SURVEY_INVITATION);
3836
        $courseId = intval($courseId);
3837
        $sessionId = intval($sessionId);
3838
        $groupId = intval($groupId);
3839
        $surveyCode = Database::escape_string($surveyCode);
3840
3841
        $sql = "SELECT survey_invitation_id FROM $table
3842
                WHERE
3843
                    c_id = $courseId AND
3844
                    session_id = $sessionId AND
3845
                    group_id = $groupId AND
3846
                    survey_code = '$surveyCode'
3847
                ";
3848
        $result = Database::query($sql);
3849
3850
        return Database::num_rows($result);
3851
    }
3852
3853
    /**
3854
     * Send the invitation by mail.
3855
     *
3856
     * @param int invitedUser - the userId (course user) or emailaddress of additional user
3857
     * $param string $invitation_code - the unique invitation code for the URL
3858
     * @return	void
3859
     */
3860
    public static function send_invitation_mail($invitedUser, $invitation_code, $invitation_title, $invitation_text)
3861
    {
3862
        $_user = api_get_user_info();
3863
        $_course = api_get_course_info();
3864
3865
        // Replacing the **link** part with a valid link for the user
3866
        $survey_link = api_get_path(WEB_CODE_PATH).'survey/fillsurvey.php?course='.$_course['code'].'&invitationcode='.$invitation_code;
3867
        $text_link = '<a href="'.$survey_link.'">'.get_lang('ClickHereToAnswerTheSurvey')."</a><br />\r\n<br />\r\n".get_lang('OrCopyPasteTheFollowingUrl')." <br />\r\n ".$survey_link;
3868
3869
        $replace_count = 0;
3870
        $full_invitation_text = api_str_ireplace('**link**', $text_link ,$invitation_text, $replace_count);
3871
        if ($replace_count < 1) {
3872
            $full_invitation_text = $full_invitation_text."<br />\r\n<br />\r\n".$text_link;
3873
        }
3874
3875
        // Sending the mail
3876
        $sender_name  = api_get_person_name($_user['firstName'], $_user['lastName'], null, PERSON_NAME_EMAIL_ADDRESS);
3877
        $sender_email = $_user['mail'];
3878
        $sender_user_id = api_get_user_id();
3879
3880
        $replyto = array();
3881
        if (api_get_setting('survey_email_sender_noreply') == 'noreply') {
3882
            $noreply = api_get_setting('noreply_email_address');
3883
            if (!empty($noreply)) {
3884
                $replyto['Reply-to'] = $noreply;
3885
                $sender_name = $noreply;
3886
                $sender_email = $noreply;
3887
                $sender_user_id = null;
3888
            }
3889
        }
3890
3891
        // Optionally: finding the e-mail of the course user
3892
        if (is_numeric($invitedUser)) {
3893
            $table_user = Database :: get_main_table(TABLE_MAIN_USER);
3894
            $sql = "SELECT firstname, lastname, email FROM $table_user
3895
                    WHERE user_id='".Database::escape_string($invitedUser)."'";
3896
            $result = Database::query($sql);
3897
            $row = Database::fetch_array($result);
3898
            $recipient_email = $row['email'];
3899
            $recipient_name = api_get_person_name($row['firstname'], $row['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);
3900
3901
            MessageManager::send_message(
3902
                $invitedUser,
3903
                $invitation_title,
3904
                $full_invitation_text,
3905
                [],
3906
                [],
3907
                null,
3908
                null,
3909
                null,
3910
                null,
3911
                $sender_user_id
3912
            );
3913
3914
        } else {
3915
            /** @todo check if the address is a valid email	 */
3916
            $recipient_email = $invitedUser;
3917
            @api_mail_html(
3918
                $recipient_name,
0 ignored issues
show
Bug introduced by
The variable $recipient_name seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
3919
                $recipient_email,
3920
                $invitation_title,
3921
                $full_invitation_text,
3922
                $sender_name,
3923
                $sender_email,
3924
                $replyto
3925
            );
3926
        }
3927
    }
3928
3929
    /**
3930
     * This function recalculates the number of users who have been invited and updates the survey table with this value.
3931
     *
3932
     * @param	string	Survey code
3933
     * @return	void
3934
     * @author Patrick Cool <[email protected]>, Ghent University
3935
     * @version January 2007
3936
     */
3937
    static function update_count_invited($survey_code)
3938
    {
3939
        $course_id = api_get_course_int_id();
3940
3941
        // Database table definition
3942
        $table_survey_invitation 	= Database :: get_course_table(TABLE_SURVEY_INVITATION);
3943
        $table_survey 				= Database :: get_course_table(TABLE_SURVEY);
3944
3945
        // Counting the number of people that are invited
3946
        $sql = "SELECT count(user) as total
3947
                FROM $table_survey_invitation
3948
		        WHERE
3949
		            c_id = $course_id AND
3950
		            survey_code = '".Database::escape_string($survey_code)."' AND
3951
		            user <> ''
3952
                ";
3953
        $result = Database::query($sql);
3954
        $row = Database::fetch_array($result);
3955
        $total_invited = $row['total'];
3956
3957
        // Updating the field in the survey table
3958
        $sql = "UPDATE $table_survey
3959
		        SET invited = '".Database::escape_string($total_invited)."'
3960
		        WHERE
3961
		            c_id = $course_id AND
3962
		            code = '".Database::escape_string($survey_code)."'
3963
                ";
3964
        Database::query($sql);
3965
    }
3966
3967
    /**
3968
     * This function gets all the invited users for a given survey code.
3969
     *
3970
     * @param	string	Survey code
3971
     * @param	string	optional - course database
3972
     * @return 	array	Array containing the course users and additional users (non course users)
3973
     *
3974
     * @todo consider making $defaults['additional_users'] also an array
3975
     *
3976
     * @author Patrick Cool <[email protected]>, Ghent University
3977
     * @author Julio Montoya, adding c_id fixes - Dec 2012
3978
     * @version January 2007
3979
     */
3980
    public static function get_invited_users($survey_code, $course_code = '', $session_id = 0)
3981
    {
3982
        if (!empty($course_code)) {
3983
            $course_info = api_get_course_info($course_code);
3984
            $course_id = $course_info['real_id'];
3985
        } else {
3986
            $course_id = api_get_course_int_id();
3987
        }
3988
3989
        if (empty($session_id)) {
3990
            $session_id = api_get_session_id();
3991
        }
3992
3993
        $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
3994
        $table_user = Database :: get_main_table(TABLE_MAIN_USER);
3995
3996
        // Selecting all the invitations of this survey AND the additional emailaddresses (the left join)
3997
        $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname' : ' ORDER BY lastname, firstname';
3998
        $sql = "SELECT user, group_id
3999
				FROM $table_survey_invitation as table_invitation
4000
				WHERE
4001
				    table_invitation.c_id = $course_id AND
4002
                    survey_code='".Database::escape_string($survey_code)."' AND
4003
                    session_id = $session_id
4004
                ";
4005
4006
        $defaults = array();
4007
        $defaults['course_users'] = array();
4008
        $defaults['additional_users'] = array(); // Textarea
4009
        $defaults['users'] = array(); // user and groups
4010
4011
        $result = Database::query($sql);
4012
        while ($row = Database::fetch_array($result)) {
4013
            if (is_numeric($row['user'])) {
4014
                $defaults['course_users'][] = $row['user'];
4015
                $defaults['users'][] = 'USER:'.$row['user'];
4016
            } else {
4017
                if (!empty($row['user'])) {
4018
                    $defaults['additional_users'][] = $row['user'];
4019
                }
4020
            }
4021
4022 View Code Duplication
            if (isset($row['group_id']) && !empty($row['group_id'])) {
4023
                $defaults['users'][] = 'GROUP:'.$row['group_id'];
4024
            }
4025
        }
4026
4027 View Code Duplication
        if (!empty($defaults['course_users'])) {
4028
            $user_ids = implode("','", $defaults['course_users']);
4029
            $sql = "SELECT user_id FROM $table_user WHERE user_id IN ('$user_ids') $order_clause";
4030
            $result = Database::query($sql);
4031
            $fixed_users = array();
4032
            while ($row = Database::fetch_array($result)) {
4033
                $fixed_users[] = $row['user_id'];
4034
            }
4035
            $defaults['course_users'] = $fixed_users;
4036
        }
4037
4038
        if (!empty($defaults['additional_users'])) {
4039
            $defaults['additional_users'] = implode(';', $defaults['additional_users']);
4040
        }
4041
        return $defaults;
4042
    }
4043
4044
    /**
4045
     * Get all the invitations
4046
     *
4047
     * @param	string	Survey code
4048
     * @return	array	Database rows matching the survey code
4049
     *
4050
     * @author Patrick Cool <[email protected]>, Ghent University
4051
     * @version September 2007
4052
     */
4053
    static function get_invitations($survey_code)
4054
    {
4055
        $course_id = api_get_course_int_id();
4056
        // Database table definition
4057
        $table_survey_invitation 	= Database :: get_course_table(TABLE_SURVEY_INVITATION);
4058
4059
        $sql = "SELECT * FROM $table_survey_invitation
4060
		        WHERE
4061
		            c_id = $course_id AND
4062
		            survey_code = '".Database::escape_string($survey_code)."'";
4063
        $result = Database::query($sql);
4064
        $return = array();
4065
        while ($row = Database::fetch_array($result)) {
4066
            $return[$row['user']] = $row;
4067
        }
4068
        return $return;
4069
    }
4070
4071
    /**
4072
     * This function displays the form for searching a survey
4073
     *
4074
     * @return	void	(direct output)
4075
     *
4076
     * @author Patrick Cool <[email protected]>, Ghent University
4077
     * @version January 2007
4078
     *
4079
     * @todo use quickforms
4080
     * @todo consider moving this to surveymanager.inc.lib.php
4081
     */
4082
    static function display_survey_search_form()
4083
    {
4084
        echo '<form class="form-horizontal" method="get" action="'.api_get_path(WEB_CODE_PATH).'survey/survey_list.php?search=advanced">';
4085
        echo '<legend>'.get_lang('SearchASurvey').'</legend>';
4086
        echo '	<div class="control-group">
4087
					<label class="control-label">
4088
						'.get_lang('Title').'
4089
					</label>
4090
					<div class="controls">
4091
						<input type="text" id="search_title" name="keyword_title"/>
4092
					</div>
4093
				</div>';
4094
        echo '	<div class="control-group">
4095
					<label class="control-label">
4096
						'.get_lang('Code').'
4097
					</label>
4098
					<div class="controls">
4099
						<input type="text" name="keyword_code"/>
4100
					</div>
4101
				</div>';
4102
        echo '	<div class="control-group">
4103
					<label class="control-label">
4104
						'.get_lang('Language').'
4105
					</label>
4106
					<div class="controls">';
4107
        echo '			<select name="keyword_language"><option value="%">'.get_lang('All').'</option>';
4108
        $languages = api_get_languages();
4109
        foreach ($languages['name'] as $index => & $name) {
4110
            echo '<option value="'.$languages['folder'][$index].'">'.$name.'</option>';
4111
        }
4112
        echo '			</select>';
4113
        echo '		</div>
4114
				</div>';
4115
        echo '<input type="hidden" name="cidReq" value="'.api_get_course_id().'"/>';
4116
        echo '	<div class="control-group">
4117
					<div class="controls">
4118
						<button class="search" type="submit" name="do_search">'.get_lang('Search').'</button>
4119
					</div>
4120
				</div>';
4121
        echo '</form>';
4122
        echo '<div style="clear: both;margin-bottom: 10px;"></div>';
4123
    }
4124
4125
    /**
4126
     * Show table only visible by DRH users
4127
     */
4128
    public static function displaySurveyListForDrh()
4129
    {
4130
        $parameters = array();
4131
        $parameters['cidReq'] = api_get_course_id();
4132
4133
        // Create a sortable table with survey-data
4134
        $table = new SortableTable('surveys', 'get_number_of_surveys', 'get_survey_data_drh', 2);
4135
        $table->set_additional_parameters($parameters);
4136
        $table->set_header(0, '', false);
4137
        $table->set_header(1, get_lang('SurveyName'));
4138
        $table->set_header(2, get_lang('SurveyCode'));
4139
        $table->set_header(3, get_lang('NumberOfQuestions'));
4140
        $table->set_header(4, get_lang('Author'));
4141
        $table->set_header(5, get_lang('AvailableFrom'));
4142
        $table->set_header(6, get_lang('AvailableUntil'));
4143
        $table->set_header(7, get_lang('Invite'));
4144
        $table->set_header(8, get_lang('Anonymous'));
4145
        $table->set_header(9, get_lang('Modify'), false, 'width="150"');
4146
        $table->set_column_filter(8, 'anonymous_filter');
4147
        $table->set_column_filter(9, 'modify_filter_drh');
4148
        $table->display();
4149
    }
4150
4151
    /**
4152
     * This function displays the sortable table with all the surveys
4153
     *
4154
     * @return	void	(direct output)
4155
     *
4156
     * @author Patrick Cool <[email protected]>, Ghent University
4157
     * @version January 2007
4158
     */
4159
    static function display_survey_list()
4160
    {
4161
        $parameters = array();
4162
        $parameters['cidReq'] = api_get_course_id();
4163
        if (isset($_GET['do_search']) && $_GET['do_search']) {
4164
            $message = get_lang('DisplaySearchResults').'<br />';
4165
            $message .= '<a href="'.api_get_self().'?'.api_get_cidreq().'">'.get_lang('DisplayAll').'</a>';
4166
            Display::display_normal_message($message, false);
4167
        }
4168
4169
        // Create a sortable table with survey-data
4170
        $table = new SortableTable('surveys', 'get_number_of_surveys', 'get_survey_data', 2);
4171
        $table->set_additional_parameters($parameters);
4172
        $table->set_header(0, '', false);
4173
        $table->set_header(1, get_lang('SurveyName'));
4174
        $table->set_header(2, get_lang('SurveyCode'));
4175
        $table->set_header(3, get_lang('NumberOfQuestions'));
4176
        $table->set_header(4, get_lang('Author'));
4177
        //$table->set_header(5, get_lang('Language'));
4178
        //$table->set_header(6, get_lang('Shared'));
4179
        $table->set_header(5, get_lang('AvailableFrom'));
4180
        $table->set_header(6, get_lang('AvailableUntil'));
4181
        $table->set_header(7, get_lang('Invite'));
4182
        $table->set_header(8, get_lang('Anonymous'));
4183
        $table->set_header(9, get_lang('Modify'), false, 'width="150"');
4184
        $table->set_column_filter(8, 'anonymous_filter');
4185
        $table->set_column_filter(9, 'modify_filter');
4186
        $table->set_form_actions(array('delete' => get_lang('DeleteSurvey')));
4187
        $table->display();
4188
    }
4189
4190
    function display_survey_list_for_coach()
4191
    {
4192
        $parameters = array();
4193
        $parameters['cidReq']=api_get_course_id();
4194
        if (isset($_GET['do_search'])) {
4195
            $message = get_lang('DisplaySearchResults').'<br />';
4196
            $message .= '<a href="'.api_get_self().'?'.api_get_cidreq().'">'.get_lang('DisplayAll').'</a>';
4197
            Display::display_normal_message($message, false);
4198
        }
4199
4200
        // Create a sortable table with survey-data
4201
        $table = new SortableTable('surveys_coach', 'get_number_of_surveys_for_coach', 'get_survey_data_for_coach', 2);
4202
        $table->set_additional_parameters($parameters);
4203
        $table->set_header(0, '', false);
4204
        $table->set_header(1, get_lang('SurveyName'));
4205
        $table->set_header(2, get_lang('SurveyCode'));
4206
        $table->set_header(3, get_lang('NumberOfQuestions'));
4207
        $table->set_header(4, get_lang('Author'));
4208
        //$table->set_header(5, get_lang('Language'));
4209
        //$table->set_header(6, get_lang('Shared'));
4210
        $table->set_header(5, get_lang('AvailableFrom'));
4211
        $table->set_header(6, get_lang('AvailableUntil'));
4212
        $table->set_header(7, get_lang('Invite'));
4213
        $table->set_header(8, get_lang('Anonymous'));
4214
        $table->set_header(9, get_lang('Modify'), false, 'width="130"');
4215
        $table->set_column_filter(8, 'anonymous_filter');
4216
        $table->set_column_filter(9, 'modify_filter_for_coach');
4217
        $table->display();
4218
    }
4219
4220
    /**
4221
     * This function changes the modify column of the sortable table
4222
     *
4223
     * @param integer $survey_id the id of the survey
4224
     * @param bool $drh
4225
     * @return string html code that are the actions that can be performed on any survey
4226
     *
4227
     * @author Patrick Cool <[email protected]>, Ghent University
4228
     * @version January 2007
4229
     */
4230
    static function modify_filter($survey_id, $drh = false)
4231
    {
4232
        $survey_id = Security::remove_XSS($survey_id);
4233
        $return = '';
4234
4235
        if ($drh) {
4236
            return '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.
4237
            Display::return_icon('stats.png', get_lang('Reporting'),'',ICON_SIZE_SMALL).'</a>';
4238
        }
4239
4240
        // Coach can see that only if the survey is in his session
4241
        if (api_is_allowed_to_edit() ||
4242
            api_is_element_in_the_session(TOOL_SURVEY, $survey_id)
4243
        ) {
4244
            $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/create_new_survey.php?'.api_get_cidreq().'&action=edit&survey_id='.$survey_id.'">'.Display::return_icon('edit.png', get_lang('Edit'),'',ICON_SIZE_SMALL).'</a>';
4245
            if (SurveyManager::survey_generation_hash_available()) {
4246
                $return .=  Display::url(
4247
                    Display::return_icon('new_link.png', get_lang('GenerateSurveyAccessLink'),'',ICON_SIZE_SMALL),
4248
                    api_get_path(WEB_CODE_PATH).'survey/generate_link.php?survey_id='.$survey_id.'&'.api_get_cidreq()
4249
                );
4250
            }
4251
            $return .= Display::url(
4252
                Display::return_icon('copy.png', get_lang('DuplicateSurvey'), '', ICON_SIZE_SMALL),
4253
                'survey_list.php?action=copy_survey&survey_id='.$survey_id.'&'.api_get_cidreq()
4254
            );
4255
4256
            $return .= ' <a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_list.php?'.api_get_cidreq().'&action=empty&survey_id='.$survey_id.'" onclick="javascript: if(!confirm(\''.addslashes(api_htmlentities(get_lang("EmptySurvey").'?')).'\')) return false;">'.
4257
                Display::return_icon('clean.png', get_lang('EmptySurvey'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
4258
        }
4259
        $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/preview.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.
4260
            Display::return_icon('preview_view.png', get_lang('Preview'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
4261
        $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_invite.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.
4262
            Display::return_icon('mail_send.png', get_lang('Publish'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
4263
        $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.
4264
            Display::return_icon('stats.png', get_lang('Reporting'),'',ICON_SIZE_SMALL).'</a>';
4265
4266 View Code Duplication
        if (api_is_allowed_to_edit() ||
4267
            api_is_element_in_the_session(TOOL_SURVEY, $survey_id)
4268
        ) {
4269
            $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_list.php?'.api_get_cidreq().'&action=delete&survey_id='.$survey_id.'" onclick="javascript: if(!confirm(\''.addslashes(api_htmlentities(get_lang("DeleteSurvey").'?', ENT_QUOTES)).'\')) return false;">'.
4270
                Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
4271
        }
4272
4273
        return $return;
4274
    }
4275
4276
    static function modify_filter_for_coach($survey_id)
4277
    {
4278
        $survey_id = Security::remove_XSS($survey_id);
4279
        //$return = '<a href="create_new_survey.php?'.api_get_cidreq().'&action=edit&survey_id='.$survey_id.'">'.Display::return_icon('edit.gif', get_lang('Edit')).'</a>';
4280
        //$return .= '<a href="survey_list.php?'.api_get_cidreq().'&action=delete&survey_id='.$survey_id.'" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang("DeleteSurvey").'?', ENT_QUOTES)).'\')) return false;">'.Display::return_icon('delete.gif', get_lang('Delete')).'</a>';
4281
        //$return .= '<a href="create_survey_in_another_language.php?id_survey='.$survey_id.'">'.Display::return_icon('copy.gif', get_lang('Copy')).'</a>';
4282
        //$return .= '<a href="survey.php?survey_id='.$survey_id.'">'.Display::return_icon('add.gif', get_lang('Add')).'</a>';
4283
        $return = '<a href="'.api_get_path(WEB_CODE_PATH).'survey/preview.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.Display::return_icon('preview_view.png', get_lang('Preview'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
4284
        $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_invite.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.Display::return_icon('mail_send.png', get_lang('Publish'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
4285
        $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_list.php?'.api_get_cidreq().'&action=empty&survey_id='.$survey_id.'" onclick="javascript: if(!confirm(\''.addslashes(api_htmlentities(get_lang("EmptySurvey").'?', ENT_QUOTES)).'\')) return false;">'.Display::return_icon('clean.png', get_lang('EmptySurvey'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
4286
        //$return .= '<a href="reporting.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.Display::return_icon('statistics.gif', get_lang('Reporting')).'</a>';
4287
        return $return;
4288
    }
4289
4290
    /**
4291
     * Returns "yes" when given parameter is one, "no" for any other value
4292
     * @param	integer	Whether anonymous or not
4293
     * @return	string	"Yes" or "No" in the current language
4294
     */
4295
    static function anonymous_filter($anonymous)
4296
    {
4297
        if ($anonymous == 1) {
4298
            return get_lang('Yes');
4299
        } else {
4300
            return get_lang('No');
4301
        }
4302
    }
4303
4304
    /**
4305
     * This function handles the search restriction for the SQL statements
4306
     *
4307
     * @return	string	Part of a SQL statement or false on error
4308
     *
4309
     * @author Patrick Cool <[email protected]>, Ghent University
4310
     * @version January 2007
4311
     */
4312
    static function survey_search_restriction()
4313
    {
4314
        if (isset($_GET['do_search'])) {
4315
            if ($_GET['keyword_title'] != '') {
4316
                $search_term[] = 'title like "%" \''.Database::escape_string($_GET['keyword_title']).'\' "%"';
4317
            }
4318
            if ($_GET['keyword_code'] != '') {
4319
                $search_term[] = 'code =\''.Database::escape_string($_GET['keyword_code']).'\'';
4320
            }
4321
            if ($_GET['keyword_language'] != '%') {
4322
                $search_term[] = 'lang =\''.Database::escape_string($_GET['keyword_language']).'\'';
4323
            }
4324
            $my_search_term = ($search_term == null) ? array() : $search_term;
4325
            $search_restriction = implode(' AND ', $my_search_term);
4326
            return $search_restriction;
4327
        } else {
4328
            return false;
4329
        }
4330
    }
4331
4332
    /**
4333
     * This function calculates the total number of surveys
4334
     *
4335
     * @return	integer	Total number of surveys
4336
     *
4337
     * @author Patrick Cool <[email protected]>, Ghent University
4338
     * @version January 2007
4339
     */
4340
    static function get_number_of_surveys()
4341
    {
4342
        $table_survey = Database :: get_course_table(TABLE_SURVEY);
4343
        $course_id = api_get_course_int_id();
4344
4345
        $search_restriction = SurveyUtil::survey_search_restriction();
4346
        if ($search_restriction) {
4347
            $search_restriction = 'WHERE c_id = '.$course_id.' AND '.$search_restriction;
4348
        } else {
4349
            $search_restriction = "WHERE c_id = $course_id";
4350
        }
4351
        $sql = "SELECT count(survey_id) AS total_number_of_items
4352
		        FROM ".$table_survey.' '.$search_restriction;
4353
        $res = Database::query($sql);
4354
        $obj = Database::fetch_object($res);
4355
        return $obj->total_number_of_items;
4356
    }
4357
4358
    static function get_number_of_surveys_for_coach()
4359
    {
4360
        $survey_tree = new SurveyTree();
4361
        return count($survey_tree->get_last_children_from_branch($survey_tree->surveylist));
4362
    }
4363
4364
    /**
4365
     * This function gets all the survey data that is to be displayed in the sortable table
4366
     *
4367
     * @param int $from
4368
     * @param int $number_of_items
4369
     * @param int $column
4370
     * @param string $direction
4371
     * @param bool $isDrh
4372
     * @return unknown
4373
     *
4374
     * @author Patrick Cool <[email protected]>, Ghent University
4375
     * @author Julio Montoya <[email protected]>, Beeznest - Adding intvals
4376
     * @version January 2007
4377
     */
4378
    static function get_survey_data($from, $number_of_items, $column, $direction, $isDrh = false)
4379
    {
4380
        $table_survey = Database :: get_course_table(TABLE_SURVEY);
4381
        $table_user = Database :: get_main_table(TABLE_MAIN_USER);
4382
        $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
4383
        $_user = api_get_user_info();
4384
4385
        // Searching
4386
        $search_restriction = SurveyUtil::survey_search_restriction();
4387
        if ($search_restriction) {
4388
            $search_restriction = ' AND '.$search_restriction;
4389
        }
4390
        $from = intval($from);
4391
        $number_of_items = intval($number_of_items);
4392
        $column = intval($column);
4393
        if (!in_array(strtolower($direction), array('asc', 'desc'))) {
4394
            $direction = 'asc';
4395
        }
4396
4397
        // Condition for the session
4398
        $session_id = api_get_session_id();
4399
        $condition_session = api_get_session_condition($session_id);
4400
        $course_id = api_get_course_int_id();
4401
4402
        $sql = "SELECT
4403
					survey.survey_id AS col0,
4404
					survey.title AS col1,
4405
					survey.code AS col2,
4406
					count(survey_question.question_id) AS col3,
4407
					".(api_is_western_name_order() ? "CONCAT(user.firstname, ' ', user.lastname)" : "CONCAT(user.lastname, ' ', user.firstname)")."	AS col4,
4408
					survey.avail_from AS col5,
4409
					survey.avail_till AS col6,
4410
					survey.invited AS col7,
4411
					survey.anonymous AS col8,
4412
					survey.survey_id AS col9,
4413
					survey.session_id AS session_id,
4414
					survey.answered,
4415
					survey.invited
4416
				 FROM $table_survey survey
4417
                    LEFT JOIN $table_survey_question survey_question
4418
                    ON (survey.survey_id = survey_question.survey_id AND survey_question.c_id = $course_id)
4419
                    LEFT JOIN $table_user user
4420
                    ON (survey.author = user.user_id)
4421
				 WHERE survey.c_id = $course_id
4422
				 $search_restriction
4423
				 $condition_session ";
4424
        $sql .= " GROUP BY survey.survey_id";
4425
        $sql .= " ORDER BY col$column $direction ";
4426
        $sql .= " LIMIT $from,$number_of_items";
4427
4428
        $res = Database::query($sql);
4429
        $surveys = array();
4430
        $array = array();
4431
        while ($survey = Database::fetch_array($res)) {
4432
            $array[0] = $survey[0];
4433
            $array[1] = Display::url(
4434
                $survey[1],
4435
                api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.$survey[0].'&'.api_get_cidreq()
4436
            );
4437
4438
            // Validation when belonging to a session
4439
            $session_img = api_get_session_image($survey['session_id'], $_user['status']);
4440
            $array[2] = $survey[2] . $session_img;
4441
            $array[3] = $survey[3];
4442
            $array[4] = $survey[4];
4443
            $array[5] = $survey[5];
4444
            $array[6] = $survey[6];
4445
            $array[7] =
4446
                Display::url(
4447
                    $survey['answered'],
4448
                    api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?view=answered&survey_id='.$survey[0].'&'.api_get_cidreq()
4449
                ).' / '.
4450
                Display::url(
4451
                    $survey['invited'],
4452
                    api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?view=invited&survey_id='.$survey[0].'&'.api_get_cidreq()
4453
                );
4454
4455
            $array[8] = $survey[8];
4456
            $array[9] = $survey[9];
4457
4458
            if ($isDrh) {
4459
                $array[1] = $survey[1];
4460
                $array[7] = strip_tags($array[7]);
4461
            }
4462
4463
            $surveys[] = $array;
4464
        }
4465
        return $surveys;
4466
    }
4467
4468
    static function get_survey_data_for_coach($from, $number_of_items, $column, $direction)
4469
    {
4470
        $survey_tree = new SurveyTree();
4471
        $last_version_surveys = $survey_tree->get_last_children_from_branch($survey_tree->surveylist);
4472
        $list = array();
4473
        foreach ($last_version_surveys as & $survey) {
4474
            $list[]=$survey['id'];
4475
        }
4476
        if (count($list) > 0) {
4477
            $list_condition = " AND survey.survey_id IN (".implode(',',$list).") ";
4478
        } else {
4479
            $list_condition = '';
4480
        }
4481
4482
        $from = intval($from);
4483
        $number_of_items = intval($number_of_items);
4484
        $column = intval($column);
4485
        if (!in_array(strtolower($direction), array('asc', 'desc'))) {
4486
            $direction = 'asc';
4487
        }
4488
4489
        $table_survey 			= Database :: get_course_table(TABLE_SURVEY);
4490
        $table_survey_question 	= Database :: get_course_table(TABLE_SURVEY_QUESTION);
4491
        $table_user 			= Database :: get_main_table(TABLE_MAIN_USER);
4492
4493
        $course_id = api_get_course_int_id();
4494
4495
        //IF(is_shared<>0,'V','-')	 					AS col6,
4496
        $sql = "SELECT ".
4497
            "survey.survey_id							AS col0, ".
4498
            "survey.title	                            AS col1, ".
4499
            "survey.code									AS col2, ".
4500
            "count(survey_question.question_id)			AS col3, ".
4501
            (api_is_western_name_order() ? "CONCAT(user.firstname, ' ', user.lastname)" : "CONCAT(user.lastname, ' ', user.firstname)")."	AS col4, ".
4502
            "survey.avail_from							AS col5, ".
4503
            "survey.avail_till							AS col6, ".
4504
            "CONCAT('<a href=\"survey_invitation.php?view=answered&survey_id=',survey.survey_id,'\">',survey.answered,'</a> / <a href=\"survey_invitation.php?view=invited&survey_id=',survey.survey_id,'\">',survey.invited, '</a>')	AS col7, ".
4505
            "survey.anonymous							AS col8, ".
4506
            "survey.survey_id							AS col9  ".
4507
            "FROM $table_survey survey ".
4508
            "LEFT JOIN $table_survey_question survey_question
4509
             ON (survey.survey_id = survey_question.survey_id AND survey.c_id = survey_question.c_id) ".
4510
            ", $table_user user
4511
               WHERE survey.author = user.user_id AND survey.c_id = $course_id $list_condition ";
4512
        $sql .= " GROUP BY survey.survey_id";
4513
        $sql .= " ORDER BY col$column $direction ";
4514
        $sql .= " LIMIT $from,$number_of_items";
4515
4516
        $res = Database::query($sql);
4517
        $surveys = array();
4518
        while ($survey = Database::fetch_array($res)) {
4519
            $surveys[] = $survey;
4520
        }
4521
        return $surveys;
4522
    }
4523
4524
    /**
4525
     * Display all the active surveys for the given course user
4526
     *
4527
     * @param int $user_id
4528
     *
4529
     * @author Patrick Cool <[email protected]>, Ghent University
4530
     * @version April 2007
4531
     */
4532
    public static function getSurveyList($user_id)
4533
    {
4534
        $_course = api_get_course_info();
4535
        $course_id = $_course['real_id'];
4536
        $user_id = intval($user_id);
4537
        $sessionId = api_get_session_id();
4538
4539
        // Database table definitions
4540
        $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
4541
        $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
4542
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
4543
        $table_survey = Database:: get_course_table(TABLE_SURVEY);
4544
4545
        $sql = 'SELECT question_id
4546
                FROM '.$table_survey_question."
4547
                WHERE c_id = $course_id";
4548
        $result = Database::query($sql);
4549
4550
        $all_question_id = array();
4551
        while ($row = Database::fetch_array($result, 'ASSOC')) {
4552
            $all_question_id[] = $row;
4553
        }
4554
4555
        $count = 0;
4556
        for ($i = 0; $i < count($all_question_id); $i++) {
4557
            $sql = 'SELECT COUNT(*) as count
4558
			        FROM '.$table_survey_answer.'
4559
					WHERE
4560
					    c_id = '.$course_id.' AND
4561
					    question_id='.intval($all_question_id[$i]['question_id']).' AND
4562
					    user = '.$user_id;
4563
            $result = Database::query($sql);
4564
            while ($row = Database::fetch_array($result, 'ASSOC')) {
4565
                if ($row['count'] == 0) {
4566
                    $count++;
4567
                    break;
4568
                }
4569
            }
4570
            if ($count > 0) {
4571
                $link_add = true;
4572
                break;
4573
            }
4574
        }
4575
4576
        echo '<table id="list-survey" class="table ">';
4577
        echo '<tr>';
4578
        echo '	<th>'.get_lang('SurveyName').'</th>';
4579
        echo '	<th>'.get_lang('Anonymous').'</th>';
4580
        echo '</tr>';
4581
4582
        $sql = "SELECT *
4583
                FROM $table_survey survey,
4584
                $table_survey_invitation survey_invitation
4585
				WHERE
4586
                    survey_invitation.user = $user_id AND
4587
                    survey.code = survey_invitation.survey_code AND
4588
                    survey.avail_from <= '".date('Y-m-d H:i:s')."' AND
4589
                    survey.avail_till >= '".date('Y-m-d H:i:s')."' AND
4590
                    survey.c_id = $course_id AND
4591
                    survey.session_id = $sessionId AND
4592
                    survey_invitation.c_id = $course_id
4593
				";
4594
        $result = Database::query($sql);
4595
        $counter = 0;
4596
        while ($row = Database::fetch_array($result, 'ASSOC')) {
4597
4598
            // Get the user into survey answer table (user or anonymus)
4599
            $sql = "SELECT user FROM $table_survey_answer
4600
					WHERE c_id = $course_id AND survey_id = (
4601
					    SELECT survey_id from $table_survey
4602
					    WHERE code ='".Database::escape_string($row['code'])." AND c_id = $course_id'
4603
                    )
4604
            ";
4605
            $result_answer = Database::query($sql);
4606
            $row_answer = Database::fetch_array($result_answer,'ASSOC');
4607
            echo '<tr>';
4608
            if ($row['answered'] == 0) {
4609
                echo '<td>';
4610
                echo Display::return_icon('statistics.png', get_lang('CreateNewSurvey'),array('style'=>'inline-block'),ICON_SIZE_TINY);
4611
                echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/fillsurvey.php?course='.$_course['sysCode'].'&invitationcode='.$row['invitation_code'].'&cidReq='.$_course['sysCode'].'">'.$row['title'].'</a></td>';
4612
            } else {
4613
                //echo '<td>'.$row['title'].'</td>';
4614
                echo '<td>';
4615
                echo Display::return_icon('statistics_na.png', get_lang('CreateNewSurvey'),array('style'=>'inline-block'),ICON_SIZE_TINY);
4616
                echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action=questionreport&cidReq='.$_course['sysCode'].'&id_session='.$row['session_id'].'&gidReq='.'0'.'&origin='.''.'&survey_id='.$row['survey_id'].'">'.$row['title'].'</a></td>';
4617
            }
4618
            echo '<td class="center">';
4619
            echo ($row['anonymous'] == 1) ? get_lang('Yes') : get_lang('No');
4620
            echo '</td>';
4621
            echo '</tr>';
4622
            if ($row['anonymous'] == 1) {
4623
                $current_user_id = $_SESSION['surveyuser'];
4624
            } else {
4625
                $current_user_id = api_get_user_id();
4626
            }
4627
            $link_available = self::show_link_available(api_get_user_id(),$row['code'],$current_user_id);
4628
            //todo check this link
4629
            if ($link_add === true && $link_available === true) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
4630
                //echo '<tr><td><a href="fillsurvey.php?user_id='.api_get_user_id().'&course='.$_course['sysCode'].'&invitationcode='.$row['invitation_code'].'&cidReq='.$_course['sysCode'].'">'.get_lang('CompleteTheSurveysQuestions').'</a></td><td></td></tr>';
4631
            }
4632
        }
4633
        echo '</table>';
4634
    }
4635
4636
    /**
4637
     * Creates a multi array with the user fields that we can show. We look the visibility with the api_get_setting function
4638
     * The username is always NOT able to change it.
4639
     * @author Julio Montoya Armas <[email protected]>, Chamilo: Personality Test modification
4640
     * @return array[value_name][name]
0 ignored issues
show
Documentation introduced by
The doc-type array[value_name][name] could not be parsed: Expected "]" at position 2, but found "value_name". (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
4641
     * 		   array[value_name][visibilty]
4642
     */
4643
    static function make_field_list()
4644
    {
4645
        //	LAST NAME and FIRST NAME
4646
        $field_list_array = array();
4647
        $field_list_array['lastname']['name'] = get_lang('LastName');
4648
        $field_list_array['firstname']['name'] = get_lang('FirstName');
4649
4650
        if (api_get_setting('profile', 'name') != 'true') {
4651
            $field_list_array['firstname']['visibility'] = 0;
4652
            $field_list_array['lastname']['visibility'] = 0;
4653
        } else {
4654
            $field_list_array['firstname']['visibility'] = 1;
4655
            $field_list_array['lastname']['visibility'] = 1;
4656
        }
4657
4658
        $field_list_array['username']['name'] = get_lang('Username');
4659
        $field_list_array['username']['visibility'] = 0;
4660
4661
        //	OFFICIAL CODE
4662
        $field_list_array['official_code']['name'] = get_lang('OfficialCode');
4663
4664 View Code Duplication
        if (api_get_setting('profile', 'officialcode') != 'true') {
4665
            $field_list_array['official_code']['visibility'] = 1;
4666
        } else {
4667
            $field_list_array['official_code']['visibility'] = 0;
4668
        }
4669
4670
        // EMAIL
4671
        $field_list_array['email']['name'] = get_lang('Email');
4672 View Code Duplication
        if (api_get_setting('profile', 'email') != 'true') {
4673
            $field_list_array['email']['visibility'] = 1;
4674
        } else {
4675
            $field_list_array['email']['visibility'] = 0;
4676
        }
4677
4678
        // PHONE
4679
        $field_list_array['phone']['name'] = get_lang('Phone');
4680 View Code Duplication
        if (api_get_setting('profile', 'phone') != 'true') {
4681
            $field_list_array['phone']['visibility'] = 0;
4682
        } else {
4683
            $field_list_array['phone']['visibility'] = 1;
4684
        }
4685
        //	LANGUAGE
4686
        $field_list_array['language']['name'] = get_lang('Language');
4687 View Code Duplication
        if (api_get_setting('profile', 'language') != 'true') {
4688
            $field_list_array['language']['visibility'] = 0;
4689
        } else {
4690
            $field_list_array['language']['visibility'] = 1;
4691
        }
4692
4693
        // EXTRA FIELDS
4694
        $extra = UserManager::get_extra_fields(0, 50, 5, 'ASC');
4695
4696
        foreach ($extra as $id => $field_details) {
4697
            if ($field_details[6] == 0) {
4698
                continue;
4699
            }
4700
            switch ($field_details[2]) {
4701 View Code Duplication
                case UserManager::USER_FIELD_TYPE_TEXT:
4702
                    $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4703
                    if ($field_details[7] == 0) {
4704
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4705
                    } else {
4706
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
4707
                    }
4708
                    break;
4709 View Code Duplication
                case UserManager::USER_FIELD_TYPE_TEXTAREA:
4710
                    $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4711
                    if ($field_details[7] == 0) {
4712
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4713
                    } else {
4714
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
4715
                    }
4716
                    break;
4717 View Code Duplication
                case UserManager::USER_FIELD_TYPE_RADIO:
4718
                    $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4719
                    if ($field_details[7] == 0) {
4720
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4721
                    } else {
4722
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
4723
                    }
4724
                    break;
4725
                case UserManager::USER_FIELD_TYPE_SELECT:
4726
                    $get_lang_variables = false;
4727 View Code Duplication
                    if (in_array($field_details[1], array('mail_notify_message', 'mail_notify_invitation', 'mail_notify_group_message'))) {
4728
                        $get_lang_variables = true;
4729
                    }
4730
4731
                    if ($get_lang_variables) {
4732
                        $field_list_array['extra_'.$field_details[1]]['name'] = get_lang($field_details[3]);
4733
                    } else {
4734
                        $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4735
                    }
4736
4737
                    if ($field_details[7] == 0) {
4738
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4739
                    } else {
4740
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
4741
                    }
4742
                    break;
4743 View Code Duplication
                case UserManager::USER_FIELD_TYPE_SELECT_MULTIPLE:
4744
                    $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4745
                    if ($field_details[7] == 0) {
4746
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4747
                    } else {
4748
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
4749
                    }
4750
                    break;
4751 View Code Duplication
                case UserManager::USER_FIELD_TYPE_DATE:
4752
                    $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4753
                    if ($field_details[7] == 0) {
4754
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4755
                    } else {
4756
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
4757
                    }
4758
                    break;
4759 View Code Duplication
                case UserManager::USER_FIELD_TYPE_DATETIME:
4760
                    $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4761
                    if ($field_details[7] == 0) {
4762
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4763
                    } else {
4764
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
4765
                    }
4766
                    break;
4767 View Code Duplication
                case UserManager::USER_FIELD_TYPE_DOUBLE_SELECT:
4768
                    $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4769
                    if ($field_details[7] == 0) {
4770
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4771
                    } else {
4772
                        $field_list_array['extra_'.$field_details[1]]['visibility']=1;
4773
                    }
4774
                    break;
4775
                case UserManager::USER_FIELD_TYPE_DIVIDER:
4776
                    //$form->addElement('static',$field_details[1], '<br /><strong>'.$field_details[3].'</strong>');
4777
                    break;
4778
            }
4779
        }
4780
        return $field_list_array;
4781
    }
4782
4783
    /**
4784
     * @author Isaac Flores Paz <[email protected]>
4785
     * @param int $user_id - User ID
4786
     * @param int $user_id_answer - User in survey answer table (user id or anonymus)
0 ignored issues
show
Documentation introduced by
There is no parameter named $user_id_answer. Did you maybe mean $user_id?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
4787
     * @return boolean
4788
     */
4789
    static function show_link_available($user_id, $survey_code, $user_answer)
4790
    {
4791
        $table_survey             = Database :: get_course_table(TABLE_SURVEY);
4792
        $table_survey_invitation  = Database :: get_course_table(TABLE_SURVEY_INVITATION);
4793
        $table_survey_answer      = Database :: get_course_table(TABLE_SURVEY_ANSWER);
4794
        $table_survey_question    = Database :: get_course_table(TABLE_SURVEY_QUESTION);
4795
4796
        $survey_code = Database::escape_string($survey_code);
4797
        $user_id = intval($user_id);
4798
        $user_answer = Database::escape_string($user_answer);
4799
4800
        $course_id = api_get_course_int_id();
4801
4802
        $sql = 'SELECT COUNT(*) as count
4803
                FROM '.$table_survey_invitation.'
4804
		        WHERE user='.$user_id.' AND survey_code="'.$survey_code.'" AND answered="1" AND c_id = '.$course_id.' ';
4805
4806
        $sql2 = 'SELECT COUNT(*) as count FROM '.$table_survey.' s INNER JOIN '.$table_survey_question.' q ON s.survey_id=q.survey_id
4807
				 WHERE s.code="'.$survey_code.'" AND q.type NOT IN("pagebreak","comment") AND s.c_id = '.$course_id.' AND q.c_id = '.$course_id.' ';
4808
4809
        $sql3 = 'SELECT COUNT(DISTINCT question_id) as count FROM '.$table_survey_answer.'
4810
				 WHERE survey_id=(SELECT survey_id FROM '.$table_survey.'
4811
				 WHERE code="'.$survey_code.'" AND c_id = '.$course_id.' ) AND user="'.$user_answer.'" AND c_id = '.$course_id.' ';
4812
4813
        $result  = Database::query($sql);
4814
        $result2 = Database::query($sql2);
4815
        $result3 = Database::query($sql3);
4816
4817
        $row  = Database::fetch_array($result, 'ASSOC');
4818
        $row2 = Database::fetch_array($result2, 'ASSOC');
4819
        $row3 = Database::fetch_array($result3, 'ASSOC');
4820
4821
        if ($row['count'] == 1 && $row3['count'] != $row2['count']) {
4822
            return true;
4823
        } else {
4824
            return false;
4825
        }
4826
    }
4827
4828
    /**
4829
     * Display survey question chart
4830
     * @param	array	Chart data
4831
     * @param	boolean	Tells if the chart has a serie. False by default
4832
     * @return	void 	(direct output)
4833
     */
4834
    public static function drawChart($chartData, $hasSerie = false, $chartContainerId = 'chartContainer')
4835
    {
4836
        $htmlChart = '';
4837
        if (api_browser_support("svg")) {
4838
            $htmlChart .= api_get_js("d3/d3.v3.5.4.min.js");
4839
            $htmlChart .= api_get_js("dimple.v2.1.2.min.js") . '
4840
            <script type="text/javascript">
4841
            var svg = dimple.newSvg("#'.$chartContainerId.'", "100%", 400);
4842
            var data = [';
4843
            $serie = array();
4844
            $order = array();
4845
            foreach ($chartData as $chartDataElement) {
4846
                $htmlChart .= '{"';
4847
                if (!$hasSerie) {
4848
                    $htmlChart .= get_lang("Option") . '":"' . $chartDataElement['option'] . '", "';
4849
                    array_push($order, $chartDataElement['option']);
4850
                } else {
4851
                    if (!is_array($chartDataElement['serie'])) {
4852
                        $htmlChart .= get_lang("Option") . '":"' . $chartDataElement['serie'] . '", "' .
4853
                            get_lang("Score") . '":"' . $chartDataElement['option'] . '", "';
4854
                        array_push($serie, $chartDataElement['serie']);
4855
                    } else {
4856
                        $htmlChart .= get_lang("Serie") . '":"' . $chartDataElement['serie'][0] . '", "' .
4857
                            get_lang("Option") . '":"' . $chartDataElement['serie'][1] . '", "' .
4858
                            get_lang("Score") . '":"' . $chartDataElement['option'] . '", "';
4859
                    }
4860
                }
4861
                $htmlChart .= get_lang("Votes") . '":"' . $chartDataElement['votes'] .
4862
                    '"},';
4863
            }
4864
            rtrim($htmlChart, ",");
4865
            $htmlChart .= '];
4866
                var myChart = new dimple.chart(svg, data);
4867
                myChart.addMeasureAxis("y", "' . get_lang("Votes") . '");';
4868
            if (!$hasSerie) {
4869
                $htmlChart .= 'var xAxisCategory = myChart.addCategoryAxis("x", "' . get_lang("Option") . '");
4870
                    xAxisCategory.addOrderRule(' . json_encode($order) . ');
4871
                    myChart.addSeries("' . get_lang("Option") . '", dimple.plot.bar);';
4872
            } else {
4873
                if (!is_array($chartDataElement['serie'])) {
0 ignored issues
show
Bug introduced by
The variable $chartDataElement seems to be defined by a foreach iteration on line 4845. Are you sure the iterator is never empty, otherwise this variable is not defined?

It seems like you are relying on a variable being defined by an iteration:

foreach ($a as $b) {
}

// $b is defined here only if $a has elements, for example if $a is array()
// then $b would not be defined here. To avoid that, we recommend to set a
// default value for $b.


// Better
$b = 0; // or whatever default makes sense in your context
foreach ($a as $b) {
}

// $b is now guaranteed to be defined here.
Loading history...
4874
                    $serie = array_values(array_unique($serie));
4875
                    $htmlChart .= 'var xAxisCategory = myChart.addCategoryAxis("x", ["' . get_lang("Option") . '","' . get_lang("Score") . '"]);
4876
                        xAxisCategory.addOrderRule(' . json_encode($serie) . ');
4877
                        xAxisCategory.addGroupOrderRule("' . get_lang("Score") . '");
4878
                        myChart.addSeries("' . get_lang("Option") . '", dimple.plot.bar);';
4879
                } else {
4880
                    $htmlChart .= 'myChart.addCategoryAxis("x", ["' . get_lang("Option") . '","' . get_lang("Score") . '"]);
4881
                        myChart.addSeries("' . get_lang("Serie") . '", dimple.plot.bar);';
4882
                }
4883
            }
4884
            $htmlChart .= 'myChart.draw();
4885
                </script>';
4886
        }
4887
        return $htmlChart;
4888
    }
4889
4890
    /**
4891
     * Set a flag to the current survey as answered by the current user
4892
     * @param string $surveyCode The survey code
4893
     * @param int $courseId The course ID
4894
     */
4895
    public static function flagSurveyAsAnswered($surveyCode, $courseId)
4896
    {
4897
        $currenUserId = api_get_user_id();
4898
        $flag = sprintf("%s-%s-%d", $courseId, $surveyCode, $currenUserId);
4899
4900
        if (!isset($_SESSION['filled_surveys'])) {
4901
            $_SESSION['filled_surveys'] = array();
4902
        }
4903
4904
        $_SESSION['filled_surveys'][] = $flag;
4905
    }
4906
4907
    /**
4908
     * Check whether a survey was answered by the current user
4909
     * @param string $surveyCode The survey code
4910
     * @param int $courseId The course ID
4911
     * @return boolean
4912
     */
4913
    public static function isSurveyAnsweredFlagged($surveyCode, $courseId)
4914
    {
4915
        $currenUserId = api_get_user_id();
4916
        $flagToCheck = sprintf("%s-%s-%d", $courseId, $surveyCode, $currenUserId);
4917
4918
        if (!isset($_SESSION['filled_surveys'])) {
4919
            return false;
4920
        }
4921
4922
        if (!is_array($_SESSION['filled_surveys'])) {
4923
            return false;
4924
        }
4925
4926
        foreach ($_SESSION['filled_surveys'] as $flag) {
4927
            if ($flagToCheck != $flag) {
4928
                continue;
4929
            }
4930
4931
            return true;
4932
        }
4933
4934
        return false;
4935
    }
4936
}
4937