Completed
Push — master ( 565c08...93d030 )
by José
125:33 queued 71:22
created

SurveyUtil::get_invited_users()   C

Complexity

Conditions 12
Paths 224

Size

Total Lines 63
Code Lines 41

Duplication

Lines 13
Ratio 20.63 %

Importance

Changes 0
Metric Value
cc 12
eloc 41
nc 224
nop 3
dl 13
loc 63
rs 5.0673
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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::isResourceInCourseGradebook(
467
            $course_id,
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::updateResourceFromCourseGradebook(
497
                        $gradebook_link_id,
498
                        $course_id,
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);
0 ignored issues
show
Bug introduced by
It seems like $shared defined by parameter $shared on line 1345 can also be of type integer; however, SurveyManager::delete_survey_question_option() does only seem to accept boolean, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
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
1520
        return true;
1521
    }
1522
1523
    /**
1524
     * This function deletes the options of a given question
1525
     *
1526
     * @param int $survey_id
1527
     * @param int $question_id
1528
     * @param bool $shared
1529
     *
1530
     * @return bool
1531
     *
1532
     * @author Patrick Cool <[email protected]>, Ghent University
1533
     * @author Julio Montoya
1534
     * @version March 2007
1535
     */
1536 View Code Duplication
    public static function delete_survey_question_option($survey_id, $question_id, $shared = false)
1537
    {
1538
        $course_id = api_get_course_int_id();
1539
        $course_condition = " c_id = $course_id AND ";
1540
1541
        // Table definitions
1542
        $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
1543
        if ($shared) {
1544
            $course_condition = "";
1545
            $table_survey_question_option = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
1546
        }
1547
1548
        // Deleting the options of the survey questions
1549
        $sql = "DELETE from $table_survey_question_option
1550
		        WHERE
1551
		            $course_condition survey_id='".intval($survey_id)."' AND
1552
		            question_id='".intval($question_id)."'";
1553
        Database::query($sql);
1554
        return true;
1555
    }
1556
1557
    /**
1558
     * SURVEY ANSWERS FUNCTIONS
1559
     */
1560
1561
    /**
1562
     * This function deletes all the answers anyone has given on this survey
1563
     * This function is normally only called when a survey is deleted
1564
     *
1565
     * @param $survey_id the id of the survey that has to be deleted
1566
     * @return true
1567
     *
1568
     * @todo write the function
1569
     *
1570
     * @author Patrick Cool <[email protected]>, Ghent University
1571
     * @version January 2007,december 2008
1572
     */
1573 View Code Duplication
    public static function delete_all_survey_answers($survey_id)
1574
    {
1575
        $course_id = api_get_course_int_id();
1576
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
1577
        $survey_id = intval($survey_id);
1578
        Database::query("DELETE FROM $table_survey_answer WHERE c_id = $course_id AND survey_id=$survey_id");
1579
        return true;
1580
    }
1581
1582
    /**
1583
     * @param int $user_id
1584
     * @param int $survey_id
1585
     * @param int $course_id
1586
     * @return bool
1587
     */
1588 View Code Duplication
    public static function is_user_filled_survey($user_id, $survey_id, $course_id)
1589
    {
1590
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
1591
1592
        $user_id	= intval($user_id);
1593
        $course_id	= intval($course_id);
1594
        $survey_id	= intval($survey_id);
1595
1596
        $sql = "SELECT DISTINCT user FROM $table_survey_answer
1597
                WHERE
1598
                    c_id		= $course_id AND
1599
                    user		= $user_id AND
1600
                    survey_id	= $survey_id";
1601
        $result = Database::query($sql);
1602
        if (Database::num_rows($result)) {
1603
            return true;
1604
        }
1605
        return false;
1606
    }
1607
1608
    /**
1609
     * This function gets all the persons who have filled the survey
1610
     *
1611
     * @param integer $survey_id
1612
     * @return array
1613
     *
1614
     * @author Patrick Cool <[email protected]>, Ghent University
1615
     * @version February 2007
1616
     */
1617
    public static function get_people_who_filled_survey($survey_id, $all_user_info = false, $course_id = null)
1618
    {
1619
        // Database table definition
1620
        $table_survey_answer = Database:: get_course_table(TABLE_SURVEY_ANSWER);
1621
        $table_user = Database:: get_main_table(TABLE_MAIN_USER);
1622
1623
        // Variable initialisation
1624
        $return = array();
1625
1626
        if (empty($course_id)) {
1627
            $course_id = api_get_course_int_id();
1628
        } else {
1629
            $course_id = intval($course_id);
1630
        }
1631
1632
        if ($all_user_info) {
1633
            $order_clause = api_sort_by_first_name() ? ' ORDER BY user.firstname, user.lastname' : ' ORDER BY user.lastname, user.firstname';
1634
            $sql = "SELECT DISTINCT
1635
			            answered_user.user as invited_user, user.firstname, user.lastname, user.user_id
1636
                    FROM $table_survey_answer answered_user
1637
                    LEFT JOIN $table_user as user ON answered_user.user = user.user_id
1638
                    WHERE
1639
                        answered_user.c_id = $course_id AND
1640
                        survey_id= '".Database::escape_string($survey_id)."' ".
1641
                $order_clause;
1642
        } else {
1643
            $sql = "SELECT DISTINCT user FROM $table_survey_answer
1644
			        WHERE c_id = $course_id AND survey_id= '".Database::escape_string($survey_id)."'  ";
1645
        }
1646
1647
        $res = Database::query($sql);
1648
        while ($row = Database::fetch_array($res, 'ASSOC')) {
1649
            if ($all_user_info) {
1650
                $return[] = $row;
1651
            } else {
1652
                $return[] = $row['user'];
1653
            }
1654
        }
1655
1656
        return $return;
1657
    }
1658
1659
    /**
1660
     * @return bool
1661
     */
1662
    public static function survey_generation_hash_available()
1663
    {
1664
        if (extension_loaded('mcrypt')) {
1665
            return true;
1666
        }
1667
        return false;
1668
    }
1669
1670
    /**
1671
     * @param int $survey_id
1672
     * @param int $course_id
1673
     * @param int $session_id
1674
     * @param int $group_id
1675
     * @return string
1676
     */
1677
    public static function generate_survey_hash($survey_id, $course_id, $session_id, $group_id)
1678
    {
1679
        $hash = hash('sha512', api_get_security_key().'_'.$course_id.'_'.$session_id.'_'.$group_id.'_'.$survey_id);
1680
        return $hash;
1681
    }
1682
1683
    /**
1684
     * @param int $survey_id
1685
     * @param int $course_id
1686
     * @param int $session_id
1687
     * @param int $group_id
1688
     * @param string $hash
1689
     *
1690
     * @return bool
1691
     */
1692
    public static function validate_survey_hash($survey_id, $course_id, $session_id, $group_id, $hash)
1693
    {
1694
        $survey_generated_hash = self::generate_survey_hash($survey_id, $course_id, $session_id, $group_id);
1695
        if ($survey_generated_hash == $hash) {
1696
            return true;
1697
        }
1698
        return false;
1699
    }
1700
1701
    /**
1702
     * @param int $survey_id
1703
     * @param int $course_id
1704
     * @param int $session_id
1705
     * @param int $group_id
1706
     *
1707
     * @return string
1708
     */
1709
    public static function generate_survey_link($survey_id, $course_id, $session_id, $group_id)
1710
    {
1711
        $code = self::generate_survey_hash($survey_id, $course_id, $session_id, $group_id);
1712
        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;
1713
    }
1714
}
1715
1716
1717
/**
1718
 * This class offers a series of general utility functions for survey querying and display
1719
 * @package chamilo.survey
1720
 */
1721
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...
1722
{
1723
    /**
1724
     * Checks whether the given survey has a pagebreak question as the first or the last question.
1725
     * If so, break the current process, displaying an error message
1726
     * @param	integer	Survey ID (database ID)
1727
     * @param	boolean	Optional. Whether to continue the current process or exit when breaking condition found. Defaults to true (do not break).
1728
     * @return	void
1729
     */
1730
    public static function check_first_last_question($survey_id, $continue = true)
1731
    {
1732
        // Table definitions
1733
        $tbl_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
1734
        $course_id = api_get_course_int_id();
1735
1736
        // Getting the information of the question
1737
        $sql = "SELECT * FROM $tbl_survey_question
1738
                WHERE c_id = $course_id AND survey_id='".Database::escape_string($survey_id)."'
1739
                ORDER BY sort ASC";
1740
        $result = Database::query($sql);
1741
        $total = Database::num_rows($result);
1742
        $counter = 1;
1743
        $error = false;
1744
        while ($row = Database::fetch_array($result, 'ASSOC')) {
1745 View Code Duplication
            if ($counter == 1 && $row['type'] == 'pagebreak') {
1746
1747
                Display::display_error_message(get_lang('PagebreakNotFirst'), false);
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_error_message() has been deprecated with message: use Display::addFlash with Display::return_message

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1748
                $error = true;
1749
            }
1750 View Code Duplication
            if ($counter == $total && $row['type'] == 'pagebreak') {
1751
                Display::display_error_message(get_lang('PagebreakNotLast'), false);
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_error_message() has been deprecated with message: use Display::addFlash with Display::return_message

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1752
                $error = true;
1753
            }
1754
            $counter++;
1755
        }
1756
1757
        if (!$continue && $error) {
1758
            Display::display_footer();
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_footer() has been deprecated with message: See template.lib.php class documentation

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1759
            exit;
1760
        }
1761
    }
1762
1763
    /**
1764
     * This function removes an (or multiple) answer(s) of a user on a question of a survey
1765
     *
1766
     * @param mixed   The user id or email of the person who fills the survey
1767
     * @param integer The survey id
1768
     * @param integer The question id
1769
     * @param integer The option id
1770
     *
1771
     * @author Patrick Cool <[email protected]>, Ghent University
1772
     * @version January 2007
1773
     */
1774
    public static function remove_answer($user, $survey_id, $question_id, $course_id) {
1775
        $course_id = intval($course_id);
1776
        // table definition
1777
        $table_survey_answer 		= Database :: get_course_table(TABLE_SURVEY_ANSWER);
1778
        $sql = "DELETE FROM $table_survey_answer
1779
				WHERE
1780
				    c_id = $course_id AND
1781
                    user = '".Database::escape_string($user)."' AND
1782
                    survey_id = '".intval($survey_id)."' AND
1783
                    question_id = '".intval($question_id)."'";
1784
        Database::query($sql);
1785
    }
1786
1787
    /**
1788
     * This function stores an answer of a user on a question of a survey
1789
     *
1790
     * @param mixed   The user id or email of the person who fills the survey
1791
     * @param integer Survey id
1792
     * @param integer Question id
1793
     * @param integer Option id
1794
     * @param string  Option value
1795
     * @param array	  Survey data settings
1796
     * @return bool False if insufficient data, true otherwise
1797
     *
1798
     * @author Patrick Cool <[email protected]>, Ghent University
1799
     * @version January 2007
1800
     */
1801
    public static function store_answer($user, $survey_id, $question_id, $option_id, $option_value, $survey_data)
1802
    {
1803
        // If the question_id is empty, don't store an answer
1804
        if (empty($question_id)) {
1805
            return false;
1806
        }
1807
        // Table definition
1808
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
1809
1810
        // Make the survey anonymous
1811
        if ($survey_data['anonymous'] == 1) {
1812
            if (!isset($_SESSION['surveyuser'])) {
1813
                $user = md5($user.time());
1814
                $_SESSION['surveyuser'] = $user;
1815
            } else {
1816
                $user = $_SESSION['surveyuser'];
1817
            }
1818
        }
1819
1820
        $course_id = $survey_data['c_id'];
1821
1822
        $sql = "INSERT INTO $table_survey_answer (c_id, user, survey_id, question_id, option_id, value) VALUES (
1823
				$course_id,
1824
				'".Database::escape_string($user)."',
1825
				'".Database::escape_string($survey_id)."',
1826
				'".Database::escape_string($question_id)."',
1827
				'".Database::escape_string($option_id)."',
1828
				'".Database::escape_string($option_value)."'
1829
				)";
1830
        Database::query($sql);
1831
        $insertId = Database::insert_id();
1832
1833
        $sql = "UPDATE $table_survey_answer SET answer_id = $insertId WHERE iid = $insertId";
1834
        Database::query($sql);
1835
        return true;
1836
    }
1837
1838
    /**
1839
     * This function checks the parameters that are used in this page
1840
     *
1841
     * @return 	string 	The header, an error and the footer if any parameter fails, else it returns true
1842
     * @author Patrick Cool <[email protected]>, Ghent University
1843
     * @version February 2007
1844
     */
1845
    public static function check_parameters($people_filled)
1846
    {
1847
        $error = false;
1848
1849
        // Getting the survey data
1850
        $survey_data = SurveyManager::get_survey($_GET['survey_id']);
1851
1852
        // $_GET['survey_id'] has to be numeric
1853
        if (!is_numeric($_GET['survey_id'])) {
1854
            $error = get_lang('IllegalSurveyId');
1855
        }
1856
1857
        // $_GET['action']
1858
        $allowed_actions = array(
1859
            'overview',
1860
            'questionreport',
1861
            'userreport',
1862
            'comparativereport',
1863
            'completereport',
1864
            'deleteuserreport'
1865
        );
1866
        if (isset($_GET['action']) && !in_array($_GET['action'], $allowed_actions)) {
1867
            $error = get_lang('ActionNotAllowed');
1868
        }
1869
1870
        // User report
1871
        if (isset($_GET['action']) && $_GET['action'] == 'userreport') {
1872
            if ($survey_data['anonymous'] == 0) {
1873
                foreach ($people_filled as $key => & $value) {
1874
                    $people_filled_userids[] = $value['invited_user'];
1875
                }
1876
            } else {
1877
                $people_filled_userids = $people_filled;
1878
            }
1879
1880
            if (isset($_GET['user']) && !in_array($_GET['user'], $people_filled_userids)) {
1881
                $error = get_lang('UnknowUser');
1882
            }
1883
        }
1884
1885
        // Question report
1886
        if (isset($_GET['action']) && $_GET['action'] == 'questionreport') {
1887
            if (isset($_GET['question']) && !is_numeric($_GET['question'])) {
1888
                $error = get_lang('UnknowQuestion');
1889
            }
1890
        }
1891
1892
        if ($error) {
1893
            $tool_name = get_lang('Reporting');
1894
            Display::display_header($tool_name);
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_header() has been deprecated with message: See template.lib.php class documentation

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1895
            Display::display_error_message(get_lang('Error').': '.$error, false);
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_error_message() has been deprecated with message: use Display::addFlash with Display::return_message

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1896
            Display::display_footer();
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_footer() has been deprecated with message: See template.lib.php class documentation

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1897
            exit;
1898
        } else {
1899
            return true;
1900
        }
1901
    }
1902
1903
    /**
1904
     * This function deals with the action handling
1905
     * @return	void
1906
     * @author Patrick Cool <[email protected]>, Ghent University
1907
     * @version February 2007
1908
     */
1909
    public static function handle_reporting_actions($survey_data, $people_filled)
1910
    {
1911
        $action = isset($_GET['action']) ? $_GET['action'] : null;
1912
1913
        // Getting the number of question
1914
        $temp_questions_data = SurveyManager::get_questions($_GET['survey_id']);
1915
1916
        // Sorting like they should be displayed and removing the non-answer question types (comment and pagebreak)
1917
        $my_temp_questions_data = $temp_questions_data == null ? array() : $temp_questions_data;
1918
        $questions_data = array();
1919
1920
        foreach ($my_temp_questions_data as $key => & $value) {
1921
            if ($value['type'] != 'comment' && $value['type'] != 'pagebreak') {
1922
                $questions_data[$value['sort']] = $value;
1923
            }
1924
        }
1925
1926
        // Counting the number of questions that are relevant for the reporting
1927
        $survey_data['number_of_questions'] = count($questions_data);
1928
1929
        if ($action == 'questionreport') {
1930
            SurveyUtil::display_question_report($survey_data);
1931
        }
1932
        if ($action == 'userreport') {
1933
            SurveyUtil::display_user_report($people_filled, $survey_data);
1934
        }
1935
        if ($action == 'comparativereport') {
1936
            SurveyUtil::display_comparative_report();
1937
        }
1938
        if ($action == 'completereport') {
1939
            SurveyUtil::display_complete_report($survey_data);
1940
        }
1941
        if ($action == 'deleteuserreport') {
1942
            SurveyUtil::delete_user_report($_GET['survey_id'], $_GET['user']);
1943
        }
1944
    }
1945
1946
    /**
1947
     * This function deletes the report of an user who wants to retake the survey
1948
     * @param integer $survey_id
1949
     * @param integer $user_id
1950
     * @return void
1951
     * @author Christian Fasanando Flores <[email protected]>
1952
     * @version November 2008
1953
     */
1954
    public static function delete_user_report($survey_id, $user_id)
1955
    {
1956
        $table_survey_answer = Database:: get_course_table(TABLE_SURVEY_ANSWER);
1957
        $table_survey_invitation = Database:: get_course_table(TABLE_SURVEY_INVITATION);
1958
        $table_survey = Database:: get_course_table(TABLE_SURVEY);
1959
1960
        $course_id = api_get_course_int_id();
1961
        $survey_id = (int) $survey_id;
1962
        $user_id = Database::escape_string($user_id);
1963
1964
        if (!empty($survey_id) && !empty($user_id)) {
1965
            // delete data from survey_answer by user_id and survey_id
1966
            $sql = "DELETE FROM $table_survey_answer
1967
			        WHERE c_id = $course_id AND survey_id = '".$survey_id."' AND user = '".$user_id."'";
1968
            Database::query($sql);
1969
            // update field answered from survey_invitation by user_id and survey_id
1970
            $sql = "UPDATE $table_survey_invitation SET answered = '0'
1971
			        WHERE
1972
			            c_id = $course_id AND
1973
			            survey_code = (
1974
                            SELECT code FROM $table_survey
1975
                            WHERE
1976
                                c_id = $course_id AND
1977
                                survey_id = '".$survey_id."'
1978
                        ) AND
1979
			            user = '".$user_id."'";
1980
            $result = Database::query($sql);
1981
        }
1982
1983 View Code Duplication
        if ($result !== false) {
1984
            $message = get_lang('SurveyUserAnswersHaveBeenRemovedSuccessfully').'<br />
1985
					<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action=userreport&survey_id='.$survey_id.'">'.
1986
                get_lang('GoBack').'</a>';
1987
            Display::display_confirmation_message($message, false);
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_confirmation_message() has been deprecated with message: use Display::addFlash with Display::return_message

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1988
        }
1989
    }
1990
1991
    /**
1992
     * This function displays the user report which is basically nothing more
1993
     * than a one-page display of all the questions
1994
     * of the survey that is filled with the answers of the person who filled the survey.
1995
     *
1996
     * @return 	string	html code of the one-page survey with the answers of the selected user
1997
     * @author Patrick Cool <[email protected]>, Ghent University
1998
     * @version February 2007 - Updated March 2008
1999
     */
2000
    public static function display_user_report($people_filled, $survey_data)
2001
    {
2002
        // Database table definitions
2003
        $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
2004
        $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
2005
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
2006
2007
        $surveyId = isset($_GET['survey_id']) ? (int) $_GET['survey_id'] : 0;
2008
2009
        // Actions bar
2010
        echo '<div class="actions">';
2011
        echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.$surveyId.'&'.api_get_cidreq().'">'.
2012
            Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('ReportingOverview'),'',ICON_SIZE_MEDIUM).'</a>';
2013
        if (isset($_GET['user'])) {
2014 View Code Duplication
            if (api_is_allowed_to_edit()) {
2015
                // The delete link
2016
                echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action=deleteuserreport&survey_id='.$surveyId.'&'.api_get_cidreq().'&user='.Security::remove_XSS($_GET['user']).'" >'.
2017
                    Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_MEDIUM).'</a>';
2018
            }
2019
2020
            // Export the user report
2021
            echo '<a href="javascript: void(0);" onclick="document.form1a.submit();">'.
2022
                Display::return_icon('export_csv.png', get_lang('ExportAsCSV'),'',ICON_SIZE_MEDIUM).'</a> ';
2023
            echo '<a href="javascript: void(0);" onclick="document.form1b.submit();">'.
2024
                Display::return_icon('export_excel.png', get_lang('ExportAsXLS'),'',ICON_SIZE_MEDIUM).'</a> ';
2025
            echo '<form id="form1a" name="form1a" method="post" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.$surveyId.'&'.api_get_cidreq().'&user_id='.Security::remove_XSS($_GET['user']).'">';
2026
            echo '<input type="hidden" name="export_report" value="export_report">';
2027
            echo '<input type="hidden" name="export_format" value="csv">';
2028
            echo '</form>';
2029
            echo '<form id="form1b" name="form1b" method="post" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.$surveyId.'&'.api_get_cidreq().'&user_id='.Security::remove_XSS($_GET['user']).'">';
2030
            echo '<input type="hidden" name="export_report" value="export_report">';
2031
            echo '<input type="hidden" name="export_format" value="xls">';
2032
            echo '</form>';
2033
            echo '<form id="form2" name="form2" method="post" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.$surveyId.'&'.api_get_cidreq().'">';
2034
        }
2035
        echo '</div>';
2036
2037
        // Step 1: selection of the user
2038
        echo "<script>
2039
        function jumpMenu(targ,selObj,restore) {
2040
            eval(targ+\".location='\"+selObj.options[selObj.selectedIndex].value+\"'\");
2041
            if (restore) selObj.selectedIndex=0;
2042
        }
2043
		</script>";
2044
        echo get_lang('SelectUserWhoFilledSurvey').'<br />';
2045
        echo '<select name="user" onchange="jumpMenu(\'parent\',this,0)">';
2046
        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>';
2047
2048
        foreach ($people_filled as $key => & $person) {
2049
            if ($survey_data['anonymous'] == 0) {
2050
                $name = api_get_person_name($person['firstname'], $person['lastname']);
2051
                $id = $person['user_id'];
2052
                if ($id == '') {
2053
                    $id = $person['invited_user'];
2054
                    $name = $person['invited_user'];
2055
                }
2056
            } else {
2057
                $name  = get_lang('Anonymous') . ' ' . ($key + 1);
2058
                $id = $person;
2059
            }
2060
            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).'" ';
2061
            if (isset($_GET['user']) && $_GET['user'] == $id) {
2062
                echo 'selected="selected"';
2063
            }
2064
            echo '>'.$name.'</option>';
2065
        }
2066
        echo '</select>';
2067
2068
        $course_id = api_get_course_int_id();
2069
        // Step 2: displaying the survey and the answer of the selected users
2070
        if (isset($_GET['user'])) {
2071
            Display::display_normal_message(
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_normal_message() has been deprecated with message: use Display::addFlash with Display::return_message($message, 'normal');

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
2072
                get_lang('AllQuestionsOnOnePage'),
2073
                false
2074
            );
2075
2076
            // Getting all the questions and options
2077
            $sql = "SELECT
2078
			            survey_question.question_id,
2079
			            survey_question.survey_id,
2080
			            survey_question.survey_question,
2081
			            survey_question.display,
2082
			            survey_question.max_value,
2083
			            survey_question.sort,
2084
			            survey_question.type,
2085
                        survey_question_option.question_option_id,
2086
                        survey_question_option.option_text,
2087
                        survey_question_option.sort as option_sort
2088
					FROM $table_survey_question survey_question
2089
					LEFT JOIN $table_survey_question_option survey_question_option
2090
					ON
2091
					    survey_question.question_id = survey_question_option.question_id AND
2092
					    survey_question_option.c_id = $course_id
2093
					WHERE
2094
					    survey_question.survey_id = '".Database::escape_string(
2095
                    $_GET['survey_id']
2096
                )."' AND
2097
                        survey_question.c_id = $course_id
2098
					ORDER BY survey_question.sort, survey_question_option.sort ASC";
2099
            $result = Database::query($sql);
2100 View Code Duplication
            while ($row = Database::fetch_array($result, 'ASSOC')) {
2101
                if ($row['type'] != 'pagebreak') {
2102
                    $questions[$row['sort']]['question_id'] = $row['question_id'];
2103
                    $questions[$row['sort']]['survey_id'] = $row['survey_id'];
2104
                    $questions[$row['sort']]['survey_question'] = $row['survey_question'];
2105
                    $questions[$row['sort']]['display'] = $row['display'];
2106
                    $questions[$row['sort']]['type'] = $row['type'];
2107
                    $questions[$row['sort']]['maximum_score'] = $row['max_value'];
2108
                    $questions[$row['sort']]['options'][$row['question_option_id']] = $row['option_text'];
2109
                }
2110
            }
2111
2112
            // Getting all the answers of the user
2113
            $sql = "SELECT * FROM $table_survey_answer
2114
			        WHERE
2115
                        c_id = $course_id AND
2116
                        survey_id = '".intval($_GET['survey_id'])."' AND
2117
                        user = '".Database::escape_string($_GET['user'])."'";
2118
            $result = Database::query($sql);
2119
            while ($row = Database::fetch_array($result, 'ASSOC')) {
2120
                $answers[$row['question_id']][] = $row['option_id'];
2121
                $all_answers[$row['question_id']][] = $row;
2122
            }
2123
2124
            // Displaying all the questions
2125
2126
            foreach ($questions as & $question) {
2127
                // If the question type is a scoring then we have to format the answers differently
2128
                switch ($question['type']) {
2129
                    case 'score':
2130
                        $finalAnswer = array();
2131
                        if (is_array($question) && is_array($all_answers)) {
2132
                            foreach ($all_answers[$question['question_id']] as $key => & $answer_array) {
2133
                                $finalAnswer[$answer_array['option_id']] = $answer_array['value'];
2134
                            }
2135
                        }
2136
                        break;
2137
                    case 'multipleresponse':
2138
                        $finalAnswer = isset($answers[$question['question_id']]) ? $answers[$question['question_id']] : '';
2139
                        break;
2140
                    default:
2141
                        $finalAnswer = '';
2142
                        if (isset($all_answers[$question['question_id']])) {
2143
                            $finalAnswer = $all_answers[$question['question_id']][0]['option_id'];
2144
                        }
2145
                        break;
2146
                }
2147
2148
                $ch_type = 'ch_'.$question['type'];
2149
                /** @var survey_question $display */
2150
                $display = new $ch_type;
2151
2152
                $url = api_get_self();
2153
                $form = new FormValidator('question', 'post', $url);
2154
                $form->addHtml('<div class="survey_question_wrapper"><div class="survey_question">');
2155
                $form->addHtml($question['survey_question']);
2156
                $display->render($form, $question, $finalAnswer);
2157
                $form->addHtml('</div></div>');
2158
                $form->display();
2159
            }
2160
        }
2161
    }
2162
2163
    /**
2164
     * This function displays the report by question.
2165
     *
2166
     * It displays a table with all the options of the question and the number of users who have answered positively on the option.
2167
     * The number of users who answered positive on a given option is expressed in an absolute number, in a percentage of the total
2168
     * and graphically using bars
2169
     * By clicking on the absolute number you get a list with the persons who have answered this.
2170
     * 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
2171
     * answers of that user.
2172
     *
2173
     * @param 	array 	All the survey data
2174
     * @return 	string	html code that displays the report by question
2175
     * @todo allow switching between horizontal and vertical.
2176
     * @todo multiple response: percentage are probably not OK
2177
     * @todo the question and option text have to be shortened and should expand when the user clicks on it.
2178
     * @todo the pagebreak and comment question types should not be shown => removed from $survey_data before
2179
     * @author Patrick Cool <[email protected]>, Ghent University
2180
     * @version February 2007 - Updated March 2008
2181
     */
2182
    public static function display_question_report($survey_data)
2183
    {
2184
        $singlePage = isset($_GET['single_page']) ? intval($_GET['single_page']) : 0;
2185
        $course_id = api_get_course_int_id();
2186
        // Database table definitions
2187
        $table_survey_question = Database:: get_course_table(TABLE_SURVEY_QUESTION);
2188
        $table_survey_question_option = Database:: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
2189
        $table_survey_answer = Database:: get_course_table(TABLE_SURVEY_ANSWER);
2190
2191
        // Determining the offset of the sql statement (the n-th question of the survey)
2192
        $offset = !isset($_GET['question']) ? 0 : intval($_GET['question']);
2193
        $currentQuestion = isset($_GET['question']) ? intval($_GET['question']) : 0;
2194
        $questions = array();
2195
        $surveyId = intval($_GET['survey_id']);
2196
        $action = Security::remove_XSS($_GET['action']);
2197
2198
        echo '<div class="actions">';
2199
        echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.$surveyId.'">'.
2200
            Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('ReportingOverview'),'',ICON_SIZE_MEDIUM).'</a>';
2201
        echo '</div>';
2202
2203
        if ($survey_data['number_of_questions'] > 0) {
2204
            $limitStatement = null;
2205
            if (!$singlePage) {
2206
                echo '<div id="question_report_questionnumbers" class="pagination">';
2207
                if ($currentQuestion != 0) {
2208
                    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>';
2209
                }
2210
2211
                for ($i = 1; $i <= $survey_data['number_of_questions']; $i++) {
2212
                    if ($offset != $i - 1) {
2213
                        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>';
2214
                    } else {
2215
                        echo '<li class="disabled"s><a href="#">' . $i . '</a></li>';
2216
                    }
2217
                }
2218
                if ($currentQuestion < ($survey_data['number_of_questions'] - 1)) {
2219
                    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>';
2220
                }
2221
                echo '</ul>';
2222
                echo '</div>';
2223
                $limitStatement = " LIMIT $offset, 1";
2224
            }
2225
2226
            // Getting the question information
2227
            $sql = "SELECT * FROM $table_survey_question
2228
			        WHERE
2229
			            c_id = $course_id AND
2230
                        survey_id='".Database::escape_string($_GET['survey_id'])."' AND
2231
                        type<>'pagebreak' AND type<>'comment'
2232
                    ORDER BY sort ASC
2233
                    $limitStatement";
2234
            $result = Database::query($sql);
2235
            //$question = Database::fetch_array($result);
2236
2237
            while ($row = Database::fetch_array($result)) {
2238
                $questions[$row['question_id']] = $row;
2239
            }
2240
        }
2241
2242
        foreach ($questions as $question) {
2243
            $chartData = array();
2244
            $options = array();
2245
            echo '<div class="title-question">';
2246
            echo strip_tags(isset($question['survey_question']) ? $question['survey_question'] : null);
2247
            echo '</div>';
2248
2249
            if ($question['type'] == 'score') {
2250
                /** @todo This function should return the options as this is needed further in the code */
2251
                $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...
2252
            } elseif ($question['type'] == 'open') {
2253
                /** @todo Also get the user who has answered this */
2254
                $sql = "SELECT * FROM $table_survey_answer
2255
                        WHERE
2256
                            c_id = $course_id AND
2257
                            survey_id='" . intval($_GET['survey_id']) . "' AND
2258
                            question_id = '" . intval($question['question_id']) . "'";
2259
                $result = Database::query($sql);
2260
                while ($row = Database::fetch_array($result, 'ASSOC')) {
2261
                    echo $row['option_id'] . '<hr noshade="noshade" size="1" />';
2262
                }
2263
            } else {
2264
                // Getting the options ORDER BY sort ASC
2265
                $sql = "SELECT * FROM $table_survey_question_option
2266
                        WHERE
2267
                            c_id = $course_id AND
2268
                            survey_id='" . intval($_GET['survey_id']) . "'
2269
                            AND question_id = '" . intval($question['question_id']) . "'
2270
                        ORDER BY sort ASC";
2271
                $result = Database::query($sql);
2272
                while ($row = Database::fetch_array($result, 'ASSOC')) {
2273
                    $options[$row['question_option_id']] = $row;
2274
                }
2275
                // Getting the answers
2276
                $sql = "SELECT *, count(answer_id) as total FROM $table_survey_answer
2277
                        WHERE
2278
                            c_id = $course_id AND
2279
                            survey_id='" . intval($_GET['survey_id']) . "'
2280
                            AND question_id = '" . intval($question['question_id']) . "'
2281
                        GROUP BY option_id, value";
2282
                $result = Database::query($sql);
2283
                $number_of_answers = array();
2284
                $data = array();
2285 View Code Duplication
                while ($row = Database::fetch_array($result, 'ASSOC')) {
2286
                    if (!isset($number_of_answers[$row['question_id']])) {
2287
                        $number_of_answers[$row['question_id']] = 0;
2288
                    }
2289
                    $number_of_answers[$row['question_id']] += $row['total'];
2290
                    $data[$row['option_id']] = $row;
2291
                }
2292
2293
                foreach ($options as $option) {
2294
                    $optionText = strip_tags($option['option_text']);
2295
                    $optionText = html_entity_decode($optionText);
2296
                    $votes = isset($data[$option['question_option_id']]['total']) ?
2297
                        $data[$option['question_option_id']]['total'] :
2298
                        '0';
2299
                    array_push($chartData, array('option' => $optionText, 'votes' => $votes));
2300
                }
2301
                $chartContainerId = 'chartContainer'.$question['question_id'];
2302
                echo '<div id="'.$chartContainerId.'" class="col-md-12">';
2303
                echo self::drawChart($chartData, false, $chartContainerId);
2304
2305
                // displaying the table: headers
2306
2307
                echo '<table class="display-survey table">';
2308
                echo '	<tr>';
2309
                echo '		<th>&nbsp;</th>';
2310
                echo '		<th>' . get_lang('AbsoluteTotal') . '</th>';
2311
                echo '		<th>' . get_lang('Percentage') . '</th>';
2312
                echo '		<th>' . get_lang('VisualRepresentation') . '</th>';
2313
                echo '	<tr>';
2314
2315
                // Displaying the table: the content
2316
                if (is_array($options)) {
2317
                    foreach ($options as $key => & $value) {
2318
                        $absolute_number = null;
2319
                        if (isset($data[$value['question_option_id']])) {
2320
                            $absolute_number = $data[$value['question_option_id']]['total'];
2321
                        }
2322
                        if ($question['type'] == 'percentage' && empty($absolute_number)) {
2323
                            continue;
2324
                        }
2325
                        $number_of_answers[$option['question_id']] = isset($number_of_answers[$option['question_id']]) ? $number_of_answers[$option['question_id']] : 0;
0 ignored issues
show
Bug introduced by
The variable $option seems to be defined by a foreach iteration on line 2293. 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...
2326
                        if ($number_of_answers[$option['question_id']] == 0) {
2327
                            $answers_number = 0;
2328
                        } else {
2329
                            $answers_number = $absolute_number / $number_of_answers[$option['question_id']] * 100;
2330
                        }
2331
                        echo '	<tr>';
2332
                        echo '		<td class="center">' . $value['option_text'] . '</td>';
2333
                        echo '		<td class="center">';
2334
                        if ($absolute_number != 0) {
2335
                            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>';
2336
                        } else {
2337
                            echo '0';
2338
                        }
2339
2340
                        echo '      </td>';
2341
                        echo '		<td class="center">' . round($answers_number, 2) . ' %</td>';
2342
                        echo '		<td class="center">';
2343
                        $size = $answers_number * 2;
2344
                        if ($size > 0) {
2345
                            echo '<div style="border:1px solid #264269; background-color:#aecaf4; height:10px; width:' . $size . 'px">&nbsp;</div>';
2346
                        } else {
2347
                            echo '<div style="text-align: left;">' . get_lang("NoDataAvailable") . '</div>';
2348
                        }
2349
                        echo ' </td>';
2350
                        echo ' </tr>';
2351
                    }
2352
                }
2353
                // displaying the table: footer (totals)
2354
                echo '	<tr>';
2355
                echo '		<td class="total"><b>' . get_lang('Total') . '</b></td>';
2356
                echo '		<td class="total"><b>' . ($number_of_answers[$option['question_id']] == 0 ? '0' : $number_of_answers[$option['question_id']]) . '</b></td>';
2357
                echo '		<td class="total">&nbsp;</td>';
2358
                echo '		<td class="total">&nbsp;</td>';
2359
                echo '	</tr>';
2360
2361
                echo '</table>';
2362
2363
                echo '</div>';
2364
            }
2365
        }
2366
        if (isset($_GET['viewoption'])) {
2367
            echo '<div class="answered-people">';
2368
2369
            echo '<h4>'.get_lang('PeopleWhoAnswered').': '.strip_tags($options[Security::remove_XSS($_GET['viewoption'])]['option_text']).'</h4>';
2370
2371
            if (is_numeric($_GET['value'])) {
2372
                $sql_restriction = "AND value='".Database::escape_string($_GET['value'])."'";
2373
            }
2374
2375
            $sql = "SELECT user FROM $table_survey_answer
2376
                    WHERE
2377
                        c_id = $course_id AND
2378
                        option_id = '".Database::escape_string($_GET['viewoption'])."'
2379
                        $sql_restriction";
2380
            $result = Database::query($sql);
2381
            echo '<ul>';
2382 View Code Duplication
            while ($row = Database::fetch_array($result, 'ASSOC')) {
2383
                $user_info = api_get_user_info($row['user']);
2384
                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>';
2385
            }
2386
            echo '</ul>';
2387
            echo '</div>';
2388
        }
2389
    }
2390
2391
    /**
2392
     * Display score data about a survey question
2393
     * @param	array	Question info
2394
     * @param	integer	The offset of results shown
2395
     * @return	void 	(direct output)
2396
     */
2397
    public static function display_question_report_score($survey_data, $question, $offset)
2398
    {
2399
        // Database table definitions
2400
        $table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
2401
        $table_survey_answer 			= Database :: get_course_table(TABLE_SURVEY_ANSWER);
2402
2403
        $course_id = api_get_course_int_id();
2404
2405
        // Getting the options
2406
        $sql = "SELECT * FROM $table_survey_question_option
2407
                WHERE
2408
                    c_id = $course_id AND
2409
                    survey_id='".Database::escape_string($_GET['survey_id'])."' AND
2410
                    question_id = '".Database::escape_string($question['question_id'])."'
2411
                ORDER BY sort ASC";
2412
        $result = Database::query($sql);
2413
        while ($row = Database::fetch_array($result)) {
2414
            $options[$row['question_option_id']] = $row;
2415
        }
2416
2417
        // Getting the answers
2418
        $sql = "SELECT *, count(answer_id) as total FROM $table_survey_answer
2419
                WHERE
2420
                   c_id = $course_id AND
2421
                   survey_id='".Database::escape_string($_GET['survey_id'])."' AND
2422
                   question_id = '".Database::escape_string($question['question_id'])."'
2423
                GROUP BY option_id, value";
2424
        $result = Database::query($sql);
2425
        $number_of_answers = 0;
2426 View Code Duplication
        while ($row = Database::fetch_array($result)) {
2427
            $number_of_answers += $row['total'];
2428
            $data[$row['option_id']][$row['value']] = $row;
2429
        }
2430
2431
        $chartData = array();
2432
        foreach ($options as $option) {
2433
            $optionText = strip_tags($option['option_text']);
2434
            $optionText = html_entity_decode($optionText);
2435
            for ($i = 1; $i <= $question['max_value']; $i++) {
2436
                $votes = $data[$option['question_option_id']][$i]['total'];
2437
                if (empty($votes)) {
2438
                    $votes = '0';
2439
                }
2440
                array_push(
2441
                    $chartData,
2442
                    array(
2443
                        'serie' => $optionText,
2444
                        'option' => $i,
2445
                        'votes' => $votes
2446
                    )
2447
                );
2448
            }
2449
        }
2450
        echo '<div id="chartContainer" class="col-md-12">';
2451
        echo self::drawChart($chartData, true);
2452
        echo '</div>';
2453
2454
        // Displaying the table: headers
2455
        echo '<table class="data_table">';
2456
        echo '	<tr>';
2457
        echo '		<th>&nbsp;</th>';
2458
        echo '		<th>'.get_lang('Score').'</th>';
2459
        echo '		<th>'.get_lang('AbsoluteTotal').'</th>';
2460
        echo '		<th>'.get_lang('Percentage').'</th>';
2461
        echo '		<th>'.get_lang('VisualRepresentation').'</th>';
2462
        echo '	<tr>';
2463
        // Displaying the table: the content
2464
        foreach ($options as $key => & $value) {
2465
            for ($i = 1; $i <= $question['max_value']; $i++) {
2466
                $absolute_number = $data[$value['question_option_id']][$i]['total'];
2467
                echo '	<tr>';
2468
                echo '		<td>'.$value['option_text'].'</td>';
2469
                echo '		<td>'.$i.'</td>';
2470
                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...
2471
                echo '		<td>'.round($absolute_number/$number_of_answers*100, 2).' %</td>';
2472
                echo '		<td>';
2473
                $size = ($absolute_number/$number_of_answers*100*2);
2474
                if ($size > 0) {
2475
                    echo '			<div style="border:1px solid #264269; background-color:#aecaf4; height:10px; width:'.$size.'px">&nbsp;</div>';
2476
                }
2477
                echo '		</td>';
2478
                echo '	</tr>';
2479
            }
2480
        }
2481
        // Displaying the table: footer (totals)
2482
        echo '	<tr>';
2483
        echo '		<td style="border-top:1px solid black"><b>'.get_lang('Total').'</b></td>';
2484
        echo '		<td style="border-top:1px solid black">&nbsp;</td>';
2485
        echo '		<td style="border-top:1px solid black"><b>'.$number_of_answers.'</b></td>';
2486
        echo '		<td style="border-top:1px solid black">&nbsp;</td>';
2487
        echo '		<td style="border-top:1px solid black">&nbsp;</td>';
2488
        echo '	</tr>';
2489
2490
        echo '</table>';
2491
    }
2492
2493
    /**
2494
     * This functions displays the complete reporting
2495
     * @return	string	HTML code
2496
     * @todo open questions are not in the complete report yet.
2497
     * @author Patrick Cool <[email protected]>, Ghent University
2498
     * @version February 2007
2499
     */
2500
    public static function display_complete_report($survey_data)
2501
    {
2502
        // Database table definitions
2503
        $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
2504
        $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
2505
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
2506
2507
        $surveyId = isset($_GET['survey_id']) ? intval($_GET['survey_id']) : 0;
2508
        $action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : '';
2509
2510
        // Actions bar
2511
        echo '<div class="actions">';
2512
        echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.Security::remove_XSS($_GET['survey_id']).'">
2513
		'.Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('ReportingOverview'),'',ICON_SIZE_MEDIUM).'</a>';
2514
        echo '<a class="survey_export_link" href="javascript: void(0);" onclick="document.form1a.submit();">
2515
		'.Display::return_icon('export_csv.png',get_lang('ExportAsCSV'),'',ICON_SIZE_MEDIUM).'</a>';
2516
        echo '<a class="survey_export_link" href="javascript: void(0);" onclick="document.form1b.submit();">
2517
		'.Display::return_icon('export_excel.png',get_lang('ExportAsXLS'),'',ICON_SIZE_MEDIUM).'</a>';
2518
        echo '</div>';
2519
2520
        // The form
2521
        echo '<form id="form1a" name="form1a" method="post" action="'.api_get_self().'?action='.$action.'&survey_id='.$surveyId.'&'.api_get_cidreq().'">';
2522
        echo '<input type="hidden" name="export_report" value="export_report">';
2523
        echo '<input type="hidden" name="export_format" value="csv">';
2524
        echo '</form>';
2525
        echo '<form id="form1b" name="form1b" method="post" action="'.api_get_self().'?action='.$action.'&survey_id='.$surveyId.'&'.api_get_cidreq().'">';
2526
        echo '<input type="hidden" name="export_report" value="export_report">';
2527
        echo '<input type="hidden" name="export_format" value="xls">';
2528
        echo '</form>';
2529
2530
        echo '<form id="form2" name="form2" method="post" action="'.api_get_self().'?action='.$action.'&survey_id='.$surveyId.'&'.api_get_cidreq().'">';
2531
2532
        // The table
2533
        echo '<br /><table class="data_table" border="1">';
2534
        // Getting the number of options per question
2535
        echo '	<tr>';
2536
        echo '		<th>';
2537
        if (
2538
            (isset($_POST['submit_question_filter']) && $_POST['submit_question_filter']) ||
2539
            (isset($_POST['export_report']) && $_POST['export_report'])
2540
        ) {
2541
            echo '<button class="cancel" type="submit" name="reset_question_filter" value="'.get_lang('ResetQuestionFilter').'">'.get_lang('ResetQuestionFilter').'</button>';
2542
        }
2543
        echo '<button class="save" type="submit" name="submit_question_filter" value="'.get_lang('SubmitQuestionFilter').'">'.get_lang('SubmitQuestionFilter').'</button>';
2544
        echo '</th>';
2545
2546
        $display_extra_user_fields = false;
2547
        if (!(isset($_POST['submit_question_filter']) && $_POST['submit_question_filter'] ||
2548
                isset($_POST['export_report']) && $_POST['export_report']) || !empty($_POST['fields_filter'])) {
2549
            // Show user fields section with a big th colspan that spans over all fields
2550
            $extra_user_fields = UserManager::get_extra_fields(0, 0, 5, 'ASC', false, true);
2551
            $num = count($extra_user_fields);
2552
            if ($num > 0 ) {
2553
                echo '<th '.($num>0?' colspan="'.$num.'"':'').'>';
2554
                echo '<label><input type="checkbox" name="fields_filter" value="1" checked="checked"/> ';
2555
                echo get_lang('UserFields');
2556
                echo '</label>';
2557
                echo '</th>';
2558
                $display_extra_user_fields = true;
2559
            }
2560
        }
2561
2562
        $course_id = api_get_course_int_id();
2563
        $sql = "SELECT q.question_id, q.type, q.survey_question, count(o.question_option_id) as number_of_options
2564
				FROM $table_survey_question q 
2565
				LEFT JOIN $table_survey_question_option o
2566
				ON q.question_id = o.question_id
2567
				WHERE 
2568
				    q.survey_id = '".$surveyId."' AND
2569
				    q.c_id = $course_id AND
2570
				    o.c_id = $course_id
2571
				GROUP BY q.question_id
2572
				ORDER BY q.sort ASC";
2573
        $result = Database::query($sql);
2574
        $questions = [];
2575
        while ($row = Database::fetch_array($result)) {
2576
            // We show the questions if
2577
            // 1. there is no question filter and the export button has not been clicked
2578
            // 2. there is a quesiton filter but the question is selected for display
2579
            if (!(isset($_POST['submit_question_filter']) && $_POST['submit_question_filter']) ||
2580
                (is_array($_POST['questions_filter']) && in_array($row['question_id'], $_POST['questions_filter']))
2581
            ) {
2582
                // We do not show comment and pagebreak question types
2583
                if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
2584
                    echo ' <th';
2585
                    // <hub> modified tst to include percentage
2586
                    if ($row['number_of_options'] > 0 && $row['type'] != 'percentage') {
2587
                        // </hub>
2588
                        echo ' colspan="'.$row['number_of_options'].'"';
2589
                    }
2590
                    echo '>';
2591
2592
                    echo '<label><input type="checkbox" name="questions_filter[]" value="'.$row['question_id'].'" checked="checked"/> ';
2593
                    echo $row['survey_question'];
2594
                    echo '</label>';
2595
                    echo '</th>';
2596
                }
2597
                // No column at all if it's not a question
2598
            }
2599
            $questions[$row['question_id']] = $row;
2600
        }
2601
        echo '	</tr>';
2602
        // Getting all the questions and options
2603
        echo '	<tr>';
2604
        echo '		<th>&nbsp;</th>'; // the user column
2605
2606
        if (!(isset($_POST['submit_question_filter']) && $_POST['submit_question_filter'] ||
2607
                isset($_POST['export_report']) && $_POST['export_report']) || !empty($_POST['fields_filter'])) {
2608
            //show the fields names for user fields
2609
            foreach($extra_user_fields as & $field) {
2610
                echo '<th>'.$field[3].'</th>';
2611
            }
2612
        }
2613
2614
        // cells with option (none for open question)
2615
        $sql = "SELECT 	
2616
                    sq.question_id, sq.survey_id,
2617
                    sq.survey_question, sq.display,
2618
                    sq.sort, sq.type, sqo.question_option_id,
2619
                    sqo.option_text, sqo.sort as option_sort
2620
				FROM $table_survey_question sq
2621
				LEFT JOIN $table_survey_question_option sqo
2622
				ON sq.question_id = sqo.question_id
2623
				WHERE
2624
				    sq.survey_id = '".$surveyId."' AND
2625
                    sq.c_id = $course_id AND
2626
                    sqo.c_id = $course_id
2627
				ORDER BY sq.sort ASC, sqo.sort ASC";
2628
        $result = Database::query($sql);
2629
2630
        $display_percentage_header = 1;
2631
        $possible_answers = [];
2632
        // in order to display only once the cell option (and not 100 times)
2633
        while ($row = Database::fetch_array($result)) {
2634
            // We show the options if
2635
            // 1. there is no question filter and the export button has not been clicked
2636
            // 2. there is a question filter but the question is selected for display
2637
            //if (!($_POST['submit_question_filter'] || $_POST['export_report']) || in_array($row['question_id'], $_POST['questions_filter'])) {
2638
            if (!(isset($_POST['submit_question_filter']) && $_POST['submit_question_filter']) ||
2639
                (is_array($_POST['questions_filter']) && in_array($row['question_id'], $_POST['questions_filter']))
2640
            ) {
2641
                // <hub> modif 05-05-2010
2642
                // we do not show comment and pagebreak question types
2643
                if ($row['type'] == 'open') {
2644
                    echo '<th>&nbsp;-&nbsp;</th>';
2645
                    $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
2646
                    $display_percentage_header = 1;
2647
                } else if ($row['type'] == 'percentage' && $display_percentage_header) {
2648
                    echo '<th>&nbsp;%&nbsp;</th>';
2649
                    $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
2650
                    $display_percentage_header = 0;
2651
                } else if ($row['type'] == 'percentage') {
2652
                    $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
2653
                } else if ($row['type'] <> 'comment' && $row['type'] <> 'pagebreak' && $row['type'] <> 'percentage') {
2654
                    echo '<th>';
2655
                    echo $row['option_text'];
2656
                    echo '</th>';
2657
                    $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
2658
                    $display_percentage_header = 1;
2659
                }
2660
                //no column at all if the question was not a question
2661
                // </hub>
2662
            }
2663
        }
2664
2665
        echo '	</tr>';
2666
2667
        // Getting all the answers of the users
2668
        $old_user = '';
2669
        $answers_of_user = array();
2670
        $sql = "SELECT * FROM $table_survey_answer
2671
                WHERE
2672
                    c_id = $course_id AND
2673
                    survey_id='".$surveyId."'
2674
                ORDER BY answer_id, user ASC";
2675
        $result = Database::query($sql);
2676
        $i = 1;
2677
        while ($row = Database::fetch_array($result)) {
2678
            if ($old_user != $row['user'] && $old_user != '') {
2679
                $userParam = $old_user;
2680
                if ($survey_data['anonymous'] != 0) {
2681
                    $userParam = $i;
2682
                    $i++;
2683
                }
2684
                SurveyUtil::display_complete_report_row(
2685
                    $survey_data,
2686
                    $possible_answers,
2687
                    $answers_of_user,
2688
                    $userParam,
2689
                    $questions,
2690
                    $display_extra_user_fields
2691
                );
2692
                $answers_of_user=array();
2693
            }
2694
            if (isset($questions[$row['question_id']]) && $questions[$row['question_id']]['type'] != 'open') {
2695
                $answers_of_user[$row['question_id']][$row['option_id']] = $row;
2696
            } else {
2697
                $answers_of_user[$row['question_id']][0] = $row;
2698
            }
2699
            $old_user = $row['user'];
2700
        }
2701
        $userParam = $old_user;
2702
        if ($survey_data['anonymous'] != 0) {
2703
            $userParam = $i;
2704
            $i++;
2705
        }
2706
        SurveyUtil::display_complete_report_row(
2707
            $survey_data,
2708
            $possible_answers,
2709
            $answers_of_user,
2710
            $userParam,
2711
            $questions,
2712
            $display_extra_user_fields
2713
        );
2714
        // This is to display the last user
2715
        echo '</table>';
2716
        echo '</form>';
2717
    }
2718
2719
    /**
2720
     * This function displays a row (= a user and his/her answers) in the table of the complete report.
2721
     *
2722
     * @param array $survey_data
2723
     * @param 	array	Possible options
2724
     * @param 	array 	User answers
2725
     * @param	mixed	User ID or user details string
2726
     * @param	boolean	Whether to show extra user fields or not
2727
     * @author Patrick Cool <[email protected]>, Ghent University
2728
     * @version February 2007 - Updated March 2008
2729
     */
2730
    public static function display_complete_report_row(
2731
        $survey_data,
2732
        $possible_options,
2733
        $answers_of_user,
2734
        $user,
2735
        $questions,
2736
        $display_extra_user_fields = false
2737
    ) {
2738
        $user = Security::remove_XSS($user);
2739
        echo '<tr>';
2740
        if ($survey_data['anonymous'] == 0) {
2741
            if (intval($user) !== 0) {
2742
                $userInfo = api_get_user_info($user);
2743
                if (!empty($userInfo)) {
2744
                    $user_displayed = $userInfo['complete_name'];
2745
                } else {
2746
                    $user_displayed = '-';
2747
                }
2748
                echo '<th><a href="'.api_get_self().'?action=userreport&survey_id='.Security::remove_XSS($_GET['survey_id']).'&user='.$user.'">'.
2749
                    $user_displayed.'</a></th>'; // the user column
2750
            } else {
2751
                echo '<th>'.$user.'</th>'; // the user column
2752
            }
2753
        } else {
2754
            echo '<th>' . get_lang('Anonymous') . ' ' . $user . '</th>';
2755
        }
2756
2757
        if ($display_extra_user_fields) {
2758
            // Show user fields data, if any, for this user
2759
            $user_fields_values = UserManager::get_extra_user_data(intval($user), false, false, false, true);
2760
            foreach ($user_fields_values as & $value) {
2761
                echo '<td align="center">'.$value.'</td>';
2762
            }
2763
        }
2764
        if (is_array($possible_options)) {
2765
            // <hub> modified to display open answers and percentage
2766
            foreach ($possible_options as $question_id => & $possible_option) {
2767
                if ($questions[$question_id]['type'] == 'open') {
2768
                    echo '<td align="center">';
2769
                    echo $answers_of_user[$question_id]['0']['option_id'];
2770
                    echo '</td>';
2771
                } else {
2772
                    foreach ($possible_option as $option_id => & $value) {
2773
                        if ($questions[$question_id]['type'] == 'percentage') {
2774 View Code Duplication
                            if (!empty($answers_of_user[$question_id][$option_id])) {
2775
                                echo "<td align='center'>";
2776
                                echo $answers_of_user[$question_id][$option_id]['value'];
2777
                                echo "</td>";
2778
                            }
2779
                        }
2780
                        else {
2781
                            echo '<td align="center">';
2782
                            if (!empty($answers_of_user[$question_id][$option_id])) {
2783 View Code Duplication
                                if ($answers_of_user[$question_id][$option_id]['value'] != 0) {
2784
                                    echo $answers_of_user[$question_id][$option_id]['value'];
2785
                                }
2786
                                else {
2787
                                    echo 'v';
2788
                                }
2789
                            }
2790
                        } // </hub>
2791
                    }
2792
                }
2793
            }
2794
        }
2795
        echo '</tr>';
2796
    }
2797
2798
    /**
2799
     * Quite similar to display_complete_report(), returns an HTML string
2800
     * that can be used in a csv file
2801
     * @todo consider merging this function with display_complete_report
2802
     * @return	string	The contents of a csv file
2803
     * @author Patrick Cool <[email protected]>, Ghent University
2804
     * @version February 2007
2805
     */
2806
    public static function export_complete_report($survey_data, $user_id = 0)
2807
    {
2808
        // Database table definitions
2809
        $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
2810
        $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
2811
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
2812
2813
        // The first column
2814
        $return = ';';
2815
2816
        // Show extra fields blank space (enough for extra fields on next line)
2817
        $extra_user_fields = UserManager::get_extra_fields(0, 0, 5, 'ASC', false, true);
2818
2819
        $num = count($extra_user_fields);
2820
        $return .= str_repeat(';', $num);
2821
2822
        $course_id = api_get_course_int_id();
2823
2824
        $sql = "SELECT
2825
                    questions.question_id,
2826
                    questions.type,
2827
                    questions.survey_question,
2828
                    count(options.question_option_id) as number_of_options
2829
				FROM $table_survey_question questions
2830
                LEFT JOIN $table_survey_question_option options
2831
				ON questions.question_id = options.question_id  AND options.c_id = $course_id
2832
				WHERE
2833
				    questions.survey_id = '".intval($_GET['survey_id'])."' AND
2834
                    questions.c_id = $course_id
2835
				GROUP BY questions.question_id
2836
				ORDER BY questions.sort ASC";
2837
        $result = Database::query($sql);
2838
        while ($row = Database::fetch_array($result)) {
2839
            // We show the questions if
2840
            // 1. there is no question filter and the export button has not been clicked
2841
            // 2. there is a quesiton filter but the question is selected for display
2842
            if (!(isset($_POST['submit_question_filter'])) ||
2843
                (isset($_POST['submit_question_filter']) &&
2844
                    is_array($_POST['questions_filter']) &&
2845
                    in_array($row['question_id'], $_POST['questions_filter']))
2846
            ) {
2847
                // We do not show comment and pagebreak question types
2848
                if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
2849
                    if ($row['number_of_options'] == 0 && $row['type'] == 'open') {
2850
                        $return .= str_replace("\r\n",'  ', api_html_entity_decode(strip_tags($row['survey_question']), ENT_QUOTES)).';';
2851
                    } else {
2852
                        for ($ii = 0; $ii < $row['number_of_options']; $ii++) {
2853
                            $return .= str_replace("\r\n",'  ', api_html_entity_decode(strip_tags($row['survey_question']), ENT_QUOTES)).';';
2854
                        }
2855
                    }
2856
                }
2857
            }
2858
        }
2859
        $return .= "\n";
2860
2861
        // Getting all the questions and options
2862
        $return .= ';';
2863
2864
        // Show the fields names for user fields
2865
        if (!empty($extra_user_fields)) {
2866
            foreach ($extra_user_fields as & $field) {
2867
                $return .= '"'.str_replace("\r\n",'  ',api_html_entity_decode(strip_tags($field[3]), ENT_QUOTES)).'";';
2868
            }
2869
        }
2870
2871
        $sql = "SELECT
2872
		            survey_question.question_id,
2873
		            survey_question.survey_id,
2874
		            survey_question.survey_question,
2875
		            survey_question.display,
2876
		            survey_question.sort,
2877
		            survey_question.type,
2878
                    survey_question_option.question_option_id,
2879
                    survey_question_option.option_text,
2880
                    survey_question_option.sort as option_sort
2881
				FROM $table_survey_question survey_question
2882
				LEFT JOIN $table_survey_question_option survey_question_option
2883
				ON
2884
				    survey_question.question_id = survey_question_option.question_id AND
2885
				    survey_question_option.c_id = $course_id
2886
				WHERE
2887
				    survey_question.survey_id = '".intval($_GET['survey_id'])."' AND
2888
				    survey_question.c_id = $course_id
2889
				ORDER BY survey_question.sort ASC, survey_question_option.sort ASC";
2890
        $result = Database::query($sql);
2891
        $possible_answers = array();
2892
        $possible_answers_type = array();
2893
        while ($row = Database::fetch_array($result)) {
2894
            // We show the options if
2895
            // 1. there is no question filter and the export button has not been clicked
2896
            // 2. there is a quesiton filter but the question is selected for display
2897
            if (!(isset($_POST['submit_question_filter'])) || (
2898
                is_array($_POST['questions_filter']) &&
2899
                in_array($row['question_id'], $_POST['questions_filter']))
2900
            ) {
2901
                // We do not show comment and pagebreak question types
2902
                if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
2903
                    $row['option_text'] = str_replace(array("\r","\n"),array('',''),$row['option_text']);
2904
                    $return .= api_html_entity_decode(strip_tags($row['option_text']), ENT_QUOTES).';';
2905
                    $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
2906
                    $possible_answers_type[$row['question_id']] = $row['type'];
2907
                }
2908
            }
2909
        }
2910
        $return .= "\n";
2911
2912
        // Getting all the answers of the users
2913
        $old_user = '';
2914
        $answers_of_user = array();
2915
        $sql = "SELECT * FROM $table_survey_answer
2916
		        WHERE c_id = $course_id AND survey_id='".Database::escape_string($_GET['survey_id'])."'";
2917
        if ($user_id != 0) {
2918
            $sql .= "AND user='".Database::escape_string($user_id)."' ";
2919
        }
2920
        $sql .= "ORDER BY user ASC";
2921
2922
        $open_question_iterator = 1;
2923
        $result = Database::query($sql);
2924
        while ($row = Database::fetch_array($result)) {
2925
            if ($old_user != $row['user'] && $old_user != '') {
2926
                $return .= SurveyUtil::export_complete_report_row(
2927
                    $survey_data,
2928
                    $possible_answers,
2929
                    $answers_of_user,
2930
                    $old_user,
2931
                    true
2932
                );
2933
                $answers_of_user=array();
2934
            }
2935 View Code Duplication
            if($possible_answers_type[$row['question_id']] == 'open') {
2936
                $temp_id = 'open'.$open_question_iterator;
2937
                $answers_of_user[$row['question_id']][$temp_id] = $row;
2938
                $open_question_iterator++;
2939
            } else {
2940
                $answers_of_user[$row['question_id']][$row['option_id']] = $row;
2941
            }
2942
            $old_user = $row['user'];
2943
        }
2944
        // This is to display the last user
2945
        $return .= SurveyUtil::export_complete_report_row(
2946
            $survey_data,
2947
            $possible_answers,
2948
            $answers_of_user,
2949
            $old_user,
2950
            true
2951
        );
2952
2953
        return $return;
2954
    }
2955
2956
    /**
2957
     * Add a line to the csv file
2958
     *
2959
     * @param	array	Possible answers
2960
     * @param	array	User's answers
2961
     * @param 	mixed	User ID or user details as string - Used as a string in the result string
2962
     * @param	boolean	Whether to display user fields or not
2963
     * @return	string	One line of the csv file
2964
     * @author Patrick Cool <[email protected]>, Ghent University
2965
     * @version February 2007
2966
     */
2967
    public static function export_complete_report_row(
2968
        $survey_data,
2969
        $possible_options,
2970
        $answers_of_user,
2971
        $user,
2972
        $display_extra_user_fields = false
2973
    ) {
2974
        $return = '';
2975
        if ($survey_data['anonymous'] == 0) {
2976
            if (intval($user) !== 0) {
2977
                $userInfo = api_get_user_info($user);
2978
2979
                if (!empty($userInfo)) {
2980
                    $user_displayed = $userInfo['complete_name'];
2981
                } else {
2982
                    $user_displayed = '-';
2983
                }
2984
                $return .= $user_displayed.';';
2985
            } else {
2986
                $return .= $user.';';
2987
            }
2988
        } else {
2989
            $return .= '-;'; // The user column
2990
        }
2991
2992 View Code Duplication
        if ($display_extra_user_fields) {
2993
            // Show user fields data, if any, for this user
2994
            $user_fields_values = UserManager::get_extra_user_data($user,false,false, false, true);
2995
            foreach ($user_fields_values as & $value) {
2996
                $return .= '"'.str_replace('"', '""', api_html_entity_decode(strip_tags($value), ENT_QUOTES)).'";';
2997
            }
2998
        }
2999
3000
        if (is_array($possible_options)) {
3001
            foreach ($possible_options as $question_id => $possible_option) {
3002
                if (is_array($possible_option) && count($possible_option) > 0) {
3003
                    foreach ($possible_option as $option_id => & $value) {
3004
                        $my_answer_of_user = !isset($answers_of_user[$question_id]) || isset($answers_of_user[$question_id]) && $answers_of_user[$question_id] == null ? array() : $answers_of_user[$question_id];
3005
                        $key = array_keys($my_answer_of_user);
3006
                        if (isset($key[0]) && substr($key[0], 0, 4) == 'open') {
3007
                            $return .= '"'.
3008
                                str_replace(
3009
                                    '"',
3010
                                    '""',
3011
                                    api_html_entity_decode(strip_tags($answers_of_user[$question_id][$key[0]]['option_id']), ENT_QUOTES)
3012
                                ).
3013
                                '"';
3014
                        } elseif (!empty($answers_of_user[$question_id][$option_id])) {
3015
                            //$return .= 'v';
3016
                            if ($answers_of_user[$question_id][$option_id]['value'] != 0) {
3017
                                $return .= $answers_of_user[$question_id][$option_id]['value'];
3018
                            } else {
3019
                                $return .= 'v';
3020
                            }
3021
                        }
3022
                        $return .= ';';
3023
                    }
3024
                }
3025
            }
3026
        }
3027
        $return .= "\n";
3028
        return $return;
3029
    }
3030
3031
    /**
3032
     * Quite similar to display_complete_report(), returns an HTML string
3033
     * that can be used in a csv file
3034
     * @todo consider merging this function with display_complete_report
3035
     * @return	string	The contents of a csv file
3036
     * @author Patrick Cool <[email protected]>, Ghent University
3037
     * @version February 2007
3038
     */
3039
    public static function export_complete_report_xls($survey_data, $filename, $user_id = 0)
3040
    {
3041
        $course_id = api_get_course_int_id();
3042
        $surveyId = isset($_GET['survey_id']) ? (int) $_GET['survey_id'] : 0;
3043
3044
        if (empty($course_id) || empty($surveyId)) {
3045
3046
            return false;
3047
        }
3048
3049
        $spreadsheet = new PHPExcel();
3050
        $spreadsheet->setActiveSheetIndex(0);
3051
        $worksheet = $spreadsheet->getActiveSheet();
3052
        $line = 1;
3053
        $column = 1; // Skip the first column (row titles)
3054
3055
        // Show extra fields blank space (enough for extra fields on next line)
3056
        // Show user fields section with a big th colspan that spans over all fields
3057
        $extra_user_fields = UserManager::get_extra_fields(0, 0, 5, 'ASC', false, true);
3058
        $num = count($extra_user_fields);
3059
        for ($i = 0; $i < $num; $i++) {
3060
            $worksheet->setCellValueByColumnAndRow($column, $line, '');
3061
            $column++;
3062
        }
3063
3064
        $display_extra_user_fields = true;
3065
3066
        // Database table definitions
3067
        $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
3068
        $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
3069
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
3070
3071
        // First line (questions)
3072
        $sql = "SELECT
3073
                    questions.question_id,
3074
                    questions.type,
3075
                    questions.survey_question,
3076
                    count(options.question_option_id) as number_of_options
3077
				FROM $table_survey_question questions
3078
				LEFT JOIN $table_survey_question_option options
3079
                ON questions.question_id = options.question_id AND options.c_id = $course_id
3080
				WHERE
3081
				    questions.survey_id = $surveyId AND
3082
				    questions.c_id = $course_id
3083
				GROUP BY questions.question_id
3084
				ORDER BY questions.sort ASC";
3085
        $result = Database::query($sql);
3086
        while ($row = Database::fetch_array($result)) {
3087
            // We show the questions if
3088
            // 1. there is no question filter and the export button has not been clicked
3089
            // 2. there is a quesiton filter but the question is selected for display
3090
            if (!(isset($_POST['submit_question_filter'])) ||
3091
                (isset($_POST['submit_question_filter']) && is_array($_POST['questions_filter']) &&
3092
                in_array($row['question_id'], $_POST['questions_filter']))
3093
            ) {
3094
                // We do not show comment and pagebreak question types
3095
                if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
3096
                    if ($row['number_of_options'] == 0 && $row['type'] == 'open') {
3097
                        $worksheet->setCellValueByColumnAndRow(
3098
                            $column,
3099
                            $line,
3100
                            api_html_entity_decode(
3101
                                strip_tags($row['survey_question']),
3102
                                ENT_QUOTES
3103
                            )
3104
                        );
3105
                        $column++;
3106
                    } else {
3107
                        for ($ii = 0; $ii < $row['number_of_options']; $ii ++) {
3108
                            $worksheet->setCellValueByColumnAndRow(
3109
                                $column,
3110
                                $line,
3111
                                api_html_entity_decode(
3112
                                    strip_tags($row['survey_question']),
3113
                                    ENT_QUOTES
3114
                                )
3115
                            );
3116
                            $column++;
3117
                        }
3118
                    }
3119
                }
3120
            }
3121
        }
3122
3123
        $line++;
3124
        $column = 1;
3125
3126
        // Show extra field values
3127
        if ($display_extra_user_fields) {
3128
            // Show the fields names for user fields
3129
            foreach ($extra_user_fields as & $field) {
3130
                $worksheet->setCellValueByColumnAndRow(
3131
                    $column,
3132
                    $line,
3133
                    api_html_entity_decode(strip_tags($field[3]), ENT_QUOTES)
3134
                );
3135
                $column++;
3136
            }
3137
        }
3138
3139
        // Getting all the questions and options (second line)
3140
        $sql = "SELECT
3141
                    survey_question.question_id, 
3142
                    survey_question.survey_id, 
3143
                    survey_question.survey_question, 
3144
                    survey_question.display, 
3145
                    survey_question.sort, 
3146
                    survey_question.type,
3147
                    survey_question_option.question_option_id, 
3148
                    survey_question_option.option_text, 
3149
                    survey_question_option.sort as option_sort
3150
				FROM $table_survey_question survey_question
3151
				LEFT JOIN $table_survey_question_option survey_question_option
3152
				ON 
3153
				    survey_question.question_id = survey_question_option.question_id AND 
3154
				    survey_question_option.c_id = $course_id
3155
				WHERE 
3156
				    survey_question.survey_id = $surveyId AND
3157
				    survey_question.c_id = $course_id
3158
				ORDER BY survey_question.sort ASC, survey_question_option.sort ASC";
3159
        $result = Database::query($sql);
3160
        $possible_answers = array();
3161
        $possible_answers_type = array();
3162
        while ($row = Database::fetch_array($result)) {
3163
            // We show the options if
3164
            // 1. there is no question filter and the export button has not been clicked
3165
            // 2. there is a quesiton filter but the question is selected for display
3166
            if (!isset($_POST['submit_question_filter']) ||
3167
                (isset($_POST['questions_filter']) && is_array($_POST['questions_filter']) &&
3168
                in_array($row['question_id'], $_POST['questions_filter']))
3169
            ) {
3170
                // We do not show comment and pagebreak question types
3171
                if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
3172
                    $worksheet->setCellValueByColumnAndRow(
3173
                        $column,
3174
                        $line,
3175
                        api_html_entity_decode(
3176
                            strip_tags($row['option_text']),
3177
                            ENT_QUOTES
3178
                        )
3179
                    );
3180
                    $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
3181
                    $possible_answers_type[$row['question_id']] = $row['type'];
3182
                    $column++;
3183
                }
3184
            }
3185
        }
3186
3187
        // Getting all the answers of the users
3188
        $line ++;
3189
        $column = 0;
3190
        $old_user = '';
3191
        $answers_of_user = array();
3192
        $sql = "SELECT * FROM $table_survey_answer
3193
                WHERE c_id = $course_id AND survey_id = $surveyId";
3194
        if ($user_id != 0) {
3195
            $sql .= " AND user='".intval($user_id)."' ";
3196
        }
3197
        $sql .=	" ORDER BY user ASC";
3198
3199
        $open_question_iterator = 1;
3200
        $result = Database::query($sql);
3201
        while ($row = Database::fetch_array($result)) {
3202
            if ($old_user != $row['user'] && $old_user != '') {
3203
                $return = SurveyUtil::export_complete_report_row_xls(
3204
                    $survey_data,
3205
                    $possible_answers,
3206
                    $answers_of_user,
3207
                    $old_user,
3208
                    true
3209
                );
3210
                foreach ($return as $elem) {
3211
                    $worksheet->setCellValueByColumnAndRow($column, $line, $elem);
3212
                    $column++;
3213
                }
3214
                $answers_of_user = array();
3215
                $line++;
3216
                $column = 0;
3217
            }
3218 View Code Duplication
            if ($possible_answers_type[$row['question_id']] == 'open') {
3219
                $temp_id = 'open'.$open_question_iterator;
3220
                $answers_of_user[$row['question_id']][$temp_id] = $row;
3221
                $open_question_iterator++;
3222
            } else {
3223
                $answers_of_user[$row['question_id']][$row['option_id']] = $row;
3224
            }
3225
            $old_user = $row['user'];
3226
        }
3227
3228
        $return = SurveyUtil::export_complete_report_row_xls(
3229
            $survey_data,
3230
            $possible_answers,
3231
            $answers_of_user,
3232
            $old_user,
3233
            true
3234
        );
3235
3236
        // this is to display the last user
3237
        foreach ($return as $elem) {
3238
            $worksheet->setCellValueByColumnAndRow($column, $line, $elem);
3239
            $column++;
3240
        }
3241
3242
        $file = api_get_path(SYS_ARCHIVE_PATH).api_replace_dangerous_char($filename);
3243
        $writer = new PHPExcel_Writer_Excel2007($spreadsheet);
3244
        $writer->save($file);
3245
        DocumentManager::file_send_for_download($file, true, $filename);
3246
3247
        return null;
3248
    }
3249
3250
    /**
3251
     * Add a line to the csv file
3252
     *
3253
     * @param	array	Possible answers
3254
     * @param	array	User's answers
3255
     * @param 	mixed	User ID or user details as string - Used as a string in the result string
3256
     * @param	boolean	Whether to display user fields or not
3257
     * @return	string	One line of the csv file
3258
     */
3259
    public static function export_complete_report_row_xls(
3260
        $survey_data,
3261
        $possible_options,
3262
        $answers_of_user,
3263
        $user,
3264
        $display_extra_user_fields = false
3265
    ) {
3266
        $return = array();
3267
        if ($survey_data['anonymous'] == 0) {
3268
            if (intval($user) !== 0) {
3269
                $sql = 'SELECT firstname, lastname
3270
                        FROM '.Database::get_main_table(TABLE_MAIN_USER).'
3271
                        WHERE user_id='.intval($user);
3272
                $rs = Database::query($sql);
3273
                if($row = Database::fetch_array($rs)) {
3274
                    $user_displayed = api_get_person_name($row['firstname'], $row['lastname']);
3275
                } else {
3276
                    $user_displayed = '-';
3277
                }
3278
                $return[] = $user_displayed;
3279
            } else {
3280
                $return[] = $user;
3281
            }
3282
        } else {
3283
            $return[] = '-'; // The user column
3284
        }
3285
3286
        if ($display_extra_user_fields) {
3287
            //show user fields data, if any, for this user
3288
            $user_fields_values = UserManager::get_extra_user_data(intval($user),false,false, false, true);
3289
            foreach ($user_fields_values as $value) {
3290
                $return[] = api_html_entity_decode(strip_tags($value), ENT_QUOTES);
3291
            }
3292
        }
3293
3294
        if (is_array($possible_options)) {
3295
            foreach ($possible_options as $question_id => & $possible_option) {
3296
                if (is_array($possible_option) && count($possible_option) > 0) {
3297
                    foreach ($possible_option as $option_id => & $value) {
3298
                        $my_answers_of_user = isset($answers_of_user[$question_id]) ? $answers_of_user[$question_id] : [];
3299
                        $key = array_keys($my_answers_of_user);
3300
                        if (isset($key[0]) && substr($key[0], 0, 4) == 'open') {
3301
                            $return[] = api_html_entity_decode(strip_tags($answers_of_user[$question_id][$key[0]]['option_id']), ENT_QUOTES);
3302
                        } elseif (!empty($answers_of_user[$question_id][$option_id])) {
3303
                            if ($answers_of_user[$question_id][$option_id]['value'] != 0) {
3304
                                $return[] = $answers_of_user[$question_id][$option_id]['value'];
3305
                            } else {
3306
                                $return[] = 'v';
3307
                            }
3308
                        } else {
3309
                            $return[] = '';
3310
                        }
3311
                    }
3312
                }
3313
            }
3314
        }
3315
3316
        return $return;
3317
    }
3318
3319
    /**
3320
     * This function displays the comparative report which allows you to compare two questions
3321
     * A comparative report creates a table where one question is on the x axis and a second question is on the y axis.
3322
     * In the intersection is the number of people who have answerd positive on both options.
3323
     *
3324
     * @return	string	HTML code
3325
     *
3326
     * @author Patrick Cool <[email protected]>, Ghent University
3327
     * @version February 2007
3328
     */
3329
    public static function display_comparative_report()
3330
    {
3331
        // Allowed question types for comparative report
3332
        $allowed_question_types = array(
3333
            'yesno',
3334
            'multiplechoice',
3335
            'multipleresponse',
3336
            'dropdown',
3337
            'percentage',
3338
            'score'
3339
        );
3340
3341
        $surveyId = isset($_GET['survey_id']) ? (int) $_GET['survey_id'] : 0;
3342
3343
        // Getting all the questions
3344
        $questions = SurveyManager::get_questions($surveyId);
3345
3346
        // Actions bar
3347
        echo '<div class="actions">';
3348
        echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.$surveyId.'&'.api_get_cidreq().'">'.
3349
                Display::return_icon('back.png', get_lang('BackTo').' '.get_lang('ReportingOverview'),'',ICON_SIZE_MEDIUM).'</a>';
3350
        echo '</div>';
3351
3352
        // Displaying an information message that only the questions with predefined answers can be used in a comparative report
3353
        Display::display_normal_message(get_lang('OnlyQuestionsWithPredefinedAnswers'), false);
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_normal_message() has been deprecated with message: use Display::addFlash with Display::return_message($message, 'normal');

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
3354
3355
        $xAxis = isset($_GET['xaxis']) ? Security::remove_XSS($_GET['xaxis']) : '';
3356
        $yAxis = isset($_GET['yaxis']) ? Security::remove_XSS($_GET['yaxis']) : '';
3357
3358
        $url = api_get_self().'?'.api_get_cidreq().'&action='.Security::remove_XSS($_GET['action']).'&survey_id='.$surveyId.'&xaxis='.$xAxis.'&y='.$yAxis;
3359
3360
        $form = new FormValidator('compare', 'get', $url);
3361
        $form->addHidden('action', Security::remove_XSS($_GET['action']));
3362
        $form->addHidden('survey_id', $surveyId);
3363
        $optionsX = ['----'];
3364
        $optionsY = ['----'];
3365
        $defaults = [];
3366
        foreach ($questions as $key => & $question) {
3367
            if (is_array($allowed_question_types)) {
3368
                if (in_array($question['type'], $allowed_question_types)) {
3369
                    //echo '<option value="'.$question['question_id'].'"';
3370
                    if (isset($_GET['xaxis']) && $_GET['xaxis'] == $question['question_id']) {
3371
                        $defaults['xaxis'] = $question['question_id'];
3372
                    }
3373
3374
                    if (isset($_GET['yaxis']) && $_GET['yaxis'] == $question['question_id']) {
3375
                        $defaults['yaxis'] = $question['question_id'];
3376
                    }
3377
3378
                    $optionsX[$question['question_id']] = api_substr(strip_tags($question['question']), 0, 50);
3379
                    $optionsY[$question['question_id']] = api_substr(strip_tags($question['question']), 0, 50);
3380
                }
3381
            }
3382
        }
3383
3384
        $form->addSelect('xaxis', get_lang('SelectXAxis'), $optionsX);
3385
        $form->addSelect('yaxis', get_lang('SelectYAxis'), $optionsY);
3386
3387
        $form->addButtonSearch(get_lang('CompareQuestions'));
3388
        $form->setDefaults($defaults);
3389
        $form->display();
3390
3391
        // Getting all the information of the x axis
3392
        if (is_numeric($xAxis)) {
3393
            $question_x = SurveyManager::get_question($xAxis);
3394
        }
3395
3396
        // Getting all the information of the y axis
3397
        if (is_numeric($yAxis)) {
3398
            $question_y = SurveyManager::get_question($yAxis);
3399
        }
3400
3401
        if (is_numeric($xAxis) && is_numeric($yAxis)) {
3402
            // Getting the answers of the two questions
3403
            $answers_x = SurveyUtil::get_answers_of_question_by_user($surveyId, $xAxis);
3404
            $answers_y = SurveyUtil::get_answers_of_question_by_user($surveyId, $yAxis);
3405
3406
            // Displaying the table
3407
            $tableHtml = '<table border="1" class="data_table">';
3408
3409
            $xOptions = array();
3410
            // The header
3411
            $tableHtml .= '<tr>';
3412
            for ($ii = 0; $ii <= count($question_x['answers']); $ii++) {
3413
                if ($ii == 0) {
3414
                    $tableHtml .=  '<th>&nbsp;</th>';
3415
                } else {
3416
                    if ($question_x['type'] == 'score') {
3417
                        for ($x = 1; $x <= $question_x['maximum_score']; $x++) {
3418
                            $tableHtml .= '<th>'.$question_x['answers'][($ii-1)].'<br />'.$x.'</th>';
3419
                        }
3420
                        $x = '';
3421
                    } else {
3422
                        $tableHtml .= '<th>'.$question_x['answers'][($ii-1)].'</th>';
3423
                    }
3424
                    $optionText = strip_tags($question_x['answers'][$ii-1]);
3425
                    $optionText = html_entity_decode($optionText);
3426
                    array_push($xOptions, trim($optionText));
3427
                }
3428
            }
3429
            $tableHtml .= '</tr>';
3430
            $chartData = array();
3431
3432
            // The main part
3433
            for ($ij = 0; $ij < count($question_y['answers']); $ij++) {
3434
                $currentYQuestion = strip_tags($question_y['answers'][$ij]);
3435
                $currentYQuestion = html_entity_decode($currentYQuestion);
3436
                // The Y axis is a scoring question type so we have more rows than the options (actually options * maximum score)
3437
                if ($question_y['type'] == 'score') {
3438
                    for ($y = 1; $y <= $question_y['maximum_score']; $y++) {
3439
                        $tableHtml .=  '<tr>';
3440
                        for ($ii = 0; $ii <= count($question_x['answers']); $ii++) {
3441
                            if ($question_x['type'] == 'score') {
3442 View Code Duplication
                                for ($x = 1; $x <= $question_x['maximum_score']; $x++) {
3443
                                    if ($ii == 0) {
3444
                                        $tableHtml .=  '<th>'.$question_y['answers'][($ij)].' '.$y.'</th>';
3445
                                        break;
3446
                                    } else {
3447
                                        $tableHtml .=  '<td align="center">';
3448
                                        $votes = SurveyUtil::comparative_check(
3449
                                            $answers_x,
3450
                                            $answers_y,
3451
                                            $question_x['answersid'][($ii - 1)],
3452
                                            $question_y['answersid'][($ij)],
3453
                                            $x,
3454
                                            $y
3455
                                        );
3456
                                        $tableHtml .=  $votes;
3457
                                        array_push(
3458
                                            $chartData,
3459
                                            array(
3460
                                                'serie' => array($currentYQuestion, $xOptions[$ii-1]),
3461
                                                'option' => $x,
3462
                                                'votes' => $votes
3463
                                            )
3464
                                        );
3465
                                        $tableHtml .=  '</td>';
3466
                                    }
3467
                                }
3468
                            } else {
3469
                                if ($ii == 0) {
3470
                                    $tableHtml .= '<th>'.$question_y['answers'][$ij].' '.$y.'</th>';
3471
                                } else {
3472
                                    $tableHtml .= '<td align="center">';
3473
                                    $votes = SurveyUtil::comparative_check(
3474
                                        $answers_x,
3475
                                        $answers_y,
3476
                                        $question_x['answersid'][($ii - 1)],
3477
                                        $question_y['answersid'][($ij)],
3478
                                        0,
3479
                                        $y
3480
                                    );
3481
                                    $tableHtml .= $votes;
3482
                                    array_push(
3483
                                        $chartData,
3484
                                        array(
3485
                                            'serie' => array($currentYQuestion, $xOptions[$ii-1]),
3486
                                            'option' => $y,
3487
                                            'votes' => $votes
3488
                                        )
3489
                                    );
3490
                                    $tableHtml .=  '</td>';
3491
                                }
3492
                            }
3493
                        }
3494
                        $tableHtml .=  '</tr>';
3495
                    }
3496
                }
3497
                // The Y axis is NOT a score question type so the number of rows = the number of options
3498
                else {
3499
                    $tableHtml .=  '<tr>';
3500
                    for ($ii = 0; $ii <= count($question_x['answers']); $ii++) {
3501
                        if ($question_x['type'] == 'score') {
3502 View Code Duplication
                            for ($x = 1; $x <= $question_x['maximum_score']; $x++) {
3503
                                if ($ii == 0) {
3504
                                    $tableHtml .=  '<th>'.$question_y['answers'][$ij].'</th>';
3505
                                    break;
3506
                                } else {
3507
                                    $tableHtml .=  '<td align="center">';
3508
                                    $votes =  SurveyUtil::comparative_check(
3509
                                        $answers_x,
3510
                                        $answers_y,
3511
                                        $question_x['answersid'][($ii-1)],
3512
                                        $question_y['answersid'][($ij)],
3513
                                        $x,
3514
                                        0
3515
                                    );
3516
                                    $tableHtml .= $votes;
3517
                                    array_push(
3518
                                        $chartData,
3519
                                        array(
3520
                                            'serie' => array($currentYQuestion, $xOptions[$ii-1]),
3521
                                            'option' => $x,
3522
                                            'votes' => $votes
3523
                                        )
3524
                                    );
3525
                                    $tableHtml .=  '</td>';
3526
                                }
3527
                            }
3528
                        } else {
3529
                            if ($ii == 0) {
3530
                                $tableHtml .=  '<th>'.$question_y['answers'][($ij)].'</th>';
3531
                            } else {
3532
                                $tableHtml .=  '<td align="center">';
3533
                                $votes = SurveyUtil::comparative_check($answers_x, $answers_y, $question_x['answersid'][($ii-1)], $question_y['answersid'][($ij)]);
3534
                                $tableHtml .= $votes;
3535
                                array_push(
3536
                                    $chartData,
3537
                                    array(
3538
                                        'serie' => $xOptions[$ii-1],
3539
                                        'option' => $currentYQuestion,
3540
                                        'votes' => $votes
3541
                                    )
3542
                                );
3543
                                $tableHtml .= '</td>';
3544
                            }
3545
                        }
3546
                    }
3547
                    $tableHtml .= '</tr>';
3548
                }
3549
            }
3550
            $tableHtml .=  '</table>';
3551
            echo '<div id="chartContainer" class="col-md-12">';
3552
            echo self::drawChart($chartData, true);
3553
            echo '</div>';
3554
            echo $tableHtml;
3555
        }
3556
    }
3557
3558
    /**
3559
     * Get all the answers of a question grouped by user
3560
     *
3561
     * @param	integer	Survey ID
3562
     * @param	integer	Question ID
3563
     * @return 	Array	Array containing all answers of all users, grouped by user
3564
     *
3565
     * @author Patrick Cool <[email protected]>, Ghent University
3566
     * @version February 2007 - Updated March 2008
3567
     */
3568
    public static function get_answers_of_question_by_user($survey_id, $question_id)
3569
    {
3570
        $course_id = api_get_course_int_id();
3571
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
3572
3573
        $sql = "SELECT * FROM $table_survey_answer
3574
                WHERE c_id = $course_id AND survey_id='".intval($survey_id)."'
3575
                AND question_id='".intval($question_id)."'
3576
                ORDER BY USER ASC";
3577
        $result = Database::query($sql);
3578
        $return = [];
3579
        while ($row = Database::fetch_array($result)) {
3580
            if ($row['value'] == 0) {
3581
                $return[$row['user']][] = $row['option_id'];
3582
            } else {
3583
                $return[$row['user']][] = $row['option_id'].'*'.$row['value'];
3584
            }
3585
        }
3586
3587
        return $return;
3588
    }
3589
3590
    /**
3591
     * Count the number of users who answer positively on both options
3592
     *
3593
     * @param	array	All answers of the x axis
3594
     * @param	array	All answers of the y axis
3595
     * @param	integer x axis value (= the option_id of the first question)
3596
     * @param	integer y axis value (= the option_id of the second question)
3597
     * @return	integer Number of users who have answered positively to both options
3598
     *
3599
     * @author Patrick Cool <[email protected]>, Ghent University
3600
     * @version February 2007
3601
     */
3602
    public static function comparative_check($answers_x, $answers_y, $option_x, $option_y, $value_x = 0, $value_y = 0)
3603
    {
3604
        if ($value_x == 0) {
3605
            $check_x = $option_x;
3606
        } else {
3607
            $check_x = $option_x.'*'.$value_x;
3608
        }
3609
        if ($value_y == 0) {
3610
            $check_y = $option_y;
3611
        } else {
3612
            $check_y = $option_y.'*'.$value_y;
3613
        }
3614
3615
        $counter = 0;
3616
        if (is_array($answers_x)) {
3617
            foreach ($answers_x as $user => & $answers) {
3618
                // Check if the user has given $option_x as answer
3619
                if (in_array($check_x, $answers)) {
3620
                    // Check if the user has given $option_y as an answer
3621
                    if (!is_null($answers_y[$user]) && in_array($check_y, $answers_y[$user])) {
3622
                        $counter++;
3623
                    }
3624
                }
3625
            }
3626
        }
3627
3628
        return $counter;
3629
    }
3630
3631
    /**
3632
     * Get all the information about the invitations of a certain survey
3633
     *
3634
     * @return	array	Lines of invitation [user, code, date, empty element]
3635
     *
3636
     * @author Patrick Cool <[email protected]>, Ghent University
3637
     * @version January 2007
3638
     *
3639
     * @todo use survey_id parameter instead of $_GET
3640
     */
3641
    public static function get_survey_invitations_data()
3642
    {
3643
        $course_id = api_get_course_int_id();
3644
        // Database table definition
3645
        $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
3646
        $table_user = Database :: get_main_table(TABLE_MAIN_USER);
3647
3648
        $sql = "SELECT
3649
					survey_invitation.user as col1,
3650
					survey_invitation.invitation_code as col2,
3651
					survey_invitation.invitation_date as col3,
3652
					'' as col4
3653
					FROM $table_survey_invitation survey_invitation
3654
                LEFT JOIN $table_user user
3655
                ON survey_invitation.user = user.user_id
3656
                WHERE
3657
                    survey_invitation.c_id = $course_id AND
3658
                    survey_invitation.survey_id = '".intval($_GET['survey_id'])."' AND
3659
                    session_id='".api_get_session_id()."'  ";
3660
        $res = Database::query($sql);
3661
        $data = [];
3662
        while ($row = Database::fetch_array($res)) {
3663
            $data[] = $row;
3664
        }
3665
3666
        return $data;
3667
    }
3668
3669
    /**
3670
     * Get the total number of survey invitations for a given survey (through $_GET['survey_id'])
3671
     *
3672
     * @return	integer	Total number of survey invitations
3673
     *
3674
     * @todo use survey_id parameter instead of $_GET
3675
     *
3676
     * @author Patrick Cool <[email protected]>, Ghent University
3677
     * @version January 2007
3678
     */
3679
    public static function get_number_of_survey_invitations()
3680
    {
3681
        $course_id = api_get_course_int_id();
3682
3683
        // Database table definition
3684
        $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
3685
3686
        $sql = "SELECT count(user) AS total
3687
		        FROM $table_survey_invitation
3688
		        WHERE
3689
                    c_id = $course_id AND
3690
                    survey_id='".intval($_GET['survey_id'])."' AND
3691
                    session_id='".api_get_session_id()."' ";
3692
        $res = Database::query($sql);
3693
        $row = Database::fetch_array($res,'ASSOC');
3694
3695
        return $row['total'];
3696
    }
3697
3698
    /**
3699
     * Save the invitation mail
3700
     *
3701
     * @param string 	Text of the e-mail
3702
     * @param integer	Whether the mail contents are for invite mail (0, default) or reminder mail (1)
3703
     *
3704
     * @author Patrick Cool <[email protected]>, Ghent University
3705
     * @version January 2007
3706
     */
3707
    public static function save_invite_mail($mailtext, $mail_subject, $reminder = 0)
3708
    {
3709
        $course_id = api_get_course_int_id();
3710
        // Database table definition
3711
        $table_survey = Database :: get_course_table(TABLE_SURVEY);
3712
3713
        // Reminder or not
3714
        if ($reminder == 0) {
3715
            $mail_field = 'invite_mail';
3716
        } else {
3717
            $mail_field = 'reminder_mail';
3718
        }
3719
3720
        $sql = "UPDATE $table_survey SET
3721
		        mail_subject='".Database::escape_string($mail_subject)."',
3722
		        $mail_field = '".Database::escape_string($mailtext)."'
3723
		        WHERE c_id = $course_id AND survey_id = '".intval($_GET['survey_id'])."'";
3724
        Database::query($sql);
3725
    }
3726
3727
    /**
3728
     * This function saves all the invitations of course users and additional users in the database
3729
     * and sends the invitations by email
3730
     *
3731
     * @param	array	Users array can be both a list of course uids AND a list of additional emailaddresses
3732
     * @param 	string	Title of the invitation, used as the title of the mail
3733
     * @param 	string	Text of the invitation, used as the text of the mail.
3734
     * 				 The text has to contain a **link** string or this will automatically be added to the end
3735
     *
3736
     * @author Patrick Cool <[email protected]>, Ghent University
3737
     * @author Julio Montoya - Adding auto-generated link support
3738
     * @version January 2007
3739
     *
3740
     */
3741
    public static function saveInvitations(
3742
        $users_array,
3743
        $invitation_title,
3744
        $invitation_text,
3745
        $reminder = 0,
3746
        $sendmail = 0,
3747
        $remindUnAnswered = 0
3748
    ) {
3749
        if (!is_array($users_array)) {
3750
            // Should not happen
3751
3752
            return 0;
3753
        }
3754
3755
        // Getting the survey information
3756
        $survey_data = SurveyManager::get_survey($_GET['survey_id']);
3757
        $survey_invitations = SurveyUtil::get_invitations($survey_data['survey_code']);
3758
        $already_invited = SurveyUtil::get_invited_users($survey_data['code']);
3759
3760
        // Remind unanswered is a special version of remind all reminder
3761
        $exclude_users = array();
3762
        if ($remindUnAnswered == 1) { // Remind only unanswered users
3763
            $reminder = 1;
3764
            $exclude_users = SurveyManager::get_people_who_filled_survey($_GET['survey_id']);
3765
        }
3766
3767
        $counter = 0;  // Nr of invitations "sent" (if sendmail option)
3768
        $course_id = api_get_course_int_id();
3769
        $session_id = api_get_session_id();
3770
3771
        $result = CourseManager::separateUsersGroups($users_array);
3772
3773
        $groupList = $result['groups'];
3774
        $users_array = $result['users'];
3775
3776
        foreach ($groupList as $groupId) {
3777
            $userGroupList = GroupManager::getStudents($groupId);
3778
            $userGroupIdList = array_column($userGroupList, 'user_id');
3779
            $users_array = array_merge($users_array, $userGroupIdList);
3780
3781
            $params = array(
3782
                'c_id' => $course_id,
3783
                'session_id' => $session_id,
3784
                'group_id' => $groupId,
3785
                'survey_code' => $survey_data['code']
3786
            );
3787
3788
            $invitationExists = self::invitationExists(
3789
                $course_id,
3790
                $session_id,
3791
                $groupId,
3792
                $survey_data['code']
3793
            );
3794
            if (empty($invitationExists)) {
3795
                self::save_invitation($params);
3796
            }
3797
        }
3798
3799
        $users_array = array_unique($users_array);
3800
3801
        foreach ($users_array as $key => $value) {
3802
            if (!isset($value) || $value == '') {
3803
                continue;
3804
            }
3805
3806
            // Skip user if reminding only unanswered people
3807
            if (in_array($value, $exclude_users)) {
3808
                continue;
3809
            }
3810
3811
            // Get the unique invitation code if we already have it
3812
            if ($reminder == 1 && array_key_exists($value, $survey_invitations)) {
3813
                $invitation_code = $survey_invitations[$value]['invitation_code'];
3814
            } else {
3815
                $invitation_code = md5($value.microtime());
3816
            }
3817
            $new_user = false; // User not already invited
3818
            // Store the invitation if user_id not in $already_invited['course_users'] OR email is not in $already_invited['additional_users']
3819
            $addit_users_array = isset($already_invited['additional_users']) && !empty($already_invited['additional_users']) ? explode(';', $already_invited['additional_users']) : array();
3820
3821
            $my_alredy_invited = $already_invited['course_users'] == null ? array() : $already_invited['course_users'];
3822
            if ((is_numeric($value) && !in_array($value, $my_alredy_invited)) ||
3823
                (!is_numeric($value) && !in_array($value, $addit_users_array))
3824
            ) {
3825
                $new_user = true;
3826
                if (!array_key_exists($value, $survey_invitations)) {
3827
                    $params = array(
3828
                        'c_id' => $course_id,
3829
                        'session_id' => $session_id,
3830
                        'user' => $value,
3831
                        'survey_code' => $survey_data['code'],
3832
                        'invitation_code' => $invitation_code,
3833
                        'invitation_date' => api_get_utc_datetime()
3834
                    );
3835
                    self::save_invitation($params);
3836
                }
3837
            }
3838
3839
            // Send the email if checkboxed
3840
            if (($new_user || $reminder == 1) && $sendmail != 0) {
3841
                // Make a change for absolute url
3842
                if (isset($invitation_text)) {
3843
                    $invitation_text = api_html_entity_decode($invitation_text, ENT_QUOTES);
3844
                    $invitation_text = str_replace('src="../../', 'src="'.api_get_path(WEB_PATH), $invitation_text);
3845
                    $invitation_text = trim(stripslashes($invitation_text));
3846
                }
3847
                SurveyUtil::send_invitation_mail($value, $invitation_code, $invitation_title, $invitation_text);
3848
                $counter++;
3849
            }
3850
        }
3851
3852
        return $counter; // Number of invitations sent
3853
    }
3854
3855
    /**
3856
     * @param $params
3857
     * @return bool|int
3858
     */
3859
    public static function save_invitation($params)
3860
    {
3861
        // Database table to store the invitations data
3862
        $table = Database::get_course_table(TABLE_SURVEY_INVITATION);
3863
        if (!empty($params['c_id']) &&
3864
            (!empty($params['user']) || !empty($params['group_id'])) &&
3865
            !empty($params['survey_code'])
3866
        ) {
3867
            $insertId = Database::insert($table, $params);
3868
            if ($insertId) {
3869
3870
                $sql = "UPDATE $table SET survey_invitation_id = $insertId
3871
                        WHERE iid = $insertId";
3872
                Database::query($sql);
3873
            }
3874
            return $insertId;
3875
        }
3876
        return false;
3877
    }
3878
3879
    /**
3880
     * @param int $courseId
3881
     * @param int $sessionId
3882
     * @param int $groupId
3883
     * @param string $surveyCode
3884
     * @return int
3885
     */
3886
    public static function invitationExists($courseId, $sessionId, $groupId, $surveyCode)
3887
    {
3888
        $table = Database::get_course_table(TABLE_SURVEY_INVITATION);
3889
        $courseId = intval($courseId);
3890
        $sessionId = intval($sessionId);
3891
        $groupId = intval($groupId);
3892
        $surveyCode = Database::escape_string($surveyCode);
3893
3894
        $sql = "SELECT survey_invitation_id FROM $table
3895
                WHERE
3896
                    c_id = $courseId AND
3897
                    session_id = $sessionId AND
3898
                    group_id = $groupId AND
3899
                    survey_code = '$surveyCode'
3900
                ";
3901
        $result = Database::query($sql);
3902
3903
        return Database::num_rows($result);
3904
    }
3905
3906
    /**
3907
     * Send the invitation by mail.
3908
     *
3909
     * @param int invitedUser - the userId (course user) or emailaddress of additional user
3910
     * $param string $invitation_code - the unique invitation code for the URL
3911
     * @return	void
3912
     */
3913
    public static function send_invitation_mail($invitedUser, $invitation_code, $invitation_title, $invitation_text)
3914
    {
3915
        $_user = api_get_user_info();
3916
        $_course = api_get_course_info();
3917
3918
        // Replacing the **link** part with a valid link for the user
3919
        $survey_link = api_get_path(WEB_CODE_PATH).'survey/fillsurvey.php?course='.$_course['code'].'&invitationcode='.$invitation_code;
3920
        $text_link = '<a href="'.$survey_link.'">'.get_lang('ClickHereToAnswerTheSurvey')."</a><br />\r\n<br />\r\n".get_lang('OrCopyPasteTheFollowingUrl')." <br />\r\n ".$survey_link;
3921
3922
        $replace_count = 0;
3923
        $full_invitation_text = api_str_ireplace('**link**', $text_link ,$invitation_text, $replace_count);
3924
        if ($replace_count < 1) {
3925
            $full_invitation_text = $full_invitation_text."<br />\r\n<br />\r\n".$text_link;
3926
        }
3927
3928
        // Sending the mail
3929
        $sender_name  = api_get_person_name($_user['firstName'], $_user['lastName'], null, PERSON_NAME_EMAIL_ADDRESS);
3930
        $sender_email = $_user['mail'];
3931
        $sender_user_id = api_get_user_id();
3932
3933
        $replyto = array();
3934
        if (api_get_setting('survey_email_sender_noreply') == 'noreply') {
3935
            $noreply = api_get_setting('noreply_email_address');
3936
            if (!empty($noreply)) {
3937
                $replyto['Reply-to'] = $noreply;
3938
                $sender_name = $noreply;
3939
                $sender_email = $noreply;
3940
                $sender_user_id = null;
3941
            }
3942
        }
3943
3944
        // Optionally: finding the e-mail of the course user
3945
        if (is_numeric($invitedUser)) {
3946
            $table_user = Database :: get_main_table(TABLE_MAIN_USER);
3947
            $sql = "SELECT firstname, lastname, email FROM $table_user
3948
                    WHERE user_id='".Database::escape_string($invitedUser)."'";
3949
            $result = Database::query($sql);
3950
            $row = Database::fetch_array($result);
3951
            $recipient_email = $row['email'];
3952
            $recipient_name = api_get_person_name($row['firstname'], $row['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);
3953
3954
            MessageManager::send_message(
3955
                $invitedUser,
3956
                $invitation_title,
3957
                $full_invitation_text,
3958
                [],
3959
                [],
3960
                null,
3961
                null,
3962
                null,
3963
                null,
3964
                $sender_user_id
3965
            );
3966
3967
        } else {
3968
            /** @todo check if the address is a valid email	 */
3969
            $recipient_email = $invitedUser;
3970
            @api_mail_html(
3971
                $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...
3972
                $recipient_email,
3973
                $invitation_title,
3974
                $full_invitation_text,
3975
                $sender_name,
3976
                $sender_email,
3977
                $replyto
3978
            );
3979
        }
3980
    }
3981
3982
    /**
3983
     * This function recalculates the number of users who have been invited and updates the survey table with this value.
3984
     *
3985
     * @param	string	Survey code
3986
     * @return	void
3987
     * @author Patrick Cool <[email protected]>, Ghent University
3988
     * @version January 2007
3989
     */
3990
    public static function update_count_invited($survey_code)
3991
    {
3992
        $course_id = api_get_course_int_id();
3993
3994
        // Database table definition
3995
        $table_survey_invitation 	= Database :: get_course_table(TABLE_SURVEY_INVITATION);
3996
        $table_survey 				= Database :: get_course_table(TABLE_SURVEY);
3997
3998
        // Counting the number of people that are invited
3999
        $sql = "SELECT count(user) as total
4000
                FROM $table_survey_invitation
4001
		        WHERE
4002
		            c_id = $course_id AND
4003
		            survey_code = '".Database::escape_string($survey_code)."' AND
4004
		            user <> ''
4005
                ";
4006
        $result = Database::query($sql);
4007
        $row = Database::fetch_array($result);
4008
        $total_invited = $row['total'];
4009
4010
        // Updating the field in the survey table
4011
        $sql = "UPDATE $table_survey
4012
		        SET invited = '".Database::escape_string($total_invited)."'
4013
		        WHERE
4014
		            c_id = $course_id AND
4015
		            code = '".Database::escape_string($survey_code)."'
4016
                ";
4017
        Database::query($sql);
4018
    }
4019
4020
    /**
4021
     * This function gets all the invited users for a given survey code.
4022
     *
4023
     * @param	string	Survey code
4024
     * @param	string	optional - course database
4025
     * @return 	array	Array containing the course users and additional users (non course users)
4026
     *
4027
     * @todo consider making $defaults['additional_users'] also an array
4028
     *
4029
     * @author Patrick Cool <[email protected]>, Ghent University
4030
     * @author Julio Montoya, adding c_id fixes - Dec 2012
4031
     * @version January 2007
4032
     */
4033
    public static function get_invited_users($survey_code, $course_code = '', $session_id = 0)
4034
    {
4035
        if (!empty($course_code)) {
4036
            $course_info = api_get_course_info($course_code);
4037
            $course_id = $course_info['real_id'];
4038
        } else {
4039
            $course_id = api_get_course_int_id();
4040
        }
4041
4042
        if (empty($session_id)) {
4043
            $session_id = api_get_session_id();
4044
        }
4045
4046
        $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
4047
        $table_user = Database :: get_main_table(TABLE_MAIN_USER);
4048
4049
        // Selecting all the invitations of this survey AND the additional emailaddresses (the left join)
4050
        $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname' : ' ORDER BY lastname, firstname';
4051
        $sql = "SELECT user, group_id
4052
				FROM $table_survey_invitation as table_invitation
4053
				WHERE
4054
				    table_invitation.c_id = $course_id AND
4055
                    survey_code='".Database::escape_string($survey_code)."' AND
4056
                    session_id = $session_id
4057
                ";
4058
4059
        $defaults = array();
4060
        $defaults['course_users'] = array();
4061
        $defaults['additional_users'] = array(); // Textarea
4062
        $defaults['users'] = array(); // user and groups
4063
4064
        $result = Database::query($sql);
4065
        while ($row = Database::fetch_array($result)) {
4066
            if (is_numeric($row['user'])) {
4067
                $defaults['course_users'][] = $row['user'];
4068
                $defaults['users'][] = 'USER:'.$row['user'];
4069
            } else {
4070
                if (!empty($row['user'])) {
4071
                    $defaults['additional_users'][] = $row['user'];
4072
                }
4073
            }
4074
4075 View Code Duplication
            if (isset($row['group_id']) && !empty($row['group_id'])) {
4076
                $defaults['users'][] = 'GROUP:'.$row['group_id'];
4077
            }
4078
        }
4079
4080 View Code Duplication
        if (!empty($defaults['course_users'])) {
4081
            $user_ids = implode("','", $defaults['course_users']);
4082
            $sql = "SELECT user_id FROM $table_user WHERE user_id IN ('$user_ids') $order_clause";
4083
            $result = Database::query($sql);
4084
            $fixed_users = array();
4085
            while ($row = Database::fetch_array($result)) {
4086
                $fixed_users[] = $row['user_id'];
4087
            }
4088
            $defaults['course_users'] = $fixed_users;
4089
        }
4090
4091
        if (!empty($defaults['additional_users'])) {
4092
            $defaults['additional_users'] = implode(';', $defaults['additional_users']);
4093
        }
4094
        return $defaults;
4095
    }
4096
4097
    /**
4098
     * Get all the invitations
4099
     *
4100
     * @param	string	Survey code
4101
     * @return	array	Database rows matching the survey code
4102
     *
4103
     * @author Patrick Cool <[email protected]>, Ghent University
4104
     * @version September 2007
4105
     */
4106 View Code Duplication
    public static function get_invitations($survey_code)
4107
    {
4108
        $course_id = api_get_course_int_id();
4109
        // Database table definition
4110
        $table_survey_invitation 	= Database :: get_course_table(TABLE_SURVEY_INVITATION);
4111
4112
        $sql = "SELECT * FROM $table_survey_invitation
4113
		        WHERE
4114
		            c_id = $course_id AND
4115
		            survey_code = '".Database::escape_string($survey_code)."'";
4116
        $result = Database::query($sql);
4117
        $return = array();
4118
        while ($row = Database::fetch_array($result)) {
4119
            $return[$row['user']] = $row;
4120
        }
4121
        return $return;
4122
    }
4123
4124
    /**
4125
     * This function displays the form for searching a survey
4126
     *
4127
     * @return	void	(direct output)
4128
     *
4129
     * @author Patrick Cool <[email protected]>, Ghent University
4130
     * @version January 2007
4131
     *
4132
     * @todo use quickforms
4133
     * @todo consider moving this to surveymanager.inc.lib.php
4134
     */
4135
    public static function display_survey_search_form()
4136
    {
4137
        $url = api_get_path(WEB_CODE_PATH).'survey/survey_list.php?search=advanced&'.api_get_cidreq();
4138
        $form = new FormValidator('search', 'get', $url);
4139
        $form->addHeader(get_lang('SearchASurvey'));
4140
        $form->addText('keyword_title', get_lang('Title'));
4141
        $form->addText('keyword_code', get_lang('Code'));
4142
        $form->addSelectLanguage('keyword_language', get_lang('Language'));
4143
        $form->addHidden('cidReq', api_get_course_id());
4144
        $form->addButtonSearch(get_lang('Search'), 'do_search');
4145
        $form->display();
4146
    }
4147
4148
    /**
4149
     * Show table only visible by DRH users
4150
     */
4151
    public static function displaySurveyListForDrh()
4152
    {
4153
        $parameters = array();
4154
        $parameters['cidReq'] = api_get_course_id();
4155
4156
        // Create a sortable table with survey-data
4157
        $table = new SortableTable('surveys', 'get_number_of_surveys', 'get_survey_data_drh', 2);
4158
        $table->set_additional_parameters($parameters);
4159
        $table->set_header(0, '', false);
4160
        $table->set_header(1, get_lang('SurveyName'));
4161
        $table->set_header(2, get_lang('SurveyCode'));
4162
        $table->set_header(3, get_lang('NumberOfQuestions'));
4163
        $table->set_header(4, get_lang('Author'));
4164
        $table->set_header(5, get_lang('AvailableFrom'));
4165
        $table->set_header(6, get_lang('AvailableUntil'));
4166
        $table->set_header(7, get_lang('Invite'));
4167
        $table->set_header(8, get_lang('Anonymous'));
4168
        $table->set_header(9, get_lang('Modify'), false, 'width="150"');
4169
        $table->set_column_filter(8, 'anonymous_filter');
4170
        $table->set_column_filter(9, 'modify_filter_drh');
4171
        $table->display();
4172
    }
4173
4174
    /**
4175
     * This function displays the sortable table with all the surveys
4176
     *
4177
     * @return	void	(direct output)
4178
     *
4179
     * @author Patrick Cool <[email protected]>, Ghent University
4180
     * @version January 2007
4181
     */
4182
    public static function display_survey_list()
4183
    {
4184
        $parameters = array();
4185
        $parameters['cidReq'] = api_get_course_id();
4186 View Code Duplication
        if (isset($_GET['do_search']) && $_GET['do_search']) {
4187
            $message = get_lang('DisplaySearchResults').'<br />';
4188
            $message .= '<a href="'.api_get_self().'?'.api_get_cidreq().'">'.get_lang('DisplayAll').'</a>';
4189
            Display::display_normal_message($message, false);
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_normal_message() has been deprecated with message: use Display::addFlash with Display::return_message($message, 'normal');

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
4190
        }
4191
4192
        // Create a sortable table with survey-data
4193
        $table = new SortableTable('surveys', 'get_number_of_surveys', 'get_survey_data', 2);
4194
        $table->set_additional_parameters($parameters);
4195
        $table->set_header(0, '', false);
4196
        $table->set_header(1, get_lang('SurveyName'));
4197
        $table->set_header(2, get_lang('SurveyCode'));
4198
        $table->set_header(3, get_lang('NumberOfQuestions'));
4199
        $table->set_header(4, get_lang('Author'));
4200
        //$table->set_header(5, get_lang('Language'));
4201
        //$table->set_header(6, get_lang('Shared'));
4202
        $table->set_header(5, get_lang('AvailableFrom'));
4203
        $table->set_header(6, get_lang('AvailableUntil'));
4204
        $table->set_header(7, get_lang('Invite'));
4205
        $table->set_header(8, get_lang('Anonymous'));
4206
        $table->set_header(9, get_lang('Modify'), false, 'width="150"');
4207
        $table->set_column_filter(8, 'anonymous_filter');
4208
        $table->set_column_filter(9, 'modify_filter');
4209
        $table->set_form_actions(array('delete' => get_lang('DeleteSurvey')));
4210
        $table->display();
4211
    }
4212
4213
    /**
4214
     * Survey list for coach
4215
     */
4216
    public static function display_survey_list_for_coach()
4217
    {
4218
        $parameters = array();
4219
        $parameters['cidReq']=api_get_course_id();
4220 View Code Duplication
        if (isset($_GET['do_search'])) {
4221
            $message = get_lang('DisplaySearchResults').'<br />';
4222
            $message .= '<a href="'.api_get_self().'?'.api_get_cidreq().'">'.get_lang('DisplayAll').'</a>';
4223
            Display::display_normal_message($message, false);
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_normal_message() has been deprecated with message: use Display::addFlash with Display::return_message($message, 'normal');

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
4224
        }
4225
4226
        // Create a sortable table with survey-data
4227
        $table = new SortableTable('surveys_coach', 'get_number_of_surveys_for_coach', 'get_survey_data_for_coach', 2);
4228
        $table->set_additional_parameters($parameters);
4229
        $table->set_header(0, '', false);
4230
        $table->set_header(1, get_lang('SurveyName'));
4231
        $table->set_header(2, get_lang('SurveyCode'));
4232
        $table->set_header(3, get_lang('NumberOfQuestions'));
4233
        $table->set_header(4, get_lang('Author'));
4234
        //$table->set_header(5, get_lang('Language'));
4235
        //$table->set_header(6, get_lang('Shared'));
4236
        $table->set_header(5, get_lang('AvailableFrom'));
4237
        $table->set_header(6, get_lang('AvailableUntil'));
4238
        $table->set_header(7, get_lang('Invite'));
4239
        $table->set_header(8, get_lang('Anonymous'));
4240
        $table->set_header(9, get_lang('Modify'), false, 'width="130"');
4241
        $table->set_column_filter(8, 'anonymous_filter');
4242
        $table->set_column_filter(9, 'modify_filter_for_coach');
4243
        $table->display();
4244
    }
4245
4246
    /**
4247
     * This function changes the modify column of the sortable table
4248
     *
4249
     * @param integer $survey_id the id of the survey
4250
     * @param bool $drh
4251
     * @return string html code that are the actions that can be performed on any survey
4252
     *
4253
     * @author Patrick Cool <[email protected]>, Ghent University
4254
     * @version January 2007
4255
     */
4256
    public static function modify_filter($survey_id, $drh = false)
4257
    {
4258
        $survey_id = Security::remove_XSS($survey_id);
4259
        $return = '';
4260
4261
        if ($drh) {
4262
            return '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.
4263
            Display::return_icon('stats.png', get_lang('Reporting'),'',ICON_SIZE_SMALL).'</a>';
4264
        }
4265
4266
        // Coach can see that only if the survey is in his session
4267
        if (api_is_allowed_to_edit() ||
4268
            api_is_element_in_the_session(TOOL_SURVEY, $survey_id)
4269
        ) {
4270
            $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>';
4271
            if (SurveyManager::survey_generation_hash_available()) {
4272
                $return .=  Display::url(
4273
                    Display::return_icon('new_link.png', get_lang('GenerateSurveyAccessLink'),'',ICON_SIZE_SMALL),
4274
                    api_get_path(WEB_CODE_PATH).'survey/generate_link.php?survey_id='.$survey_id.'&'.api_get_cidreq()
4275
                );
4276
            }
4277
            $return .= Display::url(
4278
                Display::return_icon('copy.png', get_lang('DuplicateSurvey'), '', ICON_SIZE_SMALL),
4279
                'survey_list.php?action=copy_survey&survey_id='.$survey_id.'&'.api_get_cidreq()
4280
            );
4281
4282
            $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;">'.
4283
                Display::return_icon('clean.png', get_lang('EmptySurvey'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
4284
        }
4285
        $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/preview.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.
4286
            Display::return_icon('preview_view.png', get_lang('Preview'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
4287
        $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_invite.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.
4288
            Display::return_icon('mail_send.png', get_lang('Publish'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
4289
        $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.
4290
            Display::return_icon('stats.png', get_lang('Reporting'),'',ICON_SIZE_SMALL).'</a>';
4291
4292 View Code Duplication
        if (api_is_allowed_to_edit() ||
4293
            api_is_element_in_the_session(TOOL_SURVEY, $survey_id)
4294
        ) {
4295
            $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;">'.
4296
                Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
4297
        }
4298
4299
        return $return;
4300
    }
4301
4302
    public static function modify_filter_for_coach($survey_id)
4303
    {
4304
        $survey_id = Security::remove_XSS($survey_id);
4305
        //$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>';
4306
        //$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>';
4307
        //$return .= '<a href="create_survey_in_another_language.php?id_survey='.$survey_id.'">'.Display::return_icon('copy.gif', get_lang('Copy')).'</a>';
4308
        //$return .= '<a href="survey.php?survey_id='.$survey_id.'">'.Display::return_icon('add.gif', get_lang('Add')).'</a>';
4309
        $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;';
4310
        $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;';
4311
        $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;';
4312
4313
        return $return;
4314
    }
4315
4316
    /**
4317
     * Returns "yes" when given parameter is one, "no" for any other value
4318
     * @param	integer	Whether anonymous or not
4319
     * @return	string	"Yes" or "No" in the current language
4320
     */
4321
    public static function anonymous_filter($anonymous)
4322
    {
4323
        if ($anonymous == 1) {
4324
            return get_lang('Yes');
4325
        } else {
4326
            return get_lang('No');
4327
        }
4328
    }
4329
4330
    /**
4331
     * This function handles the search restriction for the SQL statements
4332
     *
4333
     * @return	string	Part of a SQL statement or false on error
4334
     *
4335
     * @author Patrick Cool <[email protected]>, Ghent University
4336
     * @version January 2007
4337
     */
4338
    public static function survey_search_restriction()
4339
    {
4340
        if (isset($_GET['do_search'])) {
4341
            if ($_GET['keyword_title'] != '') {
4342
                $search_term[] = 'title like "%" \''.Database::escape_string($_GET['keyword_title']).'\' "%"';
4343
            }
4344
            if ($_GET['keyword_code'] != '') {
4345
                $search_term[] = 'code =\''.Database::escape_string($_GET['keyword_code']).'\'';
4346
            }
4347
            if ($_GET['keyword_language'] != '%') {
4348
                $search_term[] = 'lang =\''.Database::escape_string($_GET['keyword_language']).'\'';
4349
            }
4350
            $my_search_term = ($search_term == null) ? array() : $search_term;
4351
            $search_restriction = implode(' AND ', $my_search_term);
4352
            return $search_restriction;
4353
        } else {
4354
            return false;
4355
        }
4356
    }
4357
4358
    /**
4359
     * This function calculates the total number of surveys
4360
     *
4361
     * @return	integer	Total number of surveys
4362
     *
4363
     * @author Patrick Cool <[email protected]>, Ghent University
4364
     * @version January 2007
4365
     */
4366
    public static function get_number_of_surveys()
4367
    {
4368
        $table_survey = Database :: get_course_table(TABLE_SURVEY);
4369
        $course_id = api_get_course_int_id();
4370
4371
        $search_restriction = SurveyUtil::survey_search_restriction();
4372
        if ($search_restriction) {
4373
            $search_restriction = 'WHERE c_id = '.$course_id.' AND '.$search_restriction;
4374
        } else {
4375
            $search_restriction = "WHERE c_id = $course_id";
4376
        }
4377
        $sql = "SELECT count(survey_id) AS total_number_of_items
4378
		        FROM ".$table_survey.' '.$search_restriction;
4379
        $res = Database::query($sql);
4380
        $obj = Database::fetch_object($res);
4381
        return $obj->total_number_of_items;
4382
    }
4383
4384
    public static function get_number_of_surveys_for_coach()
4385
    {
4386
        $survey_tree = new SurveyTree();
4387
        return count($survey_tree->surveylist);
4388
    }
4389
4390
    /**
4391
     * This function gets all the survey data that is to be displayed in the sortable table
4392
     *
4393
     * @param int $from
4394
     * @param int $number_of_items
4395
     * @param int $column
4396
     * @param string $direction
4397
     * @param bool $isDrh
4398
     * @return unknown
4399
     *
4400
     * @author Patrick Cool <[email protected]>, Ghent University
4401
     * @author Julio Montoya <[email protected]>, Beeznest - Adding intvals
4402
     * @version January 2007
4403
     */
4404
    public static function get_survey_data($from, $number_of_items, $column, $direction, $isDrh = false)
4405
    {
4406
        $table_survey = Database :: get_course_table(TABLE_SURVEY);
4407
        $table_user = Database :: get_main_table(TABLE_MAIN_USER);
4408
        $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
4409
        $_user = api_get_user_info();
4410
4411
        // Searching
4412
        $search_restriction = SurveyUtil::survey_search_restriction();
4413
        if ($search_restriction) {
4414
            $search_restriction = ' AND '.$search_restriction;
4415
        }
4416
        $from = intval($from);
4417
        $number_of_items = intval($number_of_items);
4418
        $column = intval($column);
4419
        if (!in_array(strtolower($direction), array('asc', 'desc'))) {
4420
            $direction = 'asc';
4421
        }
4422
4423
        // Condition for the session
4424
        $session_id = api_get_session_id();
4425
        $condition_session = api_get_session_condition($session_id);
4426
        $course_id = api_get_course_int_id();
4427
4428
        $sql = "SELECT
4429
					survey.survey_id AS col0,
4430
					survey.title AS col1,
4431
					survey.code AS col2,
4432
					count(survey_question.question_id) AS col3,
4433
					".(api_is_western_name_order() ? "CONCAT(user.firstname, ' ', user.lastname)" : "CONCAT(user.lastname, ' ', user.firstname)")."	AS col4,
4434
					survey.avail_from AS col5,
4435
					survey.avail_till AS col6,
4436
					survey.invited AS col7,
4437
					survey.anonymous AS col8,
4438
					survey.survey_id AS col9,
4439
					survey.session_id AS session_id,
4440
					survey.answered,
4441
					survey.invited
4442
                FROM $table_survey survey
4443
                LEFT JOIN $table_survey_question survey_question
4444
                ON (survey.survey_id = survey_question.survey_id AND survey_question.c_id = $course_id)
4445
                LEFT JOIN $table_user user
4446
                ON (survey.author = user.user_id)
4447
                WHERE survey.c_id = $course_id
4448
                $search_restriction
4449
                $condition_session ";
4450
        $sql .= " GROUP BY survey.survey_id";
4451
        $sql .= " ORDER BY col$column $direction ";
4452
        $sql .= " LIMIT $from,$number_of_items";
4453
4454
        $res = Database::query($sql);
4455
        $surveys = array();
4456
        $array = array();
4457
        while ($survey = Database::fetch_array($res)) {
4458
            $array[0] = $survey[0];
4459
            $array[1] = Display::url(
4460
                $survey[1],
4461
                api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.$survey[0].'&'.api_get_cidreq()
4462
            );
4463
4464
            // Validation when belonging to a session
4465
            $session_img = api_get_session_image($survey['session_id'], $_user['status']);
4466
            $array[2] = $survey[2] . $session_img;
4467
            $array[3] = $survey[3];
4468
            $array[4] = $survey[4];
4469
            $array[5] = $survey[5];
4470
            $array[6] = $survey[6];
4471
            $array[7] =
4472
                Display::url(
4473
                    $survey['answered'],
4474
                    api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?view=answered&survey_id='.$survey[0].'&'.api_get_cidreq()
4475
                ).' / '.
4476
                Display::url(
4477
                    $survey['invited'],
4478
                    api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?view=invited&survey_id='.$survey[0].'&'.api_get_cidreq()
4479
                );
4480
4481
            $array[8] = $survey[8];
4482
            $array[9] = $survey[9];
4483
4484
            if ($isDrh) {
4485
                $array[1] = $survey[1];
4486
                $array[7] = strip_tags($array[7]);
4487
            }
4488
4489
            $surveys[] = $array;
4490
        }
4491
        return $surveys;
4492
    }
4493
4494
    /**
4495
     * @param $from
4496
     * @param $number_of_items
4497
     * @param $column
4498
     * @param $direction
4499
     * @return array
4500
     */
4501
    public static function get_survey_data_for_coach($from, $number_of_items, $column, $direction)
4502
    {
4503
        $survey_tree = new SurveyTree();
4504
        //$last_version_surveys = $survey_tree->get_last_children_from_branch($survey_tree->surveylist);
4505
        $last_version_surveys = $survey_tree->surveylist;
4506
        $list = array();
4507
        foreach ($last_version_surveys as & $survey) {
4508
            $list[]=$survey['id'];
4509
        }
4510
        if (count($list) > 0) {
4511
            $list_condition = " AND survey.survey_id IN (".implode(',',$list).") ";
4512
        } else {
4513
            $list_condition = '';
4514
        }
4515
4516
        $from = intval($from);
4517
        $number_of_items = intval($number_of_items);
4518
        $column = intval($column);
4519
        if (!in_array(strtolower($direction), array('asc', 'desc'))) {
4520
            $direction = 'asc';
4521
        }
4522
4523
        $table_survey = Database:: get_course_table(TABLE_SURVEY);
4524
        $table_survey_question = Database:: get_course_table(TABLE_SURVEY_QUESTION);
4525
        $table_user = Database:: get_main_table(TABLE_MAIN_USER);
4526
4527
        $course_id = api_get_course_int_id();
4528
4529
        $sql = "SELECT 
4530
            survey.survey_id							AS col0, 
4531
            survey.title AS col1, 
4532
            survey.code AS col2, 
4533
            count(survey_question.question_id)			AS col3, 
4534
            ".(api_is_western_name_order() ? "CONCAT(user.firstname, ' ', user.lastname)" : "CONCAT(user.lastname, ' ', user.firstname)")."	AS col4,
4535
            survey.avail_from AS col5,
4536
            survey.avail_till AS col6,
4537
            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,
4538
            survey.anonymous AS col8,
4539
            survey.survey_id AS col9
4540
            FROM $table_survey survey
4541
            LEFT JOIN $table_survey_question survey_question
4542
            ON (survey.survey_id = survey_question.survey_id AND survey.c_id = survey_question.c_id),
4543
            $table_user user
4544
            WHERE survey.author = user.user_id AND survey.c_id = $course_id $list_condition ";
4545
        $sql .= " GROUP BY survey.survey_id";
4546
        $sql .= " ORDER BY col$column $direction ";
4547
        $sql .= " LIMIT $from,$number_of_items";
4548
4549
        $res = Database::query($sql);
4550
        $surveys = array();
4551
        while ($survey = Database::fetch_array($res)) {
4552
            $surveys[] = $survey;
4553
        }
4554
4555
        return $surveys;
4556
    }
4557
4558
    /**
4559
     * Display all the active surveys for the given course user
4560
     *
4561
     * @param int $user_id
4562
     *
4563
     * @author Patrick Cool <[email protected]>, Ghent University
4564
     * @version April 2007
4565
     */
4566
    public static function getSurveyList($user_id)
4567
    {
4568
        $_course = api_get_course_info();
4569
        $course_id = $_course['real_id'];
4570
        $user_id = intval($user_id);
4571
        $sessionId = api_get_session_id();
4572
4573
        // Database table definitions
4574
        $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
4575
        $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
4576
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
4577
        $table_survey = Database:: get_course_table(TABLE_SURVEY);
4578
4579
        $sql = "SELECT question_id
4580
                FROM $table_survey_question
4581
                WHERE c_id = $course_id";
4582
        $result = Database::query($sql);
4583
4584
        $all_question_id = array();
4585
        while ($row = Database::fetch_array($result, 'ASSOC')) {
4586
            $all_question_id[] = $row;
4587
        }
4588
4589
        $count = 0;
4590
        for ($i = 0; $i < count($all_question_id); $i++) {
4591
            $sql = 'SELECT COUNT(*) as count
4592
			        FROM '.$table_survey_answer.'
4593
					WHERE
4594
					    c_id = '.$course_id.' AND
4595
					    question_id='.intval($all_question_id[$i]['question_id']).' AND
4596
					    user = '.$user_id;
4597
            $result = Database::query($sql);
4598
            while ($row = Database::fetch_array($result, 'ASSOC')) {
4599
                if ($row['count'] == 0) {
4600
                    $count++;
4601
                    break;
4602
                }
4603
            }
4604
            if ($count > 0) {
4605
                $link_add = true;
4606
                break;
4607
            }
4608
        }
4609
4610
        echo '<table id="list-survey" class="table ">';
4611
        echo '<tr>';
4612
        echo '	<th>'.get_lang('SurveyName').'</th>';
4613
        echo '	<th>'.get_lang('Anonymous').'</th>';
4614
        echo '</tr>';
4615
4616
        $now = api_get_utc_datetime();
4617
4618
        $sql = "SELECT *
4619
                FROM $table_survey survey INNER JOIN
4620
                $table_survey_invitation survey_invitation
4621
                ON (
4622
                    survey.code = survey_invitation.survey_code AND
4623
                    survey.c_id = survey_invitation.c_id
4624
                )
4625
				WHERE
4626
                    survey_invitation.user = $user_id AND                    
4627
                    survey.avail_from <= '".$now."' AND
4628
                    survey.avail_till >= '".$now."' AND
4629
                    survey.c_id = $course_id AND
4630
                    survey.session_id = $sessionId AND
4631
                    survey_invitation.c_id = $course_id
4632
				";
4633
        $result = Database::query($sql);
4634
4635
        while ($row = Database::fetch_array($result, 'ASSOC')) {
4636
            echo '<tr>';
4637
            if ($row['answered'] == 0) {
4638
                echo '<td>';
4639
                echo Display::return_icon('statistics.png', get_lang('CreateNewSurvey'), array(),ICON_SIZE_TINY);
4640
                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>';
4641
            } else {
4642
                echo '<td>';
4643
                echo Display::return_icon('statistics_na.png', get_lang('CreateNewSurvey'), array(),ICON_SIZE_TINY);
4644
                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>';
4645
            }
4646
            echo '<td class="center">';
4647
            echo ($row['anonymous'] == 1) ? get_lang('Yes') : get_lang('No');
4648
            echo '</td>';
4649
            echo '</tr>';
4650
        }
4651
        echo '</table>';
4652
    }
4653
4654
    /**
4655
     * Creates a multi array with the user fields that we can show. We look the visibility with the api_get_setting function
4656
     * The username is always NOT able to change it.
4657
     * @author Julio Montoya Armas <[email protected]>, Chamilo: Personality Test modification
4658
     * @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...
4659
     * 		   array[value_name][visibilty]
4660
     */
4661
    public static function make_field_list()
4662
    {
4663
        //	LAST NAME and FIRST NAME
4664
        $field_list_array = array();
4665
        $field_list_array['lastname']['name'] = get_lang('LastName');
4666
        $field_list_array['firstname']['name'] = get_lang('FirstName');
4667
4668
        if (api_get_setting('profile', 'name') != 'true') {
4669
            $field_list_array['firstname']['visibility'] = 0;
4670
            $field_list_array['lastname']['visibility'] = 0;
4671
        } else {
4672
            $field_list_array['firstname']['visibility'] = 1;
4673
            $field_list_array['lastname']['visibility'] = 1;
4674
        }
4675
4676
        $field_list_array['username']['name'] = get_lang('Username');
4677
        $field_list_array['username']['visibility'] = 0;
4678
4679
        //	OFFICIAL CODE
4680
        $field_list_array['official_code']['name'] = get_lang('OfficialCode');
4681
4682 View Code Duplication
        if (api_get_setting('profile', 'officialcode') != 'true') {
4683
            $field_list_array['official_code']['visibility'] = 1;
4684
        } else {
4685
            $field_list_array['official_code']['visibility'] = 0;
4686
        }
4687
4688
        // EMAIL
4689
        $field_list_array['email']['name'] = get_lang('Email');
4690 View Code Duplication
        if (api_get_setting('profile', 'email') != 'true') {
4691
            $field_list_array['email']['visibility'] = 1;
4692
        } else {
4693
            $field_list_array['email']['visibility'] = 0;
4694
        }
4695
4696
        // PHONE
4697
        $field_list_array['phone']['name'] = get_lang('Phone');
4698 View Code Duplication
        if (api_get_setting('profile', 'phone') != 'true') {
4699
            $field_list_array['phone']['visibility'] = 0;
4700
        } else {
4701
            $field_list_array['phone']['visibility'] = 1;
4702
        }
4703
        //	LANGUAGE
4704
        $field_list_array['language']['name'] = get_lang('Language');
4705 View Code Duplication
        if (api_get_setting('profile', 'language') != 'true') {
4706
            $field_list_array['language']['visibility'] = 0;
4707
        } else {
4708
            $field_list_array['language']['visibility'] = 1;
4709
        }
4710
4711
        // EXTRA FIELDS
4712
        $extra = UserManager::get_extra_fields(0, 50, 5, 'ASC');
4713
4714
        foreach ($extra as $id => $field_details) {
4715
            if ($field_details[6] == 0) {
4716
                continue;
4717
            }
4718
            switch ($field_details[2]) {
4719 View Code Duplication
                case UserManager::USER_FIELD_TYPE_TEXT:
4720
                    $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4721
                    if ($field_details[7] == 0) {
4722
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4723
                    } else {
4724
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
4725
                    }
4726
                    break;
4727 View Code Duplication
                case UserManager::USER_FIELD_TYPE_TEXTAREA:
4728
                    $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4729
                    if ($field_details[7] == 0) {
4730
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4731
                    } else {
4732
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
4733
                    }
4734
                    break;
4735 View Code Duplication
                case UserManager::USER_FIELD_TYPE_RADIO:
4736
                    $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
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
                case UserManager::USER_FIELD_TYPE_SELECT:
4744
                    $get_lang_variables = false;
4745 View Code Duplication
                    if (in_array($field_details[1], array('mail_notify_message', 'mail_notify_invitation', 'mail_notify_group_message'))) {
4746
                        $get_lang_variables = true;
4747
                    }
4748
4749
                    if ($get_lang_variables) {
4750
                        $field_list_array['extra_'.$field_details[1]]['name'] = get_lang($field_details[3]);
4751
                    } else {
4752
                        $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4753
                    }
4754
4755
                    if ($field_details[7] == 0) {
4756
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4757
                    } else {
4758
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
4759
                    }
4760
                    break;
4761 View Code Duplication
                case UserManager::USER_FIELD_TYPE_SELECT_MULTIPLE:
4762
                    $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4763
                    if ($field_details[7] == 0) {
4764
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4765
                    } else {
4766
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
4767
                    }
4768
                    break;
4769 View Code Duplication
                case UserManager::USER_FIELD_TYPE_DATE:
4770
                    $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4771
                    if ($field_details[7] == 0) {
4772
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4773
                    } else {
4774
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
4775
                    }
4776
                    break;
4777 View Code Duplication
                case UserManager::USER_FIELD_TYPE_DATETIME:
4778
                    $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4779
                    if ($field_details[7] == 0) {
4780
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4781
                    } else {
4782
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
4783
                    }
4784
                    break;
4785 View Code Duplication
                case UserManager::USER_FIELD_TYPE_DOUBLE_SELECT:
4786
                    $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4787
                    if ($field_details[7] == 0) {
4788
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4789
                    } else {
4790
                        $field_list_array['extra_'.$field_details[1]]['visibility']=1;
4791
                    }
4792
                    break;
4793
                case UserManager::USER_FIELD_TYPE_DIVIDER:
4794
                    //$form->addElement('static',$field_details[1], '<br /><strong>'.$field_details[3].'</strong>');
4795
                    break;
4796
            }
4797
        }
4798
        return $field_list_array;
4799
    }
4800
4801
    /**
4802
     * @author Isaac Flores Paz <[email protected]>
4803
     * @param int $user_id - User ID
4804
     * @param string $survey_code
4805
     * @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...
4806
     *
4807
     * @return boolean
4808
     */
4809
    public static function show_link_available($user_id, $survey_code, $user_answer)
4810
    {
4811
        $table_survey = Database:: get_course_table(TABLE_SURVEY);
4812
        $table_survey_invitation = Database:: get_course_table(TABLE_SURVEY_INVITATION);
4813
        $table_survey_answer = Database:: get_course_table(TABLE_SURVEY_ANSWER);
4814
        $table_survey_question = Database:: get_course_table(TABLE_SURVEY_QUESTION);
4815
4816
        $survey_code = Database::escape_string($survey_code);
4817
        $user_id = intval($user_id);
4818
        $user_answer = Database::escape_string($user_answer);
4819
4820
        $course_id = api_get_course_int_id();
4821
4822
        $sql = 'SELECT COUNT(*) as count
4823
                FROM '.$table_survey_invitation.'
4824
		        WHERE
4825
		            user='.$user_id.' AND
4826
		            survey_code="'.$survey_code.'" AND 
4827
		            answered="1" AND 
4828
		            c_id = '.$course_id;
4829
4830
        $sql2 = 'SELECT COUNT(*) as count FROM '.$table_survey.' s 
4831
                 INNER JOIN '.$table_survey_question.' q 
4832
                 ON s.survey_id=q.survey_id
4833
				 WHERE 
4834
				    s.code="'.$survey_code.'" AND 
4835
				    q.type NOT IN("pagebreak","comment") AND s.c_id = '.$course_id.' AND q.c_id = '.$course_id.' ';
4836
4837
        $sql3 = 'SELECT COUNT(DISTINCT question_id) as count 
4838
                 FROM '.$table_survey_answer.'
4839
				 WHERE survey_id=(
4840
				    SELECT survey_id FROM '.$table_survey.'
4841
				    WHERE 
4842
				        code = "'.$survey_code.'" AND 
4843
				        c_id = '.$course_id.' 
4844
                    )  AND 
4845
                user="'.$user_answer.'" AND 
4846
                c_id = '.$course_id;
4847
4848
        $result  = Database::query($sql);
4849
        $result2 = Database::query($sql2);
4850
        $result3 = Database::query($sql3);
4851
4852
        $row  = Database::fetch_array($result, 'ASSOC');
4853
        $row2 = Database::fetch_array($result2, 'ASSOC');
4854
        $row3 = Database::fetch_array($result3, 'ASSOC');
4855
4856
        if ($row['count'] == 1 && $row3['count'] != $row2['count']) {
4857
4858
            return true;
4859
        } else {
4860
            return false;
4861
        }
4862
    }
4863
4864
    /**
4865
     * Display survey question chart
4866
     * @param   array	$chartData
4867
     * @param   boolean	$hasSerie Tells if the chart has a serie. False by default
4868
     * @param   string $chartContainerId
4869
     * @return	string 	(direct output)
4870
     */
4871
    public static function drawChart($chartData, $hasSerie = false, $chartContainerId = 'chartContainer')
4872
    {
4873
        $htmlChart = '';
4874
        if (api_browser_support("svg")) {
4875
            $htmlChart .= api_get_asset('d3/d3.js');
4876
            $htmlChart .= api_get_js("dimple.v2.1.2.min.js") . '
4877
            <script type="text/javascript">
4878
            var svg = dimple.newSvg("#'.$chartContainerId.'", "100%", 400);
4879
            var data = [';
4880
            $serie = array();
4881
            $order = array();
4882
            foreach ($chartData as $chartDataElement) {
4883
                $htmlChart .= '{"';
4884
                if (!$hasSerie) {
4885
                    $htmlChart .= get_lang("Option") . '":"' . $chartDataElement['option'] . '", "';
4886
                    array_push($order, $chartDataElement['option']);
4887
                } else {
4888
                    if (!is_array($chartDataElement['serie'])) {
4889
                        $htmlChart .= get_lang("Option") . '":"' . $chartDataElement['serie'] . '", "' .
4890
                            get_lang("Score") . '":"' . $chartDataElement['option'] . '", "';
4891
                        array_push($serie, $chartDataElement['serie']);
4892
                    } else {
4893
                        $htmlChart .= get_lang("Serie") . '":"' . $chartDataElement['serie'][0] . '", "' .
4894
                            get_lang("Option") . '":"' . $chartDataElement['serie'][1] . '", "' .
4895
                            get_lang("Score") . '":"' . $chartDataElement['option'] . '", "';
4896
                    }
4897
                }
4898
                $htmlChart .= get_lang("Votes") . '":"' . $chartDataElement['votes'] .
4899
                    '"},';
4900
            }
4901
            rtrim($htmlChart, ",");
4902
            $htmlChart .= '];
4903
                var myChart = new dimple.chart(svg, data);
4904
                myChart.addMeasureAxis("y", "' . get_lang("Votes") . '");';
4905
            if (!$hasSerie) {
4906
                $htmlChart .= 'var xAxisCategory = myChart.addCategoryAxis("x", "' . get_lang("Option") . '");
4907
                    xAxisCategory.addOrderRule(' . json_encode($order) . ');
4908
                    myChart.addSeries("' . get_lang("Option") . '", dimple.plot.bar);';
4909
            } else {
4910
                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 4882. 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...
4911
                    $serie = array_values(array_unique($serie));
4912
                    $htmlChart .= 'var xAxisCategory = myChart.addCategoryAxis("x", ["' . get_lang("Option") . '","' . get_lang("Score") . '"]);
4913
                        xAxisCategory.addOrderRule(' . json_encode($serie) . ');
4914
                        xAxisCategory.addGroupOrderRule("' . get_lang("Score") . '");
4915
                        myChart.addSeries("' . get_lang("Option") . '", dimple.plot.bar);';
4916
                } else {
4917
                    $htmlChart .= 'myChart.addCategoryAxis("x", ["' . get_lang("Option") . '","' . get_lang("Score") . '"]);
4918
                        myChart.addSeries("' . get_lang("Serie") . '", dimple.plot.bar);';
4919
                }
4920
            }
4921
            $htmlChart .= 'myChart.draw();
4922
                </script>';
4923
        }
4924
4925
        return $htmlChart;
4926
    }
4927
4928
    /**
4929
     * Set a flag to the current survey as answered by the current user
4930
     * @param string $surveyCode The survey code
4931
     * @param int $courseId The course ID
4932
     */
4933
    public static function flagSurveyAsAnswered($surveyCode, $courseId)
4934
    {
4935
        $currenUserId = api_get_user_id();
4936
        $flag = sprintf("%s-%s-%d", $courseId, $surveyCode, $currenUserId);
4937
4938
        if (!isset($_SESSION['filled_surveys'])) {
4939
            $_SESSION['filled_surveys'] = array();
4940
        }
4941
4942
        $_SESSION['filled_surveys'][] = $flag;
4943
    }
4944
4945
    /**
4946
     * Check whether a survey was answered by the current user
4947
     * @param string $surveyCode The survey code
4948
     * @param int $courseId The course ID
4949
     * @return boolean
4950
     */
4951
    public static function isSurveyAnsweredFlagged($surveyCode, $courseId)
4952
    {
4953
        $currenUserId = api_get_user_id();
4954
        $flagToCheck = sprintf("%s-%s-%d", $courseId, $surveyCode, $currenUserId);
4955
4956
        if (!isset($_SESSION['filled_surveys'])) {
4957
            return false;
4958
        }
4959
4960
        if (!is_array($_SESSION['filled_surveys'])) {
4961
            return false;
4962
        }
4963
4964
        foreach ($_SESSION['filled_surveys'] as $flag) {
4965
            if ($flagToCheck != $flag) {
4966
                continue;
4967
            }
4968
4969
            return true;
4970
        }
4971
4972
        return false;
4973
    }
4974
4975
    /**
4976
     * Check if the current survey has answers
4977
     *
4978
     * @param $surveyId
4979
     * @return boolean return true if the survey has answers, false otherwise
4980
     */
4981 View Code Duplication
    public static function checkIfSurveyHasAnswers($surveyId)
4982
    {
4983
        $tableSurveyAnswer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
4984
        $courseId = api_get_course_int_id();
4985
4986
        $sql = "SELECT * FROM $tableSurveyAnswer
4987
                WHERE
4988
                    c_id = $courseId AND
4989
                    survey_id='".$surveyId."'
4990
                ORDER BY answer_id, user ASC";
4991
        $result = Database::query($sql);
4992
4993
        $response = Database::affected_rows($result);
4994
4995
        if ($response > 0) {
4996
            return true;
4997
        }
4998
4999
        return false;
5000
    }
5001
}
5002