Completed
Push — 1.10.x ( 4e611e...f6a4a7 )
by Angel Fernando Quiroz
35:03
created

SurveyUtil   F

Complexity

Total Complexity 449

Size/Duplication

Total Lines 3281
Duplicated Lines 8.75 %

Coupling/Cohesion

Components 2
Dependencies 17

Importance

Changes 0
Metric Value
dl 287
loc 3281
rs 0.6314
c 0
b 0
f 0
wmc 449
lcom 2
cbo 17

46 Methods

Rating   Name   Duplication   Size   Complexity  
C comparative_check() 0 28 8
F saveInvitations() 0 113 23
B save_invitation() 0 19 6
A invitationExists() 0 19 1
B send_invitation_mail() 0 68 5
B update_count_invited() 0 29 1
C get_invited_users() 13 63 12
C check_first_last_question() 9 32 8
A remove_answer() 0 12 1
B store_answer() 0 31 3
C check_parameters() 0 57 15
F handle_reporting_actions() 0 36 11
B delete_user_report() 5 35 4
F display_user_report() 11 160 20
F display_question_report() 11 207 33
D display_question_report_score() 4 95 9
F display_complete_report() 0 219 46
C display_complete_report_row() 11 67 14
F export_complete_report() 7 148 23
C export_complete_report_row() 7 57 15
F export_complete_report_xls() 7 189 26
C export_complete_report_row_xls() 0 60 16
F display_comparative_report() 72 222 35
A get_answers_of_question_by_user() 0 19 3
B get_survey_invitations_data() 0 26 2
A get_number_of_survey_invitations() 18 18 1
A save_invite_mail() 0 20 2
A get_invitations() 0 17 2
B display_survey_search_form() 0 42 2
B displaySurveyListForDrh() 9 31 2
B display_survey_list() 9 39 4
B display_survey_list_for_coach() 9 38 3
C modify_filter() 6 45 7
A modify_filter_for_coach() 0 13 1
A anonymous_filter() 0 8 2
B survey_search_restriction() 0 19 6
A get_number_of_surveys() 0 17 2
A get_number_of_surveys_for_coach() 0 5 1
C get_survey_data() 0 100 8
B get_survey_data_for_coach() 0 62 7
F getSurveyList() 0 114 15
F make_field_list() 79 139 27
B show_link_available() 0 38 3
B drawChart() 0 55 7
A flagSurveyAsAnswered() 0 11 2
B isSurveyAnsweredFlagged() 0 23 5

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like SurveyUtil often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use SurveyUtil, and based on these observations, apply Extract Interface, too.

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CourseBundle\Entity\CSurveyInvitation,
5
    Doctrine\Common\Collections\Criteria;
6
7
/**
8
 * Class SurveyManager
9
 * @package chamilo.survey
10
 * @author Patrick Cool <[email protected]>, Ghent University:
11
 * cleanup, refactoring and rewriting large parts (if not all) of the code
12
 * @author Julio Montoya <[email protected]>, Personality Test modification
13
 * and rewriting large parts of the code
14
 * @author cfasanando
15
 * @todo move this file to inc/lib
16
 * @todo use consistent naming for the functions (save vs store for instance)
17
 */
18
class SurveyManager
19
{
20
    /**
21
     * @param $code
22
     *
23
     * @return string
24
     */
25
    public static function generate_unique_code($code)
26
    {
27
        if (empty($code)) {
28
            return false;
29
        }
30
        $course_id = api_get_course_int_id();
31
        $table_survey = Database::get_course_table(TABLE_SURVEY);
32
        $code = Database::escape_string($code);
33
        $num = 0;
34
        $new_code = $code;
35
        while (true) {
36
            $sql = "SELECT * FROM $table_survey
37
                    WHERE code = '$new_code' AND c_id = $course_id";
38
            $result = Database::query($sql);
39
            if (Database::num_rows($result)) {
40
                $num++;
41
                $new_code = $code . $num;
42
            } else {
43
                break;
44
            }
45
        }
46
        return $code.$num;
47
    }
48
49
    /**
50
     * Deletes all survey invitations of a user
51
     * @param int $user_id
52
     *
53
     * @return boolean
54
     * @assert ('') === false
55
     */
56
    public static function delete_all_survey_invitations_by_user($user_id)
57
    {
58
        $user_id = intval($user_id);
59
60
        if (empty($user_id)) {
61
            return false;
62
        }
63
        $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
64
        $table_survey = Database :: get_course_table(TABLE_SURVEY);
65
66
        $sql = "SELECT survey_invitation_id, survey_code
67
                FROM $table_survey_invitation WHERE user = '$user_id' AND c_id <> 0 ";
68
        $result = Database::query($sql);
69
        while ($row = Database::fetch_array($result ,'ASSOC')){
70
            $survey_invitation_id = $row['survey_invitation_id'];
71
            $survey_code = $row['survey_code'];
72
            $sql2 = "DELETE FROM $table_survey_invitation
73
                    WHERE survey_invitation_id = '$survey_invitation_id' AND c_id <> 0";
74
            if (Database::query($sql2)) {
75
                $sql3 = "UPDATE $table_survey SET
76
                            invited = invited-1
77
                        WHERE c_id <> 0 AND code ='$survey_code'";
78
                Database::query($sql3);
79
            }
80
        }
81
    }
82
83
    /**
84
     *
85
     * @param string $course_code
86
     * @param int $session_id
87
     * @return type
88
     * @assert ('') === false
89
     */
90
    public static function get_surveys($course_code, $session_id = 0)
91
    {
92
        $table_survey = Database :: get_course_table(TABLE_SURVEY);
93
        if (empty($course_code)) {
94
            return false;
95
        }
96
        $course_info = api_get_course_info($course_code);
97
        $session_condition = api_get_session_condition($session_id, true, true);
98
99
        $sql = "SELECT * FROM $table_survey
100
                WHERE c_id = {$course_info['real_id']} $session_condition ";
101
        $result = Database::query($sql);
102
        $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...
103
        return $result;
104
    }
105
106
    /**
107
     * Retrieves all the survey information
108
     *
109
     * @param integer $survey_id the id of the survey
110
     * @param boolean $shared this parameter determines if
111
     * we have to get the information of a survey from the central (shared) database or from the
112
     * 		  course database
113
     * @param string course code optional
114
     *
115
     * @author Patrick Cool <[email protected]>, Ghent University
116
     * @version February 2007
117
     * @assert ('') === false
118
     *
119
     * @todo this is the same function as in create_new_survey.php
120
     */
121
    public static function get_survey($survey_id, $shared = 0, $course_code = '', $simple_return = false)
122
    {
123
        // Table definition
124
        if (!empty($course_code)) {
125
            $my_course_id = $course_code;
126
        } else if (isset($_GET['course'])) {
127
            $my_course_id = Security::remove_XSS($_GET['course']);
128
        } else {
129
            $my_course_id = api_get_course_id();
130
        }
131
        $my_course_info = api_get_course_info($my_course_id);
132
        $table_survey = Database :: get_course_table(TABLE_SURVEY);
133
134
        if ($shared != 0) {
135
            $table_survey	= Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
136
            $sql = "SELECT * FROM $table_survey
137
                    WHERE survey_id='".intval($survey_id)."' ";
138
        } else {
139
            $sql = "SELECT * FROM $table_survey
140
		            WHERE
141
		                survey_id='".intval($survey_id)."' AND
142
		                c_id = ".$my_course_info['real_id'];
143
        }
144
145
        $result = Database::query($sql);
146
        $return = array();
147
148
        if (Database::num_rows($result)> 0) {
149
            $return = Database::fetch_array($result,'ASSOC');
150
            if ($simple_return) {
151
                return $return;
152
            }
153
            // We do this (temporarily) to have the array match the quickform elements immediately
154
            // idealiter the fields in the db match the quickform fields
155
            $return['survey_code'] = $return['code'];
156
            $return['survey_title'] = $return['title'];
157
            $return['survey_subtitle'] = $return['subtitle'];
158
            $return['survey_language'] = $return['lang'];
159
            $return['start_date'] = $return['avail_from'];
160
            $return['end_date'] = $return['avail_till'];
161
            $return['survey_share'] = $return['is_shared'];
162
            $return['survey_introduction'] = $return['intro'];
163
            $return['survey_thanks'] = $return['surveythanks'];
164
            $return['survey_type'] = $return['survey_type'];
165
            $return['one_question_per_page'] = $return['one_question_per_page'];
166
            $return['show_form_profile'] = $return['show_form_profile'];
167
            $return['input_name_list'] = isset($return['input_name_list']) ? $return['input_name_list'] : null;
168
            $return['shuffle'] = $return['shuffle'];
169
            $return['parent_id'] = $return['parent_id'];
170
            $return['survey_version'] = $return['survey_version'];
171
            $return['anonymous'] = $return['anonymous'];
172
        }
173
174
        return $return;
175
    }
176
177
    /**
178
     * This function stores a survey in the database.
179
     *
180
     * @param array $values
181
     *
182
     * @return array $return the type of return message that has to be displayed and the message in it
183
     *
184
     * @author Patrick Cool <[email protected]>, Ghent University
185
     * @version February 2007
186
     */
187
    public static function store_survey($values)
188
    {
189
        $_user = api_get_user_info();
190
        $course_id = api_get_course_int_id();
191
        $session_id = api_get_session_id();
192
        $courseCode = api_get_course_id();
193
        $table_survey 	= Database :: get_course_table(TABLE_SURVEY);
194
        $shared_survey_id = 0;
195
196
        if (!isset($values['survey_id'])) {
197
            // Check if the code doesn't soon exists in this language
198
            $sql = 'SELECT 1 FROM '.$table_survey.'
199
			        WHERE
200
			            c_id = '.$course_id.' AND
201
			            code="'.Database::escape_string($values['survey_code']).'" AND
202
			            lang="'.Database::escape_string($values['survey_language']).'"';
203
            $rs = Database::query($sql);
204 View Code Duplication
            if (Database::num_rows($rs) > 0) {
205
                Display::addFlash(
206
                    Display::return_message(
207
                        get_lang('ThisSurveyCodeSoonExistsInThisLanguage'),
208
                        'error'
209
                    )
210
                );
211
                $return['type'] = 'error';
212
                $return['id'] = isset($values['survey_id']) ? $values['survey_id'] : 0;
213
214
                return $return;
215
            }
216
217
            if (!isset($values['anonymous'])) {
218
                $values['anonymous'] = 0;
219
            }
220
221
            $values['anonymous'] = intval($values['anonymous']);
222
            $additional['columns'] = '';
223
            $extraParams = [];
224
225
            if ($values['anonymous'] == 0) {
226
                // Input_name_list
227
                $values['show_form_profile'] = isset($values['show_form_profile']) ? $values['show_form_profile'] : 0;
228
                $extraParams['show_form_profile'] = $values['show_form_profile'];
229
230
                if ($values['show_form_profile'] == 1) {
231
                    // Input_name_list
232
                    $fields = explode(',', $values['input_name_list']);
233
                    $field_values = '';
234
                    foreach ($fields as & $field) {
235
                        if ($field != '') {
236
                            if ($values[$field] == '') {
237
                                $values[$field] = 0;
238
                            }
239
                            $field_values.= $field.':'.$values[$field].'@';
240
                        }
241
                    }
242
                    $extraParams['form_fields'] = $field_values;
243
                } else {
244
                    $extraParams['form_fields'] = '';
245
                }
246
            } else {
247
                // Input_name_list
248
                $extraParams['show_form_profile'] = 0;
249
                $extraParams['form_fields'] = '';
250
            }
251
252
            if ($values['survey_type'] == 1) {
253
                $extraParams['survey_type'] = 1;
254
                $extraParams['shuffle'] = $values['shuffle'];
255
                $extraParams['one_question_per_page'] = $values['one_question_per_page'];
256
                $extraParams['parent_id'] = $values['parent_id'];
257
258
                // Logic for versioning surveys
259
                if (!empty($values['parent_id'])) {
260
                    $versionValue = '';
261
                    $sql = 'SELECT survey_version
262
                            FROM '.$table_survey.'
263
					        WHERE
264
					            c_id = '.$course_id.' AND
265
					            parent_id = '.intval($values['parent_id']).'
266
                            ORDER BY survey_version DESC
267
                            LIMIT 1';
268
                    $rs = Database::query($sql);
269
                    if (Database::num_rows($rs) === 0) {
270
                        $sql = 'SELECT survey_version FROM '.$table_survey.'
271
						        WHERE
272
						            c_id = '.$course_id.' AND
273
						            survey_id = '.intval($values['parent_id']);
274
                        $rs = Database::query($sql);
275
                        $getversion = Database::fetch_array($rs, 'ASSOC');
276
                        if (empty($getversion['survey_version'])) {
277
                            $versionValue = ++$getversion['survey_version'];
278
                        } else {
279
                            $versionValue = $getversion['survey_version'];
280
                        }
281
                    } else {
282
                        $row = Database::fetch_array($rs, 'ASSOC');
283
                        $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...
284
                        if ($pos === false) {
285
                            $row['survey_version'] = $row['survey_version'] + 1;
286
                            $versionValue = $row['survey_version'];
287
                        } else {
288
                            $getlast = explode('\.', $row['survey_version']);
289
                            $lastversion = array_pop($getlast);
290
                            $lastversion = $lastversion + 1;
291
                            $add = implode('.', $getlast);
292
                            if ($add != '') {
293
                                $insertnewversion = $add.'.'.$lastversion;
294
                            } else {
295
                                $insertnewversion = $lastversion;
296
                            }
297
                            $versionValue = $insertnewversion;
298
                        }
299
                    }
300
                    $extraParams['survey_version'] = $versionValue;
301
                }
302
            }
303
304
            $params = [
305
                'c_id' => $course_id,
306
                'code' => strtolower(CourseManager::generate_course_code($values['survey_code'])),
307
                'title' => $values['survey_title'],
308
                'subtitle' => $values['survey_subtitle'],
309
                'author' => $_user['user_id'],
310
                'lang' => $values['survey_language'],
311
                'avail_from' => $values['start_date'],
312
                'avail_till' => $values['end_date'],
313
                'is_shared' => $shared_survey_id,
314
                'template' => 'template',
315
                'intro' => $values['survey_introduction'],
316
                'surveythanks' => $values['survey_thanks'],
317
                'creation_date' => api_get_utc_datetime(),
318
                'anonymous' => $values['anonymous'],
319
                'session_id' => api_get_session_id(),
320
                'visible_results' => $values['visible_results']
321
            ];
322
323
            $params = array_merge($params, $extraParams);
324
            $survey_id = Database::insert($table_survey, $params);
325 View Code Duplication
            if ($survey_id > 0) {
326
327
                $sql = "UPDATE $table_survey SET survey_id = $survey_id
328
                        WHERE iid = $survey_id";
329
                Database::query($sql);
330
331
                // Insert into item_property
332
                api_item_property_update(
333
                    api_get_course_info(),
334
                    TOOL_SURVEY,
335
                    $survey_id,
336
                    'SurveyAdded',
337
                    api_get_user_id()
338
                );
339
            }
340
341
            if ($values['survey_type'] == 1 && !empty($values['parent_id'])) {
342
                SurveyManager::copy_survey($values['parent_id'], $survey_id);
343
            }
344
345
            Display::addFlash(
346
                Display::return_message(
347
                    get_lang('SurveyCreatedSuccesfully'),
348
                    'success'
349
                )
350
            );
351
            $return['id'] = $survey_id;
352
        } else {
353
            // Check whether the code doesn't soon exists in this language
354
            $sql = 'SELECT 1 FROM '.$table_survey.'
355
			        WHERE
356
			            c_id = '.$course_id.' AND
357
			            code = "'.Database::escape_string($values['survey_code']).'" AND
358
			            lang = "'.Database::escape_string($values['survey_language']).'" AND
359
			            survey_id !='.intval($values['survey_id']);
360
            $rs = Database::query($sql);
361 View Code Duplication
            if (Database::num_rows($rs) > 0) {
362
                Display::addFlash(
363
                    Display::return_message(
364
                        get_lang('ThisSurveyCodeSoonExistsInThisLanguage'),
365
                        'error'
366
                    )
367
                );
368
                $return['type'] = 'error';
369
                $return['id'] = isset($values['survey_id']) ? $values['survey_id'] : 0;
370
                return $return;
371
            }
372
373
            if (!isset($values['anonymous']) ||
374
                (isset($values['anonymous']) && $values['anonymous'] == '')
375
            ) {
376
                $values['anonymous'] = 0;
377
            }
378
379
            $values['shuffle'] = isset($values['shuffle']) ? $values['shuffle'] : null;
380
            $values['one_question_per_page'] = isset($values['one_question_per_page']) ? $values['one_question_per_page'] : null;
381
            $values['show_form_profile'] = isset($values['show_form_profile']) ? $values['show_form_profile'] : null;
382
383
            $extraParams = [];
384
            $extraParams['shuffle'] = $values['shuffle'];
385
            $extraParams['one_question_per_page'] = $values['one_question_per_page'];
386
            $extraParams['shuffle'] = $values['shuffle'];
387
388
            if ($values['anonymous'] == 0) {
389
                $extraParams['show_form_profile'] = $values['show_form_profile'];
390
                if ($values['show_form_profile'] == 1) {
391
                    $fields = explode(',',$values['input_name_list']);
392
                    $field_values = '';
393
                    foreach ($fields as &$field) {
394
                        if ($field != '') {
395
                            if (!isset($values[$field]) ||
396
                                (isset($values[$field]) && $values[$field] == '')
397
                            ) {
398
                                $values[$field] = 0;
399
                            }
400
                            $field_values.= $field.':'.$values[$field].'@';
401
                        }
402
                    }
403
                    $extraParams['form_fields'] = $field_values;
404
                } else {
405
                    $extraParams['form_fields'] = '';
406
                }
407
            } else {
408
                $extraParams['show_form_profile'] = 0;
409
                $extraParams['form_fields'] = '';
410
            }
411
412
            $params = [
413
                'title' => $values['survey_title'],
414
                'subtitle' => $values['survey_subtitle'],
415
                'author' => $_user['user_id'],
416
                'lang' => $values['survey_language'],
417
                'avail_from' => $values['start_date'],
418
                'avail_till' => $values['end_date'],
419
                'is_shared' => $shared_survey_id,
420
                'template' => 'template',
421
                'intro' => $values['survey_introduction'],
422
                'surveythanks' => $values['survey_thanks'],
423
                'anonymous' => $values['anonymous'],
424
                'session_id' => api_get_session_id(),
425
                'visible_results' => $values['visible_results'],
426
            ];
427
428
            $params = array_merge($params, $extraParams);
429
            Database::update(
430
                $table_survey,
431
                $params,
432
                [
433
                    'c_id = ? AND survey_id = ?' => [
434
                        $course_id,
435
                        $values['survey_id'],
436
                    ],
437
                ]
438
            );
439
440
            // Update into item_property (update)
441
            api_item_property_update(
442
                api_get_course_info(),
443
                TOOL_SURVEY,
444
                $values['survey_id'],
445
                'SurveyUpdated',
446
                api_get_user_id()
447
            );
448
449
            Display::addFlash(
450
                Display::return_message(
451
                    get_lang('SurveyUpdatedSuccesfully'),
452
                    'confirmation'
453
                )
454
            );
455
456
            $return['id'] = $values['survey_id'];
457
        }
458
459
        $survey_id = intval($return['id']);
460
461
        // Gradebook
462
        $gradebook_option = false;
463
        if (isset($values['survey_qualify_gradebook'])) {
464
            $gradebook_option = $values['survey_qualify_gradebook'] > 0;
465
        }
466
467
        $gradebook_link_type = 8;
468
469
        $link_info = GradebookUtils::is_resource_in_course_gradebook(
470
            $courseCode,
471
            $gradebook_link_type,
472
            $survey_id,
473
            $session_id
474
        );
475
476
        $gradebook_link_id = isset($link_info['id']) ? $link_info['id'] : false;
477
478
        if ($gradebook_option) {
479
            if ($survey_id > 0) {
480
                $title_gradebook = ''; // Not needed here.
481
                $description_gradebook = ''; // Not needed here.
482
                $survey_weight = floatval($_POST['survey_weight']);
483
                $max_score = 1;
484
485
                if (!$gradebook_link_id) {
486
                    GradebookUtils::add_resource_to_course_gradebook(
487
                        $values['category_id'],
488
                        $courseCode,
489
                        $gradebook_link_type,
490
                        $survey_id,
491
                        $title_gradebook,
492
                        $survey_weight,
493
                        $max_score,
494
                        $description_gradebook,
495
                        1,
496
                        $session_id
497
                    );
498
                } else {
499
                    GradebookUtils::update_resource_from_course_gradebook(
500
                        $gradebook_link_id,
501
                        $courseCode,
502
                        $survey_weight
503
                    );
504
                }
505
            }
506
        } else {
507
            // Delete everything of the gradebook for this $linkId
508
            GradebookUtils::remove_resource_from_course_gradebook($gradebook_link_id);
509
510
            //comenting this line to correctly return the function msg
511
            //exit;
512
        }
513
514
        return $return;
515
    }
516
517
    /**
518
     * This function stores a shared survey in the central database.
519
     *
520
     * @param array $values
521
     * @return array $return the type of return message that has to be displayed and the message in it
522
     *
523
     * @author Patrick Cool <[email protected]>, Ghent University
524
     * @version February 2007
525
     */
526
    public function store_shared_survey($values)
527
    {
528
        $_user = api_get_user_info();
529
        $_course = api_get_course_info();
530
531
        // Table definitions
532
        $table_survey	= Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY);
533
534
        if (!$values['survey_id'] ||
535
            !is_numeric($values['survey_id']) ||
536
            $values['survey_share']['survey_share'] == 'true'
537
        ) {
538
            $sql = "INSERT INTO $table_survey (code, title, subtitle, author, lang, template, intro, surveythanks, creation_date, course_code) VALUES (
539
                    '".Database::escape_string($values['survey_code'])."',
540
                    '".Database::escape_string($values['survey_title'])."',
541
                    '".Database::escape_string($values['survey_subtitle'])."',
542
                    '".intval($_user['user_id'])."',
543
                    '".Database::escape_string($values['survey_language'])."',
544
                    '".Database::escape_string('template')."',
545
                    '".Database::escape_string($values['survey_introduction'])."',
546
                    '".Database::escape_string($values['survey_thanks'])."',
547
                    '".api_get_utc_datetime()."',
548
                    '".$_course['id']."')";
549
            Database::query($sql);
550
            $return	= Database::insert_id();
551
552
            $sql = "UPDATE $table_survey SET survey_id = $return WHERE iid = $return";
553
            Database::query($sql);
554
555
        } else {
556
            $sql = "UPDATE $table_survey SET
557
                        code 			= '".Database::escape_string($values['survey_code'])."',
558
                        title 			= '".Database::escape_string($values['survey_title'])."',
559
                        subtitle 		= '".Database::escape_string($values['survey_subtitle'])."',
560
                        author 			= '".intval($_user['user_id'])."',
561
                        lang 			= '".Database::escape_string($values['survey_language'])."',
562
                        template 		= '".Database::escape_string('template')."',
563
                        intro			= '".Database::escape_string($values['survey_introduction'])."',
564
                        surveythanks	= '".Database::escape_string($values['survey_thanks'])."'
565
					WHERE survey_id = '".Database::escape_string($values['survey_share']['survey_share'])."'";
566
            Database::query($sql);
567
            $return	= $values['survey_share']['survey_share'];
568
        }
569
570
        return $return;
571
    }
572
573
    /**
574
     * This function deletes a survey (and also all the question in that survey
575
     *
576
     * @param int $survey_id id of the survey that has to be deleted
577
     * @return true
578
     *
579
     * @author Patrick Cool <[email protected]>, Ghent University
580
     * @version January 2007
581
     */
582
    public static function delete_survey($survey_id, $shared = false, $course_id = '')
583
    {
584
        // Database table definitions
585
        if (empty($course_id)) {
586
            $course_id = api_get_course_int_id();
587
        }
588
589
        $survey_id = intval($survey_id);
590
591
        if (empty($survey_id)) {
592
            return false;
593
        }
594
595
        $course_info = api_get_course_info_by_id($course_id);
596
        $course_id   = $course_info['real_id'];
597
598
        $table_survey = Database :: get_course_table(TABLE_SURVEY);
599
        $table_survey_question_group = Database :: get_course_table(TABLE_SURVEY_QUESTION_GROUP);
600
601
        if ($shared) {
602
            $table_survey = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY);
603
            // Deleting the survey
604
            $sql = "DELETE FROM $table_survey
605
                    WHERE survey_id='".$survey_id."'";
606
            Database::query($sql);
607
        } else {
608
            $sql = "DELETE FROM $table_survey
609
                    WHERE c_id = $course_id AND survey_id='".$survey_id."'";
610
            Database::query($sql);
611
        }
612
613
        // Deleting groups of this survey
614
        $sql = "DELETE FROM $table_survey_question_group
615
                WHERE c_id = $course_id AND survey_id='".$survey_id."'";
616
        Database::query($sql);
617
618
        // Deleting the questions of the survey
619
        SurveyManager::delete_all_survey_questions($survey_id, $shared);
620
621
        // Update into item_property (delete)
622
        api_item_property_update(
623
            $course_info,
624
            TOOL_SURVEY,
625
            $survey_id,
626
            'SurveyDeleted',
627
            api_get_user_id()
628
        );
629
        return true;
630
    }
631
632
    /**
633
     * @param int $survey_id
634
     * @param int $new_survey_id
635
     * @param int $targetCourseId
636
     *
637
     * @return bool
638
     */
639
    public static function copy_survey($survey_id, $new_survey_id = null, $targetCourseId = null)
640
    {
641
        $course_id = api_get_course_int_id();
642
        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...
643
            $targetCourseId = $course_id;
644
        }
645
646
        // Database table definitions
647
        $table_survey = Database::get_course_table(TABLE_SURVEY);
648
        $table_survey_question_group = Database::get_course_table(TABLE_SURVEY_QUESTION_GROUP);
649
        $table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
650
        $table_survey_options = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
651
        $survey_id = intval($survey_id);
652
653
        // Get groups
654
        $survey_data = self::get_survey($survey_id, 0, null, true);
655
        if (empty($survey_data)) {
656
            return true;
657
        }
658
659
        if (empty($new_survey_id)) {
660
            $params = $survey_data;
661
            $params['code'] = self::generate_unique_code($params['code']);
662
            $params['c_id'] = $targetCourseId;
663
            unset($params['survey_id']);
664
            $params['session_id'] = api_get_session_id();
665
            $params['title'] = $params['title'] . ' ' . get_lang('Copy');
666
            unset($params['iid']);
667
            Database::insert($table_survey, $params);
668
            $new_survey_id = Database::insert_id();
669
670 View Code Duplication
            if ($new_survey_id) {
671
                $sql = "UPDATE $table_survey SET survey_id = $new_survey_id
672
                        WHERE iid = $new_survey_id";
673
                Database::query($sql);
674
675
                // Insert into item_property
676
                api_item_property_update(
677
                    api_get_course_info(),
678
                    TOOL_SURVEY,
679
                    $new_survey_id,
680
                    'SurveyAdded',
681
                    api_get_user_id()
682
                );
683
            }
684
        } else {
685
            $new_survey_id = intval($new_survey_id);
686
        }
687
688
        $sql = "SELECT * FROM $table_survey_question_group
689
                WHERE c_id = $course_id AND  survey_id='".$survey_id."'";
690
        $res = Database::query($sql);
691
        while($row = Database::fetch_array($res, 'ASSOC')) {
692
            $params = array(
693
                'c_id' =>  $targetCourseId,
694
                'name' => $row['name'],
695
                'description' => $row['description'],
696
                'survey_id' => $new_survey_id
697
            );
698
            $insertId = Database::insert($table_survey_question_group, $params);
699
700
            $sql = "UPDATE $table_survey_question_group SET id = iid
701
                    WHERE iid = $insertId";
702
            Database::query($sql);
703
704
            $group_id[$row['id']] = $insertId;
705
        }
706
707
        // Get questions
708
        $sql = "SELECT * FROM $table_survey_question
709
                WHERE c_id = $course_id AND survey_id='".$survey_id."'";
710
        $res = Database::query($sql);
711
        while ($row = Database::fetch_array($res, 'ASSOC')) {
712
            $params = array(
713
                'c_id' =>  $targetCourseId,
714
                'survey_id' => $new_survey_id,
715
                'survey_question' => $row['survey_question'],
716
                'survey_question_comment' => $row['survey_question_comment'],
717
                'type' => $row['type'],
718
                'display' => $row['display'],
719
                'sort' => $row['sort'],
720
                'shared_question_id' =>  $row['shared_question_id'],
721
                'max_value' =>  $row['max_value'],
722
                'survey_group_pri' =>  $row['survey_group_pri'],
723
                'survey_group_sec1' =>  $row['survey_group_sec1'],
724
                'survey_group_sec2' => $row['survey_group_sec2']
725
            );
726
            $insertId = Database::insert($table_survey_question, $params);
727
            $sql = "UPDATE $table_survey_question SET question_id = iid WHERE iid = $insertId";
728
            Database::query($sql);
729
730
            $question_id[$row['question_id']] = $insertId;
731
        }
732
733
        // Get questions options
734
        $sql = "SELECT * FROM $table_survey_options
735
                WHERE c_id = $course_id AND survey_id='".$survey_id."'";
736
737
        $res = Database::query($sql);
738
        while ($row = Database::fetch_array($res ,'ASSOC')) {
739
            $params = array(
740
                'c_id' =>  $targetCourseId,
741
                'question_id' => $question_id[$row['question_id']],
742
                'survey_id' => $new_survey_id,
743
                'option_text' => $row['option_text'],
744
                'sort' => $row['sort'],
745
                'value' => $row['value']
746
            );
747
            $insertId = Database::insert($table_survey_options, $params);
748
749
            $sql = "UPDATE $table_survey_options SET question_option_id = $insertId
750
                    WHERE iid = $insertId";
751
            Database::query($sql);
752
        }
753
754
        return $new_survey_id;
755
    }
756
757
    /**
758
     * This function duplicates a survey (and also all the question in that survey
759
     *
760
     * @param int $survey_id id of the survey that has to be duplicated
761
     * @param int $courseId id of the course which survey has to be duplicated
762
     * @return true
763
     *
764
     * @author Eric Marguin <[email protected]>, Elixir Interactive
765
     * @version October 2007
766
     */
767
    public static function empty_survey($survey_id, $courseId = null)
768
    {
769
        // Database table definitions
770
        $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
771
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
772
        $table_survey = Database :: get_course_table(TABLE_SURVEY);
773
774
        $course_id = $courseId ? $courseId : api_get_course_int_id();
775
776
        $datas = SurveyManager::get_survey($survey_id);
777
        $session_where = '';
778
        if (api_get_session_id() != 0) {
779
            $session_where = ' AND session_id = "'.api_get_session_id().'" ';
780
        }
781
782
        $sql = 'DELETE FROM '.$table_survey_invitation.'
783
		        WHERE
784
		            c_id = '.$course_id.' AND
785
		            survey_code = "'.Database::escape_string($datas['code']).'" '.$session_where.' ';
786
        Database::query($sql);
787
788
        $sql = 'DELETE FROM '.$table_survey_answer.'
789
		        WHERE c_id = '.$course_id.' AND survey_id='.intval($survey_id);
790
        Database::query($sql);
791
792
        $sql = 'UPDATE '.$table_survey.' SET invited=0, answered=0
793
		        WHERE c_id = '.$course_id.' AND survey_id='.intval($survey_id);
794
        Database::query($sql);
795
796
        return true;
797
    }
798
799
    /**
800
     * This function recalculates the number of people who have taken the survey (=filled at least one question)
801
     *
802
     * @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...
803
     * @return true
804
     *
805
     * @author Patrick Cool <[email protected]>, Ghent University
806
     * @version February 2007
807
     */
808
    public static function update_survey_answered($survey_data, $user, $survey_code)
809
    {
810
        // Database table definitions
811
        $table_survey = Database :: get_course_table(TABLE_SURVEY);
812
        $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
813
814
        $survey_id = $survey_data['survey_id'];
815
        $course_id = $survey_data['c_id'];
816
        $session_id = $survey_data['session_id'];
817
818
        // Getting a list with all the people who have filled the survey
819
        $people_filled = SurveyManager::get_people_who_filled_survey($survey_id, false, $course_id);
820
821
        $number = intval(count($people_filled));
822
823
        // Storing this value in the survey table
824
        $sql = "UPDATE $table_survey
825
		        SET answered = $number
826
		        WHERE
827
                    c_id = $course_id AND
828
		            survey_id = ".intval($survey_id);
829
        Database::query($sql);
830
831
        // Storing that the user has finished the survey.
832
        $sql = "UPDATE $table_survey_invitation SET answered='1'
833
                WHERE
834
                    c_id = $course_id AND
835
                    session_id='".$session_id."' AND
836
                    user='".Database::escape_string($user)."' AND
837
                    survey_code='".Database::escape_string($survey_code)."'";
838
        Database::query($sql);
839
    }
840
841
    /***
842
     * SURVEY QUESTION FUNCTIONS
843
     */
844
845
    /**
846
     * This function return the "icon" of the question type
847
     *
848
     * @author Patrick Cool <[email protected]>, Ghent University
849
     * @version February 2007
850
     */
851
    public static function icon_question($type)
852
    {
853
        // the possible question types
854
        $possible_types = array(
855
            'personality',
856
            'yesno',
857
            'multiplechoice',
858
            'multipleresponse',
859
            'open',
860
            'dropdown',
861
            'comment',
862
            'pagebreak',
863
            'percentage',
864
            'score',
865
        );
866
867
        // the images array
868
        $icon_question = array(
869
            'yesno' => 'yesno.png',
870
            'personality' => 'yesno.png',
871
            'multiplechoice' => 'mcua.png',
872
            'multipleresponse' => 'mcma.png',
873
            'open' => 'open_answer.png',
874
            'dropdown' => 'dropdown.png',
875
            'percentage' => 'percentagequestion.png',
876
            'score' => 'scorequestion.png',
877
            'comment' => 'commentquestion.png',
878
            'pagebreak' => 'page_end.png',
879
        );
880
881
        if (in_array($type, $possible_types)) {
882
            return $icon_question[$type];
883
        } else {
884
            return false;
885
        }
886
    }
887
888
    /**
889
     * This function retrieves all the information of a question
890
     *
891
     * @param integer $question_id the id of the question
892
     * @return array
893
     *
894
     * @author Patrick Cool <[email protected]>, Ghent University
895
     * @version January 2007
896
     *
897
     * @todo one sql call should do the trick
898
     */
899
    public static function get_question($question_id, $shared = false)
900
    {
901
        // Table definitions
902
        $tbl_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
903
        $table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
904
        $course_id = api_get_course_int_id();
905
906
        $sql = "SELECT * FROM $tbl_survey_question
907
                WHERE c_id = $course_id AND question_id='".intval($question_id)."'
908
                ORDER BY `sort` ";
909
910
        $sqlOption = "  SELECT * FROM $table_survey_question_option
911
                        WHERE c_id = $course_id AND question_id='".intval($question_id)."'
912
                        ORDER BY `sort` ";
913
914
        if ($shared) {
915
            $tbl_survey_question = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
916
            $table_survey_question_option = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
917
918
            $sql = "SELECT * FROM $tbl_survey_question
919
                    WHERE question_id='".intval($question_id)."'
920
                    ORDER BY `sort` ";
921
            $sqlOption = "SELECT * FROM $table_survey_question_option
922
                          WHERE question_id='".intval($question_id)."'
923
                          ORDER BY `sort` ";
924
        }
925
926
        // Getting the information of the question
927
928
        $result = Database::query($sql);
929
        $row = Database::fetch_array($result,'ASSOC');
930
931
        $return['survey_id'] = $row['survey_id'];
932
        $return['question_id'] = $row['question_id'];
933
        $return['type'] = $row['type'];
934
        $return['question'] = $row['survey_question'];
935
        $return['horizontalvertical'] = $row['display'];
936
        $return['shared_question_id'] = $row['shared_question_id'];
937
        $return['maximum_score'] = $row['max_value'];
938
939
        if ($row['survey_group_pri'] != 0) {
940
            $return['assigned'] = $row['survey_group_pri'];
941
            $return['choose'] = 1;
942 View Code Duplication
        } else {
943
            $return['assigned1'] = $row['survey_group_sec1'];
944
            $return['assigned2'] = $row['survey_group_sec2'];
945
            $return['choose'] = 2;
946
        }
947
948
        // Getting the information of the question options
949
950
        $result = Database::query($sqlOption);
951 View Code Duplication
        while ($row = Database::fetch_array($result, 'ASSOC')) {
952
            /** @todo this should be renamed to options instead of answers */
953
            $return['answers'][] = $row['option_text'];
954
            $return['values'][] = $row['value'];
955
956
            /** @todo this can be done more elegantly (used in reporting) */
957
            $return['answersid'][] = $row['question_option_id'];
958
        }
959
960
        return $return;
961
    }
962
963
    /**
964
     * This function gets all the question of any given survey
965
     *
966
     * @param integer $survey_id the id of the survey
967
     * @return array containing all the questions of the survey
968
     *
969
     * @author Patrick Cool <[email protected]>, Ghent University
970
     * @version February 2007
971
     *
972
     * @todo one sql call should do the trick
973
     */
974
    public static function get_questions($survey_id, $course_id = '')
975
    {
976
        // Table definitions
977
        $tbl_survey_question 			= Database :: get_course_table(TABLE_SURVEY_QUESTION);
978
        $table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
979
980
        if (empty($course_id)) {
981
            $course_id = api_get_course_int_id();
982
        }
983
984
        $return = array();
985
986
        // Getting the information of the question
987
        $sql = "SELECT * FROM $tbl_survey_question
988
		        WHERE c_id = $course_id AND survey_id='".intval($survey_id)."'";
989
        $result = Database::query($sql);
990
        $return = array();
991
        while ($row = Database::fetch_array($result, 'ASSOC')) {
992
            $return[$row['question_id']]['survey_id'] = $row['survey_id'];
993
            $return[$row['question_id']]['question_id'] = $row['question_id'];
994
            $return[$row['question_id']]['type'] = $row['type'];
995
            $return[$row['question_id']]['question'] = $row['survey_question'];
996
            $return[$row['question_id']]['horizontalvertical'] = $row['display'];
997
            $return[$row['question_id']]['maximum_score'] = $row['max_value'];
998
            $return[$row['question_id']]['sort'] = $row['sort'];
999
        }
1000
1001
        // Getting the information of the question options
1002
        $sql = "SELECT * FROM $table_survey_question_option
1003
		        WHERE c_id = $course_id AND survey_id='".intval($survey_id)."'";
1004
        $result = Database::query($sql);
1005
        while ($row = Database::fetch_array($result, 'ASSOC')) {
1006
            $return[$row['question_id']]['answers'][] = $row['option_text'];
1007
        }
1008
1009
        return $return;
1010
    }
1011
1012
    /**
1013
     * This function saves a question in the database.
1014
     * This can be either an update of an existing survey or storing a new survey
1015
     * @param array $survey_data
1016
     * @param array $form_content all the information of the form
1017
     *
1018
     * @author Patrick Cool <[email protected]>, Ghent University
1019
     * @version January 2007
1020
     */
1021
    public static function save_question($survey_data, $form_content)
1022
    {
1023
        $return_message = '';
1024
1025
        if (strlen($form_content['question']) > 1) {
1026
            // Checks length of the question
1027
            $empty_answer = false;
1028
1029
            if ($survey_data['survey_type'] == 1) {
1030
                if (empty($form_content['choose'])) {
1031
                    $return_message = 'PleaseChooseACondition';
1032
                    return $return_message;
1033
                }
1034
1035
                if (($form_content['choose'] == 2) &&
1036
                    ($form_content['assigned1'] == $form_content['assigned2'])
1037
                ) {
1038
                    $return_message = 'ChooseDifferentCategories';
1039
                    return $return_message;
1040
                }
1041
            }
1042
1043
            if ($form_content['type'] != 'percentage') {
1044
                if (isset($form_content['answers'])) {
1045
                    for ($i = 0; $i < count($form_content['answers']); $i++) {
1046
                        if (strlen($form_content['answers'][$i]) < 1) {
1047
                            $empty_answer = true;
1048
                            break;
1049
                        }
1050
                    }
1051
                }
1052
            }
1053
1054
            if ($form_content['type'] == 'score') {
1055
                if (strlen($form_content['maximum_score']) < 1) {
1056
                    $empty_answer = true;
1057
                }
1058
            }
1059
            $additional = array();
1060
            $course_id = api_get_course_int_id();
1061
1062
            if (!$empty_answer) {
1063
                // Table definitions
1064
                $tbl_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
1065
1066
                // Getting all the information of the survey
1067
                $survey_data = SurveyManager::get_survey($form_content['survey_id']);
1068
1069
                // Storing the question in the shared database
1070
                if (is_numeric($survey_data['survey_share']) && $survey_data['survey_share'] != 0) {
1071
                    $shared_question_id = SurveyManager::save_shared_question($form_content, $survey_data);
1072
                    $form_content['shared_question_id'] = $shared_question_id;
1073
                }
1074
1075
                // Storing a new question
1076
                if ($form_content['question_id'] == '' || !is_numeric($form_content['question_id'])) {
1077
                    // Finding the max sort order of the questions in the given survey
1078
                    $sql = "SELECT max(sort) AS max_sort
1079
					        FROM $tbl_survey_question
1080
                            WHERE c_id = $course_id AND survey_id='".intval($form_content['survey_id'])."'";
1081
                    $result = Database::query($sql);
1082
                    $row = Database::fetch_array($result,'ASSOC');
1083
                    $max_sort = $row['max_sort'];
1084
1085
                    // Some variables defined for survey-test type
1086
                    $extraParams = [];
1087
                    if (isset($_POST['choose'])) {
1088
                        if ($_POST['choose'] == 1) {
1089
                            $extraParams['survey_group_pri'] = $_POST['assigned'];
1090 View Code Duplication
                        } elseif ($_POST['choose'] == 2) {
1091
                            $extraParams['survey_group_sec1'] = $_POST['assigned1'];
1092
                            $extraParams['survey_group_sec2'] = $_POST['assigned2'];
1093
                        }
1094
                    }
1095
1096
                    $questionComment = isset($form_content['question_comment']) ? $form_content['question_comment'] : '';
1097
                    $maxScore = isset($form_content['maximum_score']) ? $form_content['maximum_score'] : '';
1098
                    $display = isset($form_content['horizontalvertical']) ? $form_content['horizontalvertical'] : '';
1099
1100
                    $params = [
1101
                        'c_id' => $course_id,
1102
                        'survey_id' => $form_content['survey_id'],
1103
                        'survey_question' => $form_content['question'],
1104
                        'survey_question_comment' => $questionComment,
1105
                        'type' => $form_content['type'],
1106
                        'display' => $display,
1107
                        'sort' => $max_sort + 1,
1108
                        'shared_question_id' => $form_content['shared_question_id'],
1109
                        'max_value' => $maxScore,
1110
                    ];
1111
1112
                    $params = array_merge($params, $extraParams);
1113
                    $question_id = Database::insert($tbl_survey_question, $params);
1114
                    if ($question_id) {
1115
1116
                        $sql = "UPDATE $tbl_survey_question SET question_id = $question_id
1117
                                WHERE iid = $question_id";
1118
                        Database::query($sql);
1119
1120
                        $form_content['question_id'] = $question_id;
1121
                        $return_message = 'QuestionAdded';
1122
                    }
1123
                } else {
1124
                    // Updating an existing question
1125
1126
                    $extraParams = [];
1127
1128
                    if (isset($_POST['choose'])) {
1129
                        if ($_POST['choose'] == 1) {
1130
                            $extraParams['survey_group_pri'] = $_POST['assigned'];
1131
                            $extraParams['survey_group_sec1'] = 0;
1132
                            $extraParams['survey_group_sec2'] = 0;
1133 View Code Duplication
                        } elseif ($_POST['choose'] == 2) {
1134
                            $extraParams['survey_group_pri'] = 0;
1135
                            $extraParams['survey_group_sec1'] = $_POST['assigned1'];
1136
                            $extraParams['survey_group_sec2'] = $_POST['assigned2'];
1137
                        }
1138
                    }
1139
1140
                    $maxScore = isset($form_content['maximum_score']) ? $form_content['maximum_score'] : null;
1141
                    $questionComment = isset($form_content['question_comment']) ? $form_content['question_comment'] : null;
1142
1143
                    // Adding the question to the survey_question table
1144
                    $params = [
1145
                        'survey_question' => $form_content['question'],
1146
                        'survey_question_comment' => $questionComment,
1147
                        'display' => $form_content['horizontalvertical'],
1148
                    ];
1149
1150
                    $params = array_merge($params, $extraParams);
1151
1152
                    Database::update(
1153
                        $tbl_survey_question,
1154
                        $params,
1155
                        [
1156
                            'c_id = ? AND question_id = ?' => [
1157
                                $course_id,
1158
                                $form_content['question_id'],
1159
                            ],
1160
                        ]
1161
                    );
1162
1163
                    $return_message = 'QuestionUpdated';
1164
                }
1165
1166
                if (!empty($form_content['survey_id'])) {
1167
                    //Updating survey
1168
                    api_item_property_update(
1169
                        api_get_course_info(),
1170
                        TOOL_SURVEY,
1171
                        $form_content['survey_id'],
1172
                        'SurveyUpdated',
1173
                        api_get_user_id()
1174
                    );
1175
                }
1176
1177
                // Storing the options of the question
1178
                SurveyManager::save_question_options($form_content, $survey_data);
1179
            } else {
1180
                $return_message = 'PleasFillAllAnswer';
1181
            }
1182
        } else {
1183
            $return_message = 'PleaseEnterAQuestion';
1184
        }
1185
1186
        if (!empty($return_message)) {
1187
            Display::addFlash(Display::return_message(get_lang($return_message)));
1188
        }
1189
        return $return_message;
1190
    }
1191
1192
    /**
1193
    * This function saves the question in the shared database
1194
    *
1195
    * @param array $form_content all the information of the form
1196
    * @param array $survey_data all the information of the survey
1197
    *
1198
    * @author Patrick Cool <[email protected]>, Ghent University
1199
    * @version February 2007
1200
    *
1201
    * @todo editing of a shared question
1202
    */
1203
    public function save_shared_question($form_content, $survey_data)
1204
    {
1205
        $_course = api_get_course_info();
1206
1207
        // Table definitions
1208
        $tbl_survey_question = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
1209
1210
        // Storing a new question
1211
        if ($form_content['shared_question_id'] == '' ||
1212
            !is_numeric($form_content['shared_question_id'])
1213
        ) {
1214
            // Finding the max sort order of the questions in the given survey
1215
            $sql = "SELECT max(sort) AS max_sort FROM $tbl_survey_question
1216
                    WHERE survey_id='".intval($survey_data['survey_share'])."'
1217
                    AND code='".Database::escape_string($_course['id'])."'";
1218
            $result = Database::query($sql);
1219
            $row = Database::fetch_array($result,'ASSOC');
1220
            $max_sort = $row['max_sort'];
1221
1222
            // Adding the question to the survey_question table
1223
            $sql = "INSERT INTO $tbl_survey_question (survey_id, survey_question, survey_question_comment, type, display, sort, code) VALUES (
1224
                    '".Database::escape_string($survey_data['survey_share'])."',
1225
                    '".Database::escape_string($form_content['question'])."',
1226
                    '".Database::escape_string($form_content['question_comment'])."',
1227
                    '".Database::escape_string($form_content['type'])."',
1228
                    '".Database::escape_string($form_content['horizontalvertical'])."',
1229
                    '".Database::escape_string($max_sort+1)."',
1230
                    '".Database::escape_string($_course['id'])."')";
1231
            Database::query($sql);
1232
            $shared_question_id = Database::insert_id();
1233
        }  else {
1234
            // Updating an existing question
1235
            // adding the question to the survey_question table
1236
            $sql = "UPDATE $tbl_survey_question SET
1237
                        survey_question = '".Database::escape_string($form_content['question'])."',
1238
                        survey_question_comment = '".Database::escape_string($form_content['question_comment'])."',
1239
                        display = '".Database::escape_string($form_content['horizontalvertical'])."'
1240
                    WHERE
1241
                        question_id = '".intval($form_content['shared_question_id'])."' AND
1242
                        code = '".Database::escape_string($_course['id'])."'";
1243
            Database::query($sql);
1244
            $shared_question_id = $form_content['shared_question_id'];
1245
        }
1246
1247
        return $shared_question_id;
1248
    }
1249
1250
    /**
1251
     * This functions moves a question of a survey up or down
1252
     *
1253
     * @param string $direction
1254
     * @param integer $survey_question_id
1255
     * @param integer $survey_id
1256
     *
1257
     * @author Patrick Cool <[email protected]>, Ghent University
1258
     * @version January 2007
1259
     */
1260
    public static function move_survey_question($direction, $survey_question_id, $survey_id)
1261
    {
1262
        // Table definition
1263
        $table_survey_question 	= Database :: get_course_table(TABLE_SURVEY_QUESTION);
1264
        $course_id = api_get_course_int_id();
1265
1266
        if ($direction == 'moveup') {
1267
            $sort = 'DESC';
1268
        }
1269
        if ($direction == 'movedown') {
1270
            $sort = 'ASC';
1271
        }
1272
1273
        // Finding the two questions that needs to be swapped
1274
        $sql = "SELECT * FROM $table_survey_question
1275
		        WHERE c_id = $course_id AND survey_id='".Database::escape_string($survey_id)."'
1276
		        ORDER BY sort $sort";
1277
        $result = Database::query($sql);
1278
        $found = false;
1279
        while ($row = Database::fetch_array($result, 'ASSOC')) {
1280
            if ($found) {
1281
                $question_id_two = $row['question_id'];
1282
                $question_sort_two = $row['sort'];
1283
                $found = false;
1284
            }
1285
            if ($row['question_id'] == $survey_question_id) {
1286
                $found = true;
1287
                $question_id_one = $row['question_id'];
1288
                $question_sort_one = $row['sort'];
1289
            }
1290
        }
1291
1292
        $sql1 = "UPDATE $table_survey_question SET sort = '".Database::escape_string($question_sort_two)."'
1293
		        WHERE c_id = $course_id AND  question_id='".intval($question_id_one)."'";
1294
        Database::query($sql1);
1295
        $sql2 = "UPDATE $table_survey_question SET sort = '".Database::escape_string($question_sort_one)."'
1296
		        WHERE c_id = $course_id AND question_id='".intval($question_id_two)."'";
1297
        Database::query($sql2);
1298
    }
1299
1300
    /**
1301
     * This function deletes all the questions of a given survey
1302
     * This function is normally only called when a survey is deleted
1303
     *
1304
     * @param int $survey_id the id of the survey that has to be deleted
1305
     * @return true
1306
     *
1307
     * @author Patrick Cool <[email protected]>, Ghent University
1308
     * @version January 2007
1309
     */
1310
    public static function delete_all_survey_questions($survey_id, $shared = false)
1311
    {
1312
        $course_id = api_get_course_int_id();
1313
1314
        // Table definitions
1315
        $table_survey_question 	= Database :: get_course_table(TABLE_SURVEY_QUESTION);
1316
        $course_condition = " c_id = $course_id AND ";
1317
        if ($shared) {
1318
            $course_condition = "";
1319
            $table_survey_question 	= Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
1320
        }
1321
1322
        $sql = "DELETE FROM $table_survey_question
1323
		        WHERE $course_condition survey_id='".intval($survey_id)."'";
1324
1325
        // Deleting the survey questions
1326
1327
        Database::query($sql);
1328
1329
        // Deleting all the options of the questions of the survey
1330
        SurveyManager::delete_all_survey_questions_options($survey_id, $shared);
1331
1332
        // Deleting all the answers on this survey
1333
        SurveyManager::delete_all_survey_answers($survey_id);
1334
    }
1335
1336
    /**
1337
     * This function deletes a survey question and all its options
1338
     *
1339
     * @param integer $survey_id the id of the survey
1340
     * @param integer $question_id the id of the question
1341
     * @param integer $shared
1342
     *
1343
     * @todo also delete the answers to this question
1344
     *
1345
     * @author Patrick Cool <[email protected]>, Ghent University
1346
     * @version March 2007
1347
     */
1348
    public static function delete_survey_question($survey_id, $question_id, $shared = false)
1349
    {
1350
        $course_id = api_get_course_int_id();
1351
        // Table definitions
1352
        $table_survey_question 	= Database :: get_course_table(TABLE_SURVEY_QUESTION);
1353
        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...
1354
            SurveyManager::delete_shared_survey_question($survey_id, $question_id);
1355
        }
1356
1357
        // Deleting the survey questions
1358
        $sql = "DELETE FROM $table_survey_question
1359
		        WHERE
1360
		            c_id = $course_id AND
1361
		            survey_id='".intval($survey_id)."' AND
1362
		            question_id='".intval($question_id)."'";
1363
        Database::query($sql);
1364
1365
        // Deleting the options of the question of the survey
1366
        SurveyManager::delete_survey_question_option($survey_id, $question_id, $shared);
1367
    }
1368
1369
    /**
1370
     * This function deletes a shared survey question from the main database and all its options
1371
     *
1372
     * @param int $question_id the id of the question
1373
     * @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...
1374
     *
1375
     * @todo delete all the options of this question
1376
     *
1377
     * @author Patrick Cool <[email protected]>, Ghent University
1378
     * @version March 2007
1379
     */
1380
    public static function delete_shared_survey_question($survey_id, $question_id)
1381
    {
1382
        // Table definitions
1383
        $table_survey_question 	      = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
1384
        $table_survey_question_option = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
1385
1386
        // First we have to get the shared_question_id
1387
        $question_data = SurveyManager::get_question($question_id);
1388
1389
        // Deleting the survey questions
1390
        $sql = "DELETE FROM $table_survey_question
1391
		        WHERE question_id='".intval($question_data['shared_question_id'])."'";
1392
        Database::query($sql);
1393
1394
        // Deleting the options of the question of the survey question
1395
        $sql = "DELETE FROM $table_survey_question_option
1396
		        WHERE question_id='".intval($question_data['shared_question_id'])."'";
1397
        Database::query($sql);
1398
    }
1399
1400
    /**
1401
     * This function stores the options of the questions in the table
1402
     *
1403
     * @param array $form_content
1404
     * @author Patrick Cool <[email protected]>, Ghent University
1405
     * @version January 2007
1406
     *
1407
     * @todo writing the update statement when editing a question
1408
     */
1409
    public static function save_question_options($form_content, $survey_data)
1410
    {
1411
        $course_id = api_get_course_int_id();
1412
        // A percentage question type has options 1 -> 100
1413
        if ($form_content['type'] == 'percentage') {
1414
            for($i = 1; $i < 101; $i++) {
1415
                $form_content['answers'][] = $i;
1416
            }
1417
        }
1418
1419
        if (is_numeric($survey_data['survey_share']) && $survey_data['survey_share'] != 0) {
1420
            SurveyManager::save_shared_question_options($form_content, $survey_data);
1421
        }
1422
1423
        // Table definition
1424
        $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
1425
1426
        // We are editing a question so we first have to remove all the existing options from the database
1427
        if (is_numeric($form_content['question_id'])) {
1428
            $sql = "DELETE FROM $table_survey_question_option
1429
			        WHERE c_id = $course_id AND question_id = '".intval($form_content['question_id'])."'";
1430
            Database::query($sql);
1431
        }
1432
1433
        $counter = 1;
1434
        if (isset($form_content['answers']) && is_array($form_content['answers'])) {
1435
            for ($i = 0; $i < count($form_content['answers']); $i++) {
1436
                $values = isset($form_content['values']) ? $form_content['values'][$i] : '';
1437
1438
                $params = [
1439
                    'c_id' => $course_id,
1440
                    'question_id' => $form_content['question_id'],
1441
                    'survey_id' => $form_content['survey_id'],
1442
                    'option_text' => $form_content['answers'][$i],
1443
                    'value' => $values,
1444
                    'sort' => $counter,
1445
                ];
1446
                $insertId = Database::insert($table_survey_question_option, $params);
1447
                if ($insertId) {
1448
1449
                    $sql = "UPDATE $table_survey_question_option
1450
                            SET question_option_id = $insertId
1451
                            WHERE iid = $insertId";
1452
                    Database::query($sql);
1453
1454
                    $counter++;
1455
                }
1456
            }
1457
        }
1458
    }
1459
1460
    /**
1461
     * This function stores the options of the questions in the shared table
1462
     *
1463
     * @param array $form_content
1464
     *
1465
     * @author Patrick Cool <[email protected]>, Ghent University
1466
     * @version February 2007
1467
     *
1468
     * @todo writing the update statement when editing a question
1469
     */
1470
    public function save_shared_question_options($form_content, $survey_data)
1471
    {
1472
        if (is_array($form_content) && is_array($form_content['answers'])) {
1473
            // Table definition
1474
            $table = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
1475
1476
            // We are editing a question so we first have to remove all the existing options from the database
1477
            $sql = "DELETE FROM $table
1478
                    WHERE question_id = '".Database::escape_string($form_content['shared_question_id'])."'";
1479
            Database::query($sql);
1480
1481
            $counter = 1;
1482
            foreach ($form_content['answers'] as & $answer) {
1483
                $params = [
1484
                    'question_id' => $form_content['shared_question_id'],
1485
                    'survey_id' => $survey_data['is_shared'],
1486
                    'option_text' => $answer,
1487
                    'sort' => $counter,
1488
                ];
1489
                Database::insert($table, $params);
1490
1491
                $counter++;
1492
            }
1493
        }
1494
    }
1495
1496
    /**
1497
     * This function deletes all the options of the questions of a given survey
1498
     * This function is normally only called when a survey is deleted
1499
     *
1500
     * @param $survey_id the id of the survey that has to be deleted
1501
     * @return true
1502
     *
1503
     * @author Patrick Cool <[email protected]>, Ghent University
1504
     * @version January 2007
1505
     */
1506 View Code Duplication
    public static function delete_all_survey_questions_options($survey_id, $shared = false)
1507
    {
1508
        // Table definitions
1509
        $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
1510
        $course_id = api_get_course_int_id();
1511
        $course_condition = " c_id = $course_id AND ";
1512
        if ($shared) {
1513
            $course_condition = "";
1514
            $table_survey_question_option = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
1515
        }
1516
1517
        $sql = "DELETE FROM $table_survey_question_option
1518
                WHERE $course_condition survey_id='".intval($survey_id)."'";
1519
1520
        // Deleting the options of the survey questions
1521
        Database::query($sql);
1522
        return true;
1523
    }
1524
1525
    /**
1526
     * This function deletes the options of a given question
1527
     *
1528
     * @param int $survey_id
1529
     * @param int $question_id
1530
     * @param int $shared
1531
     *
1532
     * @return bool
1533
     *
1534
     * @author Patrick Cool <[email protected]>, Ghent University
1535
     * @author Julio Montoya
1536
     * @version March 2007
1537
     */
1538 View Code Duplication
    public static function delete_survey_question_option($survey_id, $question_id, $shared = false)
1539
    {
1540
        $course_id = api_get_course_int_id();
1541
        $course_condition = " c_id = $course_id AND ";
1542
1543
        // Table definitions
1544
        $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
1545
        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...
1546
            $course_condition = "";
1547
            $table_survey_question_option = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
1548
        }
1549
1550
        // Deleting the options of the survey questions
1551
        $sql = "DELETE from $table_survey_question_option
1552
		        WHERE
1553
		            $course_condition survey_id='".intval($survey_id)."' AND
1554
		            question_id='".intval($question_id)."'";
1555
        Database::query($sql);
1556
        return true;
1557
    }
1558
1559
    /**
1560
     * SURVEY ANSWERS FUNCTIONS
1561
     */
1562
1563
    /**
1564
     * This function deletes all the answers anyone has given on this survey
1565
     * This function is normally only called when a survey is deleted
1566
     *
1567
     * @param $survey_id the id of the survey that has to be deleted
1568
     * @return true
1569
     *
1570
     * @todo write the function
1571
     *
1572
     * @author Patrick Cool <[email protected]>, Ghent University
1573
     * @version January 2007,december 2008
1574
     */
1575
    public static function delete_all_survey_answers($survey_id)
1576
    {
1577
        $course_id = api_get_course_int_id();
1578
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
1579
        $survey_id = intval($survey_id);
1580
        Database::query("DELETE FROM $table_survey_answer WHERE c_id = $course_id AND survey_id=$survey_id");
1581
        return true;
1582
    }
1583
1584
    /**
1585
     * @param int $user_id
1586
     * @param int $survey_id
1587
     * @param int $course_id
1588
     * @return bool
1589
     */
1590 View Code Duplication
    public static function is_user_filled_survey($user_id, $survey_id, $course_id)
1591
    {
1592
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
1593
1594
        $user_id	= intval($user_id);
1595
        $course_id	= intval($course_id);
1596
        $survey_id	= intval($survey_id);
1597
1598
        $sql = "SELECT DISTINCT user FROM $table_survey_answer
1599
                WHERE
1600
                    c_id		= $course_id AND
1601
                    user		= $user_id AND
1602
                    survey_id	= $survey_id";
1603
        $result = Database::query($sql);
1604
        if (Database::num_rows($result)) {
1605
            return true;
1606
        }
1607
        return false;
1608
    }
1609
1610
    /**
1611
     * This function gets all the persons who have filled the survey
1612
     *
1613
     * @param integer $survey_id
1614
     * @return array
1615
     *
1616
     * @author Patrick Cool <[email protected]>, Ghent University
1617
     * @version February 2007
1618
     */
1619
    public static function get_people_who_filled_survey($survey_id, $all_user_info = false, $course_id = null)
1620
    {
1621
        // Database table definition
1622
        $table_survey_answer = Database:: get_course_table(TABLE_SURVEY_ANSWER);
1623
        $table_user = Database:: get_main_table(TABLE_MAIN_USER);
1624
1625
        // Variable initialisation
1626
        $return = array();
1627
1628
        if (empty($course_id)) {
1629
            $course_id = api_get_course_int_id();
1630
        } else {
1631
            $course_id = intval($course_id);
1632
        }
1633
1634
        if ($all_user_info) {
1635
            $order_clause = api_sort_by_first_name() ? ' ORDER BY user.firstname, user.lastname' : ' ORDER BY user.lastname, user.firstname';
1636
            $sql = "SELECT DISTINCT
1637
			            answered_user.user as invited_user, user.firstname, user.lastname, user.user_id
1638
                    FROM $table_survey_answer answered_user
1639
                    LEFT JOIN $table_user as user ON answered_user.user = user.user_id
1640
                    WHERE
1641
                        answered_user.c_id = $course_id AND
1642
                        survey_id= '".Database::escape_string($survey_id)."' ".
1643
                $order_clause;
1644
        } else {
1645
            $sql = "SELECT DISTINCT user FROM $table_survey_answer
1646
			        WHERE c_id = $course_id AND survey_id= '".Database::escape_string($survey_id)."'  ";
1647
        }
1648
1649
        $res = Database::query($sql);
1650
        while ($row = Database::fetch_array($res, 'ASSOC')) {
1651
            if ($all_user_info) {
1652
                $return[] = $row;
1653
            } else {
1654
                $return[] = $row['user'];
1655
            }
1656
        }
1657
1658
        return $return;
1659
    }
1660
1661
    public static function survey_generation_hash_available()
1662
    {
1663
        if (extension_loaded('mcrypt')) {
1664
            return true;
1665
        }
1666
        return false;
1667
    }
1668
1669
    public static function generate_survey_hash($survey_id, $course_id, $session_id, $group_id)
1670
    {
1671
        $hash = hash('sha512', api_get_security_key().'_'.$course_id.'_'.$session_id.'_'.$group_id.'_'.$survey_id);
1672
        return $hash;
1673
    }
1674
1675
    public static function validate_survey_hash($survey_id, $course_id, $session_id, $group_id, $hash)
1676
    {
1677
        $survey_generated_hash = self::generate_survey_hash($survey_id, $course_id, $session_id, $group_id);
1678
        if ($survey_generated_hash == $hash) {
1679
            return true;
1680
        }
1681
        return false;
1682
    }
1683
1684
    public static function generate_survey_link($survey_id, $course_id, $session_id, $group_id)
1685
    {
1686
        $code = self::generate_survey_hash($survey_id, $course_id, $session_id, $group_id);
1687
        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;
1688
    }
1689
1690
    /**
1691
     * Check if the current user has mandatory surveys no-answered
1692
     * and redirect to fill the first found survey
1693
     */
1694
    public static function protectByMandatory()
1695
    {
1696
        if (strpos($_SERVER['SCRIPT_NAME'], 'fillsurvey.php') !== false) {
1697
            return;
1698
        }
1699
1700
        $userId = api_get_user_id();
1701
        $courseId = api_get_course_int_id();
1702
        $sessionId = api_get_session_id();
1703
1704
        if (!$userId) {
1705
            return;
1706
        }
1707
1708
        if (!$courseId) {
1709
            return;
1710
        }
1711
1712
        try {
1713
            /** @var CSurveyInvitation $invitation */
1714
            $invitation = Database::getManager()
1715
                ->createQuery("
1716
                    SELECT i FROM ChamiloCourseBundle:CSurveyInvitation i
1717
                    INNER JOIN ChamiloCourseBundle:CSurvey s WITH s.code = i.surveyCode
1718
                    INNER JOIN ChamiloCoreBundle:ExtraFieldValues efv WITH efv.itemId = s.iid
1719
                    INNER JOIN ChamiloCoreBundle:ExtraField ef WITH efv.field = ef.id
1720
                    WHERE i.answered = 0
1721
                        AND i.cId = :course
1722
                        AND i.user = :user
1723
                        AND i.sessionId = :session
1724
                        AND :now BETWEEN s.availFrom AND s.availTill
1725
                        AND ef.variable = :variable
1726
                        AND efv.value = 1
1727
                    ORDER BY s.availTill ASC
1728
                ")
1729
                ->setMaxResults(1)
1730
                ->setParameters([
1731
                    'course' => $courseId,
1732
                    'user' => $userId,
1733
                    'session' => $sessionId,
1734
                    'now' => new DateTime('UTC', new DateTimeZone('UTC')),
1735
                    'variable' => 'is_mandatory'
1736
                ])
1737
                ->getSingleResult();
1738
        } catch (Exception $e) {
1739
            $invitation = null;
1740
        }
1741
1742
        if (!$invitation) {
1743
            return;
1744
        }
1745
1746
        $urlParams = http_build_query([
1747
            'course' => api_get_course_id(),
1748
            'invitationcode' => $invitation->getInvitationCode()
1749
        ]);
1750
1751
        Display::addFlash(
1752
            Display::return_message(get_lang('MandatorySurveyNoAnswered'), 'warning')
1753
        );
1754
1755
        header('Location: '.api_get_path(WEB_CODE_PATH).'survey/fillsurvey.php?'.$urlParams.'&'.api_get_cidreq());
1756
        exit;
1757
    }
1758
}
1759
1760
1761
/**
1762
 * This class offers a series of general utility functions for survey querying and display
1763
 * @package chamilo.survey
1764
 */
1765
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...
1766
{
1767
    /**
1768
     * Checks whether the given survey has a pagebreak question as the first or the last question.
1769
     * If so, break the current process, displaying an error message
1770
     * @param	integer	Survey ID (database ID)
1771
     * @param	boolean	Optional. Whether to continue the current process or exit when breaking condition found. Defaults to true (do not break).
1772
     * @return	void
1773
     */
1774
    static function check_first_last_question($survey_id, $continue = true)
1775
    {
1776
        // Table definitions
1777
        $tbl_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
1778
        $course_id = api_get_course_int_id();
1779
1780
        // Getting the information of the question
1781
        $sql = "SELECT * FROM $tbl_survey_question
1782
                WHERE c_id = $course_id AND survey_id='".Database::escape_string($survey_id)."'
1783
                ORDER BY sort ASC";
1784
        $result = Database::query($sql);
1785
        $total = Database::num_rows($result);
1786
        $counter = 1;
1787
        $error = false;
1788
        while ($row = Database::fetch_array($result, 'ASSOC')) {
1789 View Code Duplication
            if ($counter == 1 && $row['type'] == 'pagebreak') {
1790
1791
                Display::display_error_message(get_lang('PagebreakNotFirst'), false);
1792
                $error = true;
1793
            }
1794 View Code Duplication
            if ($counter == $total && $row['type'] == 'pagebreak') {
1795
                Display::display_error_message(get_lang('PagebreakNotLast'), false);
1796
                $error = true;
1797
            }
1798
            $counter++;
1799
        }
1800
1801
        if (!$continue && $error) {
1802
            Display::display_footer();
1803
            exit;
1804
        }
1805
    }
1806
1807
    /**
1808
     * This function removes an (or multiple) answer(s) of a user on a question of a survey
1809
     *
1810
     * @param mixed   The user id or email of the person who fills the survey
1811
     * @param integer The survey id
1812
     * @param integer The question id
1813
     * @param integer The option id
1814
     *
1815
     * @author Patrick Cool <[email protected]>, Ghent University
1816
     * @version January 2007
1817
     */
1818
    static function remove_answer($user, $survey_id, $question_id, $course_id) {
1819
        $course_id = intval($course_id);
1820
        // table definition
1821
        $table_survey_answer 		= Database :: get_course_table(TABLE_SURVEY_ANSWER);
1822
        $sql = "DELETE FROM $table_survey_answer
1823
				WHERE
1824
				    c_id = $course_id AND
1825
                    user = '".Database::escape_string($user)."' AND
1826
                    survey_id = '".intval($survey_id)."' AND
1827
                    question_id = '".intval($question_id)."'";
1828
        Database::query($sql);
1829
    }
1830
1831
    /**
1832
     * This function stores an answer of a user on a question of a survey
1833
     *
1834
     * @param mixed   The user id or email of the person who fills the survey
1835
     * @param integer Survey id
1836
     * @param integer Question id
1837
     * @param integer Option id
1838
     * @param string  Option value
1839
     * @param array	  Survey data settings
1840
     *
1841
     * @author Patrick Cool <[email protected]>, Ghent University
1842
     * @version January 2007
1843
     */
1844
    static function store_answer($user, $survey_id, $question_id, $option_id, $option_value, $survey_data)
1845
    {
1846
        // Table definition
1847
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
1848
1849
        // Make the survey anonymous
1850
        if ($survey_data['anonymous'] == 1) {
1851
            if (!isset($_SESSION['surveyuser'])) {
1852
                $user = md5($user.time());
1853
                $_SESSION['surveyuser'] = $user;
1854
            } else {
1855
                $user = $_SESSION['surveyuser'];
1856
            }
1857
        }
1858
1859
        $course_id = $survey_data['c_id'];
1860
1861
        $sql = "INSERT INTO $table_survey_answer (c_id, user, survey_id, question_id, option_id, value) VALUES (
1862
				$course_id,
1863
				'".Database::escape_string($user)."',
1864
				'".Database::escape_string($survey_id)."',
1865
				'".Database::escape_string($question_id)."',
1866
				'".Database::escape_string($option_id)."',
1867
				'".Database::escape_string($option_value)."'
1868
				)";
1869
        Database::query($sql);
1870
        $insertId = Database::insert_id();
1871
1872
        $sql = "UPDATE $table_survey_answer SET answer_id = $insertId WHERE iid = $insertId";
1873
        Database::query($sql);
1874
    }
1875
1876
    /**
1877
     * This function checks the parameters that are used in this page
1878
     *
1879
     * @return 	string 	The header, an error and the footer if any parameter fails, else it returns true
1880
     * @author Patrick Cool <[email protected]>, Ghent University
1881
     * @version February 2007
1882
     */
1883
    static function check_parameters($people_filled)
1884
    {
1885
        $error = false;
1886
1887
        // Getting the survey data
1888
        $survey_data = SurveyManager::get_survey($_GET['survey_id']);
1889
1890
        // $_GET['survey_id'] has to be numeric
1891
        if (!is_numeric($_GET['survey_id'])) {
1892
            $error = get_lang('IllegalSurveyId');
1893
        }
1894
1895
        // $_GET['action']
1896
        $allowed_actions = array(
1897
            'overview',
1898
            'questionreport',
1899
            'userreport',
1900
            'comparativereport',
1901
            'completereport',
1902
            'deleteuserreport'
1903
        );
1904
        if (isset($_GET['action']) && !in_array($_GET['action'], $allowed_actions)) {
1905
            $error = get_lang('ActionNotAllowed');
1906
        }
1907
1908
        // User report
1909
        if (isset($_GET['action']) && $_GET['action'] == 'userreport') {
1910
            if ($survey_data['anonymous'] == 0) {
1911
                foreach ($people_filled as $key => & $value) {
1912
                    $people_filled_userids[] = $value['invited_user'];
1913
                }
1914
            } else {
1915
                $people_filled_userids = $people_filled;
1916
            }
1917
1918
            if (isset($_GET['user']) && !in_array($_GET['user'], $people_filled_userids)) {
1919
                $error = get_lang('UnknowUser');
1920
            }
1921
        }
1922
1923
        // Question report
1924
        if (isset($_GET['action']) && $_GET['action'] == 'questionreport') {
1925
            if (isset($_GET['question']) && !is_numeric($_GET['question'])) {
1926
                $error = get_lang('UnknowQuestion');
1927
            }
1928
        }
1929
1930
        if ($error) {
1931
            $tool_name = get_lang('Reporting');
1932
            Display::display_header($tool_name);
1933
            Display::display_error_message(get_lang('Error').': '.$error, false);
1934
            Display::display_footer();
1935
            exit;
1936
        } else {
1937
            return true;
1938
        }
1939
    }
1940
1941
    /**
1942
     * This function deals with the action handling
1943
     * @return	void
1944
     * @author Patrick Cool <[email protected]>, Ghent University
1945
     * @version February 2007
1946
     */
1947
    public static function handle_reporting_actions($survey_data, $people_filled)
1948
    {
1949
        $action = isset($_GET['action']) ? $_GET['action'] : null;
1950
1951
        // Getting the number of question
1952
        $temp_questions_data = SurveyManager::get_questions($_GET['survey_id']);
1953
1954
        // Sorting like they should be displayed and removing the non-answer question types (comment and pagebreak)
1955
        $my_temp_questions_data = $temp_questions_data == null ? array() : $temp_questions_data;
1956
        $questions_data = array();
1957
1958
        foreach ($my_temp_questions_data as $key => & $value) {
1959
            if ($value['type'] != 'comment' && $value['type'] != 'pagebreak') {
1960
                $questions_data[$value['sort']] = $value;
1961
            }
1962
        }
1963
1964
        // Counting the number of questions that are relevant for the reporting
1965
        $survey_data['number_of_questions'] = count($questions_data);
1966
1967
        if ($action == 'questionreport') {
1968
            SurveyUtil::display_question_report($survey_data);
1969
        }
1970
        if ($action == 'userreport') {
1971
            SurveyUtil::display_user_report($people_filled, $survey_data);
1972
        }
1973
        if ($action == 'comparativereport') {
1974
            SurveyUtil::display_comparative_report();
1975
        }
1976
        if ($action == 'completereport') {
1977
            SurveyUtil::display_complete_report($survey_data);
1978
        }
1979
        if ($action == 'deleteuserreport') {
1980
            SurveyUtil::delete_user_report($_GET['survey_id'], $_GET['user']);
1981
        }
1982
    }
1983
1984
    /**
1985
     * This function deletes the report of an user who wants to retake the survey
1986
     * @param integer survey_id
1987
     * @param integer user_id
1988
     * @return void
1989
     * @author Christian Fasanando Flores <[email protected]>
1990
     * @version November 2008
1991
     */
1992
    function delete_user_report($survey_id, $user_id)
1993
    {
1994
        $table_survey_answer = Database:: get_course_table(TABLE_SURVEY_ANSWER);
1995
        $table_survey_invitation = Database:: get_course_table(TABLE_SURVEY_INVITATION);
1996
        $table_survey = Database:: get_course_table(TABLE_SURVEY);
1997
1998
        $course_id = api_get_course_int_id();
1999
        $survey_id = (int) $survey_id;
2000
2001
        if (!empty($survey_id) && !empty($user_id)) {
2002
            $user_id = Database::escape_string($user_id);
2003
            // delete data from survey_answer by user_id and survey_id
2004
            $sql = "DELETE FROM $table_survey_answer
2005
			        WHERE c_id = $course_id AND survey_id = '".$survey_id."' AND user = '".$user_id."'";
2006
            Database::query($sql);
2007
            // update field answered from survey_invitation by user_id and survey_id
2008
            $sql = "UPDATE $table_survey_invitation SET answered = '0'
2009
			        WHERE
2010
			            c_id = $course_id AND
2011
			            survey_code = (
2012
                            SELECT code FROM $table_survey
2013
                            WHERE
2014
                                c_id = $course_id AND
2015
                                survey_id = '".(int)$survey_id."'
2016
                        ) AND
2017
			            user = '".$user_id."'";
2018
            $result = Database::query($sql);
2019
        }
2020
2021 View Code Duplication
        if ($result !== false) {
2022
            $message = get_lang('SurveyUserAnswersHaveBeenRemovedSuccessfully').'<br />
2023
					<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action=userreport&survey_id='.Security::remove_XSS($survey_id).'">'.get_lang('GoBack').'</a>';
2024
            Display::display_confirmation_message($message, false);
2025
        }
2026
    }
2027
2028
    /**
2029
     * This function displays the user report which is basically nothing more
2030
     * than a one-page display of all the questions
2031
     * of the survey that is filled with the answers of the person who filled the survey.
2032
     *
2033
     * @return 	string	html code of the one-page survey with the answers of the selected user
2034
     * @author Patrick Cool <[email protected]>, Ghent University
2035
     * @version February 2007 - Updated March 2008
2036
     */
2037
    public static function display_user_report($people_filled, $survey_data)
2038
    {
2039
        // Database table definitions
2040
        $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
2041
        $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
2042
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
2043
2044
        // Actions bar
2045
        echo '<div class="actions">';
2046
        echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.Security::remove_XSS($_GET['survey_id']).'">'.
2047
            Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('ReportingOverview'),'',ICON_SIZE_MEDIUM).'</a>';
2048
        if (isset($_GET['user'])) {
2049
            if (api_is_allowed_to_edit()) {
2050
                // The delete link
2051
                echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action=deleteuserreport&survey_id='.Security::remove_XSS($_GET['survey_id']).'&user='.Security::remove_XSS($_GET['user']).'" >'.
2052
                    Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_MEDIUM).'</a>';
2053
            }
2054
2055
            // Export the user report
2056
            echo '<a href="javascript: void(0);" onclick="document.form1a.submit();">'.
2057
                Display::return_icon('export_csv.png', get_lang('ExportAsCSV'),'',ICON_SIZE_MEDIUM).'</a> ';
2058
            echo '<a href="javascript: void(0);" onclick="document.form1b.submit();">'.
2059
                Display::return_icon('export_excel.png', get_lang('ExportAsXLS'),'',ICON_SIZE_MEDIUM).'</a> ';
2060
            echo '<form id="form1a" name="form1a" method="post" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.Security::remove_XSS($_GET['survey_id']).'&user_id='.Security::remove_XSS($_GET['user']).'">';
2061
            echo '<input type="hidden" name="export_report" value="export_report">';
2062
            echo '<input type="hidden" name="export_format" value="csv">';
2063
            echo '</form>';
2064
            echo '<form id="form1b" name="form1b" method="post" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.Security::remove_XSS($_GET['survey_id']).'&user_id='.Security::remove_XSS($_GET['user']).'">';
2065
            echo '<input type="hidden" name="export_report" value="export_report">';
2066
            echo '<input type="hidden" name="export_format" value="xls">';
2067
            echo '</form>';
2068
            echo '<form id="form2" name="form2" method="post" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.Security::remove_XSS($_GET['survey_id']).'">';
2069
        }
2070
        echo '</div>';
2071
2072
        // Step 1: selection of the user
2073
        echo "<script>
2074
        function jumpMenu(targ,selObj,restore) {
2075
            eval(targ+\".location='\"+selObj.options[selObj.selectedIndex].value+\"'\");
2076
            if (restore) selObj.selectedIndex=0;
2077
        }
2078
		</script>";
2079
        echo get_lang('SelectUserWhoFilledSurvey').'<br />';
2080
        echo '<select name="user" onchange="jumpMenu(\'parent\',this,0)">';
2081
        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>';
2082
2083
        foreach ($people_filled as $key => & $person) {
2084
            if ($survey_data['anonymous'] == 0) {
2085
                $name = api_get_person_name($person['firstname'], $person['lastname']);
2086
                $id = $person['user_id'];
2087
                if ($id == '') {
2088
                    $id = $person['invited_user'];
2089
                    $name = $person['invited_user'];
2090
                }
2091
            } else {
2092
                $name  = get_lang('Anonymous') . ' ' . ($key + 1);
2093
                $id = $person;
2094
            }
2095
            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).'" ';
2096
            if (isset($_GET['user']) && $_GET['user'] == $id) {
2097
                echo 'selected="selected"';
2098
            }
2099
            echo '>'.$name.'</option>';
2100
        }
2101
        echo '</select>';
2102
2103
        $course_id = api_get_course_int_id();
2104
        // Step 2: displaying the survey and the answer of the selected users
2105
        if (isset($_GET['user'])) {
2106
            Display::display_normal_message(
2107
                get_lang('AllQuestionsOnOnePage'),
2108
                false
2109
            );
2110
2111
            // Getting all the questions and options
2112
            $sql = "SELECT
2113
			            survey_question.question_id,
2114
			            survey_question.survey_id,
2115
			            survey_question.survey_question,
2116
			            survey_question.display,
2117
			            survey_question.max_value,
2118
			            survey_question.sort,
2119
			            survey_question.type,
2120
                        survey_question_option.question_option_id,
2121
                        survey_question_option.option_text,
2122
                        survey_question_option.sort as option_sort
2123
					FROM $table_survey_question survey_question
2124
					LEFT JOIN $table_survey_question_option survey_question_option
2125
					ON
2126
					    survey_question.question_id = survey_question_option.question_id AND
2127
					    survey_question_option.c_id = $course_id
2128
					WHERE
2129
					    survey_question.survey_id = '".Database::escape_string(
2130
                    $_GET['survey_id']
2131
                )."' AND
2132
                        survey_question.c_id = $course_id
2133
					ORDER BY survey_question.sort, survey_question_option.sort ASC";
2134
            $result = Database::query($sql);
2135 View Code Duplication
            while ($row = Database::fetch_array($result, 'ASSOC')) {
2136
                if ($row['type'] != 'pagebreak') {
2137
                    $questions[$row['sort']]['question_id'] = $row['question_id'];
2138
                    $questions[$row['sort']]['survey_id'] = $row['survey_id'];
2139
                    $questions[$row['sort']]['survey_question'] = $row['survey_question'];
2140
                    $questions[$row['sort']]['display'] = $row['display'];
2141
                    $questions[$row['sort']]['type'] = $row['type'];
2142
                    $questions[$row['sort']]['maximum_score'] = $row['max_value'];
2143
                    $questions[$row['sort']]['options'][$row['question_option_id']] = $row['option_text'];
2144
                }
2145
            }
2146
2147
            // Getting all the answers of the user
2148
            $sql = "SELECT * FROM $table_survey_answer
2149
			        WHERE
2150
                        c_id = $course_id AND
2151
                        survey_id = '".intval($_GET['survey_id'])."' AND
2152
                        user = '".Database::escape_string($_GET['user'])."'";
2153
            $result = Database::query($sql);
2154
            while ($row = Database::fetch_array($result, 'ASSOC')) {
2155
                $answers[$row['question_id']][] = $row['option_id'];
2156
                $all_answers[$row['question_id']][] = $row;
2157
            }
2158
2159
            // Displaying all the questions
2160
2161
            foreach ($questions as & $question) {
2162
                // If the question type is a scoring then we have to format the answers differently
2163
                switch ($question['type']) {
2164
                    case 'score':
2165
                        $finalAnswer = array();
2166
                        if (is_array($question) && is_array($all_answers)) {
2167
                            foreach ($all_answers[$question['question_id']] as $key => & $answer_array) {
2168
                                $finalAnswer[$answer_array['option_id']] = $answer_array['value'];
2169
                            }
2170
                        }
2171
                        break;
2172
                    case 'multipleresponse':
2173
                        $finalAnswer = isset($answers[$question['question_id']]) ? $answers[$question['question_id']] : '';
2174
                        break;
2175
                    default:
2176
                        $finalAnswer = '';
2177
                        if (isset($all_answers[$question['question_id']])) {
2178
                            $finalAnswer = $all_answers[$question['question_id']][0]['option_id'];
2179
                        }
2180
                        break;
2181
                }
2182
2183
                $ch_type = 'ch_'.$question['type'];
2184
                /** @var survey_question $display */
2185
                $display = new $ch_type;
2186
2187
                $url = api_get_self();
2188
                $form = new FormValidator('question', 'post', $url);
2189
                $form->addHtml('<div class="survey_question_wrapper"><div class="survey_question">');
2190
                $form->addHtml($question['survey_question']);
2191
                $display->render($form, $question, $finalAnswer);
2192
                $form->addHtml('</div></div>');
2193
                $form->display();
2194
            }
2195
        }
2196
    }
2197
2198
    /**
2199
     * This function displays the report by question.
2200
     *
2201
     * It displays a table with all the options of the question and the number of users who have answered positively on the option.
2202
     * The number of users who answered positive on a given option is expressed in an absolute number, in a percentage of the total
2203
     * and graphically using bars
2204
     * By clicking on the absolute number you get a list with the persons who have answered this.
2205
     * 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
2206
     * answers of that user.
2207
     *
2208
     * @param 	array 	All the survey data
2209
     * @return 	string	html code that displays the report by question
2210
     * @todo allow switching between horizontal and vertical.
2211
     * @todo multiple response: percentage are probably not OK
2212
     * @todo the question and option text have to be shortened and should expand when the user clicks on it.
2213
     * @todo the pagebreak and comment question types should not be shown => removed from $survey_data before
2214
     * @author Patrick Cool <[email protected]>, Ghent University
2215
     * @version February 2007 - Updated March 2008
2216
     */
2217
    public static function display_question_report($survey_data)
2218
    {
2219
        $singlePage = isset($_GET['single_page']) ? intval($_GET['single_page']) : 0;
2220
        $course_id = api_get_course_int_id();
2221
        // Database table definitions
2222
        $table_survey_question 			= Database :: get_course_table(TABLE_SURVEY_QUESTION);
2223
        $table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
2224
        $table_survey_answer 			= Database :: get_course_table(TABLE_SURVEY_ANSWER);
2225
2226
        // Determining the offset of the sql statement (the n-th question of the survey)
2227
        $offset = !isset($_GET['question']) ? 0 : intval($_GET['question']);
2228
        $currentQuestion = isset($_GET['question']) ? intval($_GET['question']) : 0;
2229
        $questions = array();
2230
        $surveyId = intval($_GET['survey_id']);
2231
        $action = Security::remove_XSS($_GET['action']);
2232
2233
        echo '<div class="actions">';
2234
        echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.$surveyId.'">'.
2235
            Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('ReportingOverview'),'',ICON_SIZE_MEDIUM).'</a>';
2236
        echo '</div>';
2237
2238
        if ($survey_data['number_of_questions'] > 0) {
2239
            $limitStatement = null;
2240
            if (!$singlePage) {
2241
                echo '<div id="question_report_questionnumbers" class="pagination">';
2242
                if ($currentQuestion != 0) {
2243
                    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>';
2244
                }
2245
2246
                for ($i = 1; $i <= $survey_data['number_of_questions']; $i++) {
2247
                    if ($offset != $i - 1) {
2248
                        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>';
2249
                    } else {
2250
                        echo '<li class="disabled"s><a href="#">' . $i . '</a></li>';
2251
                    }
2252
                }
2253
                if ($currentQuestion < ($survey_data['number_of_questions'] - 1)) {
2254
                    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>';
2255
                }
2256
                echo '</ul>';
2257
                echo '</div>';
2258
                $limitStatement = " LIMIT $offset, 1";
2259
            }
2260
2261
            // Getting the question information
2262
            $sql = "SELECT * FROM $table_survey_question
2263
			        WHERE
2264
			            c_id = $course_id AND
2265
                        survey_id='".Database::escape_string($_GET['survey_id'])."' AND
2266
                        type<>'pagebreak' AND type<>'comment'
2267
                    ORDER BY sort ASC
2268
                    $limitStatement";
2269
            $result = Database::query($sql);
2270
2271
            while ($row = Database::fetch_array($result)) {
2272
                $questions[$row['question_id']] = $row;
2273
            }
2274
        }
2275
2276
        foreach ($questions as $question) {
2277
            $chartData = array();
2278
            $options = array();
2279
            echo '<div class="title-question">';
2280
            echo strip_tags(isset($question['survey_question']) ? $question['survey_question'] : null);
2281
            echo '</div>';
2282
2283
            if ($question['type'] == 'score') {
2284
                /** @todo This function should return the options as this is needed further in the code */
2285
                $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...
2286
            } elseif ($question['type'] == 'open') {
2287
                /** @todo Also get the user who has answered this */
2288
                $sql = "SELECT * FROM $table_survey_answer
2289
                        WHERE
2290
                            c_id = $course_id AND
2291
                            survey_id='" . intval($_GET['survey_id']) . "' AND
2292
                            question_id = '" . intval($question['question_id']) . "'";
2293
                $result = Database::query($sql);
2294
                while ($row = Database::fetch_array($result)) {
2295
                    echo $row['option_id'] . '<hr noshade="noshade" size="1" />';
2296
                }
2297
            } else {
2298
                // Getting the options ORDER BY sort ASC
2299
                $sql = "SELECT * FROM $table_survey_question_option
2300
                        WHERE
2301
                            c_id = $course_id AND
2302
                            survey_id='" . intval($_GET['survey_id']) . "'
2303
                            AND question_id = '" . intval($question['question_id']) . "'
2304
                        ORDER BY sort ASC";
2305
                $result = Database::query($sql);
2306
                while ($row = Database::fetch_array($result)) {
2307
                    $options[$row['question_option_id']] = $row;
2308
                }
2309
2310
                // Getting the answers
2311
                $sql = "SELECT *, count(answer_id) as total FROM $table_survey_answer
2312
                        WHERE
2313
                            c_id = $course_id AND
2314
                            survey_id='" . intval($_GET['survey_id']) . "'
2315
                            AND question_id = '" . intval($question['question_id']) . "'
2316
                        GROUP BY option_id, value";
2317
                $result = Database::query($sql);
2318
                $number_of_answers = array();
2319
                $data = array();
2320 View Code Duplication
                while ($row = Database::fetch_array($result)) {
2321
                    if (!isset($number_of_answers[$row['question_id']])) {
2322
                        $number_of_answers[$row['question_id']] = 0;
2323
                    }
2324
                    $number_of_answers[$row['question_id']] += $row['total'];
2325
                    $data[$row['option_id']] = $row;
2326
                }
2327
2328
                foreach ($options as $option) {
2329
                    $optionText = strip_tags($option['option_text']);
2330
                    $optionText = html_entity_decode($optionText);
2331
                    $votes = isset($data[$option['question_option_id']]['total']) ?
2332
                        $data[$option['question_option_id']]['total'] :
2333
                        '0';
2334
                    array_push($chartData, array('option' => $optionText, 'votes' => $votes));
2335
                }
2336
                $chartContainerId = 'chartContainer'.$question['question_id'];
2337
                echo '<div id="'.$chartContainerId.'" class="col-md-12">';
2338
                echo self::drawChart($chartData, false, $chartContainerId);
2339
2340
                // displaying the table: headers
2341
2342
                echo '<table class="display-survey table">';
2343
                echo '	<tr>';
2344
                echo '		<th>&nbsp;</th>';
2345
                echo '		<th>' . get_lang('AbsoluteTotal') . '</th>';
2346
                echo '		<th>' . get_lang('Percentage') . '</th>';
2347
                echo '		<th>' . get_lang('VisualRepresentation') . '</th>';
2348
                echo '	<tr>';
2349
2350
                // Displaying the table: the content
2351
                if (is_array($options)) {
2352
                    foreach ($options as $key => & $value) {
2353
                        $absolute_number = null;
2354
                        if (isset($data[$value['question_option_id']])) {
2355
                            $absolute_number = $data[$value['question_option_id']]['total'];
2356
                        }
2357
                        if ($question['type'] == 'percentage' && empty($absolute_number)) {
2358
                            continue;
2359
                        }
2360
                        if ($number_of_answers[$option['question_id']] == 0) {
2361
                            $answers_number = 0;
2362
                        } else {
2363
                            $answers_number = $absolute_number / $number_of_answers[$option['question_id']] * 100;
0 ignored issues
show
Bug introduced by
The variable $option seems to be defined by a foreach iteration on line 2328. 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...
2364
                        }
2365
                        echo '	<tr>';
2366
                        echo '		<td class="center">' . $value['option_text'] . '</td>';
2367
                        echo '		<td class="center">';
2368
                        if ($absolute_number != 0) {
2369
                            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>';
2370
                        } else {
2371
                            echo '0';
2372
                        }
2373
2374
                        echo '      </td>';
2375
                        echo '		<td class="center">' . round($answers_number, 2) . ' %</td>';
2376
                        echo '		<td class="center">';
2377
                        $size = $answers_number * 2;
2378
                        if ($size > 0) {
2379
                            echo '<div style="border:1px solid #264269; background-color:#aecaf4; height:10px; width:' . $size . 'px">&nbsp;</div>';
2380
                        } else {
2381
                            echo '<div style="text-align: left;">' . get_lang("NoDataAvailable") . '</div>';
2382
                        }
2383
                        echo ' </td>';
2384
                        echo ' </tr>';
2385
                    }
2386
                }
2387
                // displaying the table: footer (totals)
2388
                echo '	<tr>';
2389
                echo '		<td class="total"><b>' . get_lang('Total') . '</b></td>';
2390
                echo '		<td class="total"><b>' . ($number_of_answers[$option['question_id']] == 0 ? '0' : $number_of_answers[$option['question_id']]) . '</b></td>';
2391
                echo '		<td class="total">&nbsp;</td>';
2392
                echo '		<td class="total">&nbsp;</td>';
2393
                echo '	</tr>';
2394
2395
                echo '</table>';
2396
2397
                echo '</div>';
2398
            }
2399
        }
2400
        if (isset($_GET['viewoption'])) {
2401
            echo '<div class="answered-people">';
2402
2403
            echo '<h4>'.get_lang('PeopleWhoAnswered').': '.strip_tags($options[Security::remove_XSS($_GET['viewoption'])]['option_text']).'</h4>';
2404
2405
            if (is_numeric($_GET['value'])) {
2406
                $sql_restriction = "AND value='".Database::escape_string($_GET['value'])."'";
2407
            }
2408
2409
            $sql = "SELECT user FROM $table_survey_answer
2410
                    WHERE
2411
                        c_id = $course_id AND
2412
                        option_id = '".Database::escape_string($_GET['viewoption'])."'
2413
                        $sql_restriction";
2414
            $result = Database::query($sql);
2415
            echo '<ul>';
2416 View Code Duplication
            while ($row = Database::fetch_array($result)) {
2417
                $user_info = api_get_user_info($row['user']);
2418
                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>';
2419
            }
2420
            echo '</ul>';
2421
            echo '</div>';
2422
        }
2423
    }
2424
2425
    /**
2426
     * Display score data about a survey question
2427
     * @param	array	Question info
2428
     * @param	integer	The offset of results shown
2429
     * @return	void 	(direct output)
2430
     */
2431
    public static function display_question_report_score($survey_data, $question, $offset)
2432
    {
2433
        // Database table definitions
2434
        $table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
2435
        $table_survey_answer 			= Database :: get_course_table(TABLE_SURVEY_ANSWER);
2436
2437
        $course_id = api_get_course_int_id();
2438
2439
        // Getting the options
2440
        $sql = "SELECT * FROM $table_survey_question_option
2441
                WHERE
2442
                    c_id = $course_id AND
2443
                    survey_id='".Database::escape_string($_GET['survey_id'])."' AND
2444
                    question_id = '".Database::escape_string($question['question_id'])."'
2445
                ORDER BY sort ASC";
2446
        $result = Database::query($sql);
2447
        while ($row = Database::fetch_array($result)) {
2448
            $options[$row['question_option_id']] = $row;
2449
        }
2450
2451
        // Getting the answers
2452
        $sql = "SELECT *, count(answer_id) as total FROM $table_survey_answer
2453
                WHERE
2454
                   c_id = $course_id AND
2455
                   survey_id='".Database::escape_string($_GET['survey_id'])."' AND
2456
                   question_id = '".Database::escape_string($question['question_id'])."'
2457
                GROUP BY option_id, value";
2458
        $result = Database::query($sql);
2459
        $number_of_answers = 0;
2460 View Code Duplication
        while ($row = Database::fetch_array($result)) {
2461
            $number_of_answers += $row['total'];
2462
            $data[$row['option_id']][$row['value']] = $row;
2463
        }
2464
2465
        $chartData = array();
2466
        foreach ($options as $option) {
2467
            $optionText = strip_tags($option['option_text']);
2468
            $optionText = html_entity_decode($optionText);
2469
            for ($i = 1; $i <= $question['max_value']; $i++) {
2470
                $votes = $data[$option['question_option_id']][$i]['total'];
2471
                if (empty($votes)) {
2472
                    $votes = '0';
2473
                }
2474
                array_push(
2475
                    $chartData,
2476
                    array(
2477
                        'serie' => $optionText,
2478
                        'option' => $i,
2479
                        'votes' => $votes
2480
                    )
2481
                );
2482
            }
2483
        }
2484
        echo '<div id="chartContainer" class="col-md-12">';
2485
        echo self::drawChart($chartData, true);
2486
        echo '</div>';
2487
2488
        // Displaying the table: headers
2489
        echo '<table class="data_table">';
2490
        echo '	<tr>';
2491
        echo '		<th>&nbsp;</th>';
2492
        echo '		<th>'.get_lang('Score').'</th>';
2493
        echo '		<th>'.get_lang('AbsoluteTotal').'</th>';
2494
        echo '		<th>'.get_lang('Percentage').'</th>';
2495
        echo '		<th>'.get_lang('VisualRepresentation').'</th>';
2496
        echo '	<tr>';
2497
        // Displaying the table: the content
2498
        foreach ($options as $key => & $value) {
2499
            for ($i = 1; $i <= $question['max_value']; $i++) {
2500
                $absolute_number = $data[$value['question_option_id']][$i]['total'];
2501
                echo '	<tr>';
2502
                echo '		<td>'.$value['option_text'].'</td>';
2503
                echo '		<td>'.$i.'</td>';
2504
                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...
2505
                echo '		<td>'.round($absolute_number/$number_of_answers*100, 2).' %</td>';
2506
                echo '		<td>';
2507
                $size = ($absolute_number/$number_of_answers*100*2);
2508
                if ($size > 0) {
2509
                    echo '			<div style="border:1px solid #264269; background-color:#aecaf4; height:10px; width:'.$size.'px">&nbsp;</div>';
2510
                }
2511
                echo '		</td>';
2512
                echo '	</tr>';
2513
            }
2514
        }
2515
        // Displaying the table: footer (totals)
2516
        echo '	<tr>';
2517
        echo '		<td style="border-top:1px solid black"><b>'.get_lang('Total').'</b></td>';
2518
        echo '		<td style="border-top:1px solid black">&nbsp;</td>';
2519
        echo '		<td style="border-top:1px solid black"><b>'.$number_of_answers.'</b></td>';
2520
        echo '		<td style="border-top:1px solid black">&nbsp;</td>';
2521
        echo '		<td style="border-top:1px solid black">&nbsp;</td>';
2522
        echo '	</tr>';
2523
2524
        echo '</table>';
2525
    }
2526
2527
    /**
2528
     * This functions displays the complete reporting
2529
     * @return	string	HTML code
2530
     * @todo open questions are not in the complete report yet.
2531
     * @author Patrick Cool <[email protected]>, Ghent University
2532
     * @version February 2007
2533
     */
2534
    public static function display_complete_report($survey_data)
2535
    {
2536
        // Database table definitions
2537
        $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
2538
        $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
2539
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
2540
2541
        // Actions bar
2542
        echo '<div class="actions">';
2543
        echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.Security::remove_XSS($_GET['survey_id']).'">
2544
		'.Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('ReportingOverview'),'',ICON_SIZE_MEDIUM).'</a>';
2545
        echo '<a class="survey_export_link" href="javascript: void(0);" onclick="document.form1a.submit();">
2546
		'.Display::return_icon('export_csv.png',get_lang('ExportAsCSV'),'',ICON_SIZE_MEDIUM).'</a>';
2547
        echo '<a class="survey_export_link" href="javascript: void(0);" onclick="document.form1b.submit();">
2548
		'.Display::return_icon('export_excel.png',get_lang('ExportAsXLS'),'',ICON_SIZE_MEDIUM).'</a>';
2549
        echo '</div>';
2550
2551
        // The form
2552
        echo '<form id="form1a" name="form1a" method="post" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.Security::remove_XSS($_GET['survey_id']).'">';
2553
        echo '<input type="hidden" name="export_report" value="export_report">';
2554
        echo '<input type="hidden" name="export_format" value="csv">';
2555
        echo '</form>';
2556
        echo '<form id="form1b" name="form1b" method="post" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.Security::remove_XSS($_GET['survey_id']).'">';
2557
        echo '<input type="hidden" name="export_report" value="export_report">';
2558
        echo '<input type="hidden" name="export_format" value="xls">';
2559
        echo '</form>';
2560
2561
        echo '<form id="form2" name="form2" method="post" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.Security::remove_XSS($_GET['survey_id']).'">';
2562
2563
        // The table
2564
        echo '<br /><table class="data_table" border="1">';
2565
        // Getting the number of options per question
2566
        echo '	<tr>';
2567
        echo '		<th>';
2568
        if (isset($_POST['submit_question_filter']) && $_POST['submit_question_filter'] ||
2569
            isset($_POST['export_report']) && $_POST['export_report']) {
2570
            echo '<button class="cancel" type="submit" name="reset_question_filter" value="'.get_lang('ResetQuestionFilter').'">'.get_lang('ResetQuestionFilter').'</button>';
2571
        }
2572
        echo '<button class="save" type="submit" name="submit_question_filter" value="'.get_lang('SubmitQuestionFilter').'">'.get_lang('SubmitQuestionFilter').'</button>';
2573
        echo '</th>';
2574
2575
        $display_extra_user_fields = false;
2576
        if (!(isset($_POST['submit_question_filter']) && $_POST['submit_question_filter'] ||
2577
                isset($_POST['export_report']) && $_POST['export_report']) || !empty($_POST['fields_filter'])) {
2578
            // Show user fields section with a big th colspan that spans over all fields
2579
            $extra_user_fields = UserManager::get_extra_fields(0, 0, 5, 'ASC', false, true);
2580
            $num = count($extra_user_fields);
2581
            if ($num > 0 ) {
2582
                echo '<th '.($num>0?' colspan="'.$num.'"':'').'>';
2583
                echo '<label><input type="checkbox" name="fields_filter" value="1" checked="checked"/> ';
2584
                echo get_lang('UserFields');
2585
                echo '</label>';
2586
                echo '</th>';
2587
                $display_extra_user_fields = true;
2588
            }
2589
        }
2590
2591
        $course_id = api_get_course_int_id();
2592
2593
        // Get all the questions ordered by the "sort" column
2594
        // <hub> modify the query to display open questions too
2595
        //		$sql = "SELECT q.question_id, q.type, q.survey_question, count(o.question_option_id) as number_of_options
2596
        //				FROM $table_survey_question q LEFT JOIN $table_survey_question_option o
2597
        //				ON q.question_id = o.question_id
2598
        //				WHERE q.question_id = o.question_id
2599
        //				AND q.survey_id = '".Database::escape_string($_GET['survey_id'])."'
2600
        //				GROUP BY q.question_id
2601
        //				ORDER BY q.sort ASC";
2602
        $sql = "SELECT q.question_id, q.type, q.survey_question, count(o.question_option_id) as number_of_options
2603
				FROM $table_survey_question q LEFT JOIN $table_survey_question_option o
2604
				ON q.question_id = o.question_id
2605
				WHERE q.survey_id = '".Database::escape_string($_GET['survey_id'])."' AND
2606
				q.c_id = $course_id AND
2607
				o.c_id = $course_id
2608
				GROUP BY q.question_id
2609
				ORDER BY q.sort ASC";
2610
        // </hub>
2611
        $result = Database::query($sql);
2612
        while ($row = Database::fetch_array($result)) {
2613
            // We show the questions if
2614
            // 1. there is no question filter and the export button has not been clicked
2615
            // 2. there is a quesiton filter but the question is selected for display
2616
            //if (!($_POST['submit_question_filter'] || $_POST['export_report']) || in_array($row['question_id'], $_POST['questions_filter'])) {
2617
            if (!(isset($_POST['submit_question_filter']) && $_POST['submit_question_filter']) ||
2618
                (is_array($_POST['questions_filter']) &&
2619
                    in_array($row['question_id'], $_POST['questions_filter']))) {
2620
                // We do not show comment and pagebreak question types
2621
                if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
2622
                    echo ' <th';
2623
                    // <hub> modified tst to include percentage
2624
                    if ($row['number_of_options'] > 0 && $row['type'] != 'percentage') {
2625
                        // </hub>
2626
                        echo ' colspan="'.$row['number_of_options'].'"';
2627
                    }
2628
                    echo '>';
2629
2630
                    echo '<label><input type="checkbox" name="questions_filter[]" value="'.$row['question_id'].'" checked="checked"/> ';
2631
                    echo $row['survey_question'];
2632
                    echo '</label>';
2633
                    echo '</th>';
2634
                }
2635
                // No column at all if it's not a question
2636
            }
2637
            $questions[$row['question_id']] = $row;
2638
        }
2639
        echo '	</tr>';
2640
        // Getting all the questions and options
2641
        echo '	<tr>';
2642
        echo '		<th>&nbsp;</th>'; // the user column
2643
2644
        if (!(isset($_POST['submit_question_filter']) && $_POST['submit_question_filter'] ||
2645
                isset($_POST['export_report']) && $_POST['export_report']) || !empty($_POST['fields_filter'])) {
2646
            //show the fields names for user fields
2647
            foreach($extra_user_fields as & $field) {
2648
                echo '<th>'.$field[3].'</th>';
2649
            }
2650
        }
2651
2652
        // cells with option (none for open question)
2653
        $sql = "SELECT 	sq.question_id, sq.survey_id,
2654
						sq.survey_question, sq.display,
2655
						sq.sort, sq.type, sqo.question_option_id,
2656
						sqo.option_text, sqo.sort as option_sort
2657
				FROM $table_survey_question sq
2658
				LEFT JOIN $table_survey_question_option sqo
2659
				ON sq.question_id = sqo.question_id
2660
				WHERE
2661
				    sq.survey_id = '".Database::escape_string($_GET['survey_id'])."' AND
2662
                    sq.c_id = $course_id AND
2663
                    sqo.c_id = $course_id
2664
				ORDER BY sq.sort ASC, sqo.sort ASC";
2665
        $result = Database::query($sql);
2666
2667
        $display_percentage_header = 1;	// in order to display only once the cell option (and not 100 times)
2668
        while ($row = Database::fetch_array($result)) {
2669
            // We show the options if
2670
            // 1. there is no question filter and the export button has not been clicked
2671
            // 2. there is a question filter but the question is selected for display
2672
            //if (!($_POST['submit_question_filter'] || $_POST['export_report']) || in_array($row['question_id'], $_POST['questions_filter'])) {
2673
            if (!(isset($_POST['submit_question_filter']) && $_POST['submit_question_filter']) ||
2674
                (is_array($_POST['questions_filter']) && in_array($row['question_id'], $_POST['questions_filter']))
2675
            ) {
2676
                // <hub> modif 05-05-2010
2677
                // we do not show comment and pagebreak question types
2678
                if ($row['type'] == 'open') {
2679
                    echo '<th>&nbsp;-&nbsp;</th>';
2680
                    $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
2681
                    $display_percentage_header = 1;
2682
                } else if ($row['type'] == 'percentage' && $display_percentage_header) {
2683
                    echo '<th>&nbsp;%&nbsp;</th>';
2684
                    $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
2685
                    $display_percentage_header = 0;
2686
                } else if ($row['type'] == 'percentage') {
2687
                    $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
2688
                } else if ($row['type'] <> 'comment' AND $row['type'] <> 'pagebreak' AND $row['type'] <> 'percentage') {
2689
                    echo '<th>';
2690
                    echo $row['option_text'];
2691
                    echo '</th>';
2692
                    $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
2693
                    $display_percentage_header = 1;
2694
                }
2695
                //no column at all if the question was not a question
2696
                // </hub>
2697
            }
2698
        }
2699
2700
        echo '	</tr>';
2701
2702
        // Getting all the answers of the users
2703
        $old_user = '';
2704
        $answers_of_user = array();
2705
        $sql = "SELECT * FROM $table_survey_answer
2706
                WHERE
2707
                    c_id = $course_id AND
2708
                    survey_id='".intval($_GET['survey_id'])."'
2709
                ORDER BY answer_id, user ASC";
2710
        $result = Database::query($sql);
2711
        $i = 1;
2712
        while ($row = Database::fetch_array($result)) {
2713
            if ($old_user != $row['user'] && $old_user != '') {
2714
                $userParam = $old_user;
2715
                if ($survey_data['anonymous'] != 0) {
2716
                    $userParam = $i;
2717
                    $i++;
2718
                }
2719
                SurveyUtil::display_complete_report_row(
2720
                    $survey_data,
2721
                    $possible_answers,
2722
                    $answers_of_user,
2723
                    $userParam,
2724
                    $questions,
2725
                    $display_extra_user_fields
2726
                );
2727
                $answers_of_user=array();
2728
            }
2729
            if (isset($questions[$row['question_id']]) && $questions[$row['question_id']]['type'] != 'open') {
2730
                $answers_of_user[$row['question_id']][$row['option_id']] = $row;
2731
            } else {
2732
                $answers_of_user[$row['question_id']][0] = $row;
2733
            }
2734
            $old_user = $row['user'];
2735
        }
2736
        $userParam = $old_user;
2737
        if ($survey_data['anonymous'] != 0) {
2738
            $userParam = $i;
2739
            $i++;
2740
        }
2741
        SurveyUtil::display_complete_report_row(
2742
            $survey_data,
2743
            $possible_answers,
2744
            $answers_of_user,
2745
            $userParam,
2746
            $questions,
2747
            $display_extra_user_fields
2748
        );
2749
        // This is to display the last user
2750
        echo '</table>';
2751
        echo '</form>';
2752
    }
2753
2754
    /**
2755
     * This function displays a row (= a user and his/her answers) in the table of the complete report.
2756
     *
2757
     * @param array $survey_data
2758
     * @param 	array	Possible options
2759
     * @param 	array 	User answers
2760
     * @param	mixed	User ID or user details string
2761
     * @param	boolean	Whether to show extra user fields or not
2762
     * @author Patrick Cool <[email protected]>, Ghent University
2763
     * @version February 2007 - Updated March 2008
2764
     */
2765
    static function display_complete_report_row(
2766
        $survey_data,
2767
        $possible_options,
2768
        $answers_of_user,
2769
        $user,
2770
        $questions,
2771
        $display_extra_user_fields = false
2772
    ) {
2773
        $user = Security::remove_XSS($user);
2774
        echo '<tr>';
2775
        if ($survey_data['anonymous'] == 0) {
2776
            if (intval($user) !== 0) {
2777
                $userInfo = api_get_user_info($user);
2778
                if (!empty($userInfo)) {
2779
                    $user_displayed = $userInfo['complete_name'];
2780
                } else {
2781
                    $user_displayed = '-';
2782
                }
2783
                echo '<th><a href="'.api_get_self().'?action=userreport&survey_id='.Security::remove_XSS($_GET['survey_id']).'&user='.$user.'">'.
2784
                    $user_displayed.'</a></th>'; // the user column
2785
            } else {
2786
                echo '<th>'.$user.'</th>'; // the user column
2787
            }
2788
        } else {
2789
            echo '<th>' . get_lang('Anonymous') . ' ' . $user . '</th>';
2790
        }
2791
2792
        if ($display_extra_user_fields) {
2793
            // Show user fields data, if any, for this user
2794
            $user_fields_values = UserManager::get_extra_user_data(intval($user), false, false, false, true);
2795
            foreach ($user_fields_values as & $value) {
2796
                echo '<td align="center">'.$value.'</td>';
2797
            }
2798
        }
2799
        if (is_array($possible_options)) {
2800
            // <hub> modified to display open answers and percentage
2801
            foreach ($possible_options as $question_id => & $possible_option) {
2802
                if ($questions[$question_id]['type'] == 'open') {
2803
                    echo '<td align="center">';
2804
                    echo $answers_of_user[$question_id]['0']['option_id'];
2805
                    echo '</td>';
2806
                } else {
2807
                    foreach ($possible_option as $option_id => & $value) {
2808
                        if ($questions[$question_id]['type'] == 'percentage') {
2809 View Code Duplication
                            if (!empty($answers_of_user[$question_id][$option_id])) {
2810
                                echo "<td align='center'>";
2811
                                echo $answers_of_user[$question_id][$option_id]['value'];
2812
                                echo "</td>";
2813
                            }
2814
                        }
2815
                        else {
2816
                            echo '<td align="center">';
2817
                            if (!empty($answers_of_user[$question_id][$option_id])) {
2818 View Code Duplication
                                if ($answers_of_user[$question_id][$option_id]['value'] != 0) {
2819
                                    echo $answers_of_user[$question_id][$option_id]['value'];
2820
                                }
2821
                                else {
2822
                                    echo 'v';
2823
                                }
2824
                            }
2825
                        } // </hub>
2826
                    }
2827
                }
2828
            }
2829
        }
2830
        echo '</tr>';
2831
    }
2832
2833
    /**
2834
     * Quite similar to display_complete_report(), returns an HTML string
2835
     * that can be used in a csv file
2836
     * @todo consider merging this function with display_complete_report
2837
     * @return	string	The contents of a csv file
2838
     * @author Patrick Cool <[email protected]>, Ghent University
2839
     * @version February 2007
2840
     */
2841
    public static function export_complete_report($survey_data, $user_id = 0)
2842
    {
2843
        // Database table definitions
2844
        $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
2845
        $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
2846
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
2847
2848
        // The first column
2849
        $return = ';';
2850
2851
        // Show extra fields blank space (enough for extra fields on next line)
2852
2853
        $extra_user_fields = UserManager::get_extra_fields(0, 0, 5, 'ASC', false, true);
2854
2855
        $num = count($extra_user_fields);
2856
        $return .= str_repeat(';', $num);
2857
2858
        $course_id = api_get_course_int_id();
2859
2860
        $sql = "SELECT
2861
                    questions.question_id,
2862
                    questions.type,
2863
                    questions.survey_question,
2864
                    count(options.question_option_id) as number_of_options
2865
				FROM $table_survey_question questions
2866
                LEFT JOIN $table_survey_question_option options
2867
				ON questions.question_id = options.question_id  AND options.c_id = $course_id
2868
				WHERE
2869
				    questions.survey_id = '".intval($_GET['survey_id'])."' AND
2870
                    questions.c_id = $course_id
2871
				GROUP BY questions.question_id
2872
				ORDER BY questions.sort ASC";
2873
        $result = Database::query($sql);
2874
        while ($row = Database::fetch_array($result)) {
2875
            // We show the questions if
2876
            // 1. there is no question filter and the export button has not been clicked
2877
            // 2. there is a quesiton filter but the question is selected for display
2878
            if (!($_POST['submit_question_filter']) ||
2879
                (is_array($_POST['questions_filter']) &&
2880
                    in_array($row['question_id'], $_POST['questions_filter']))
2881
            ) {
2882
                // We do not show comment and pagebreak question types
2883
                if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
2884
                    if ($row['number_of_options'] == 0 && $row['type'] == 'open') {
2885
                        $return .= str_replace("\r\n",'  ', api_html_entity_decode(strip_tags($row['survey_question']), ENT_QUOTES)).';';
2886
                    } else {
2887
                        for ($ii = 0; $ii < $row['number_of_options']; $ii++) {
2888
                            $return .= str_replace("\r\n",'  ', api_html_entity_decode(strip_tags($row['survey_question']), ENT_QUOTES)).';';
2889
                        }
2890
                    }
2891
                }
2892
            }
2893
        }
2894
        $return .= "\n";
2895
2896
        // Getting all the questions and options
2897
        $return .= ';';
2898
2899
        // Show the fields names for user fields
2900
        if (!empty($extra_user_fields)) {
2901
            foreach ($extra_user_fields as & $field) {
2902
                $return .= '"'.str_replace("\r\n",'  ',api_html_entity_decode(strip_tags($field[3]), ENT_QUOTES)).'";';
2903
            }
2904
        }
2905
2906
        $sql = "SELECT
2907
		            survey_question.question_id,
2908
		            survey_question.survey_id,
2909
		            survey_question.survey_question,
2910
		            survey_question.display,
2911
		            survey_question.sort,
2912
		            survey_question.type,
2913
                    survey_question_option.question_option_id,
2914
                    survey_question_option.option_text,
2915
                    survey_question_option.sort as option_sort
2916
				FROM $table_survey_question survey_question
2917
				LEFT JOIN $table_survey_question_option survey_question_option
2918
				ON
2919
				    survey_question.question_id = survey_question_option.question_id AND
2920
				    survey_question_option.c_id = $course_id
2921
				WHERE
2922
				    survey_question.survey_id = '".intval($_GET['survey_id'])."' AND
2923
				    survey_question.c_id = $course_id
2924
				ORDER BY survey_question.sort ASC, survey_question_option.sort ASC";
2925
        $result = Database::query($sql);
2926
        $possible_answers = array();
2927
        $possible_answers_type = array();
2928
        while ($row = Database::fetch_array($result)) {
2929
            // We show the options if
2930
            // 1. there is no question filter and the export button has not been clicked
2931
            // 2. there is a quesiton filter but the question is selected for display
2932
            if (!($_POST['submit_question_filter']) || (is_array($_POST['questions_filter']) &&
2933
                in_array($row['question_id'], $_POST['questions_filter']))
2934
            ) {
2935
                // We do not show comment and pagebreak question types
2936
                if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
2937
                    $row['option_text'] = str_replace(array("\r","\n"),array('',''),$row['option_text']);
2938
                    $return .= api_html_entity_decode(strip_tags($row['option_text']), ENT_QUOTES).';';
2939
                    $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
2940
                    $possible_answers_type[$row['question_id']] = $row['type'];
2941
                }
2942
            }
2943
        }
2944
        $return .= "\n";
2945
2946
        // Getting all the answers of the users
2947
        $old_user = '';
2948
        $answers_of_user = array();
2949
        $sql = "SELECT * FROM $table_survey_answer
2950
		        WHERE c_id = $course_id AND survey_id='".Database::escape_string($_GET['survey_id'])."'";
2951
        if ($user_id != 0) {
2952
            $sql .= "AND user='".Database::escape_string($user_id)."' ";
2953
        }
2954
        $sql .= "ORDER BY user ASC";
2955
2956
        $open_question_iterator = 1;
2957
        $result = Database::query($sql);
2958
        while ($row = Database::fetch_array($result)) {
2959
            if ($old_user != $row['user'] && $old_user != '') {
2960
                $return .= SurveyUtil::export_complete_report_row(
2961
                    $survey_data,
2962
                    $possible_answers,
2963
                    $answers_of_user,
2964
                    $old_user,
2965
                    true
2966
                );
2967
                $answers_of_user=array();
2968
            }
2969 View Code Duplication
            if($possible_answers_type[$row['question_id']] == 'open') {
2970
                $temp_id = 'open'.$open_question_iterator;
2971
                $answers_of_user[$row['question_id']][$temp_id] = $row;
2972
                $open_question_iterator++;
2973
            } else {
2974
                $answers_of_user[$row['question_id']][$row['option_id']] = $row;
2975
            }
2976
            $old_user = $row['user'];
2977
        }
2978
        // This is to display the last user
2979
        $return .= SurveyUtil::export_complete_report_row(
2980
            $survey_data,
2981
            $possible_answers,
2982
            $answers_of_user,
2983
            $old_user,
2984
            true
2985
        );
2986
2987
        return $return;
2988
    }
2989
2990
    /**
2991
     * Add a line to the csv file
2992
     *
2993
     * @param	array	Possible answers
2994
     * @param	array	User's answers
2995
     * @param 	mixed	User ID or user details as string - Used as a string in the result string
2996
     * @param	boolean	Whether to display user fields or not
2997
     * @return	string	One line of the csv file
2998
     * @author Patrick Cool <[email protected]>, Ghent University
2999
     * @version February 2007
3000
     */
3001
    static function export_complete_report_row(
3002
        $survey_data,
3003
        $possible_options,
3004
        $answers_of_user,
3005
        $user,
3006
        $display_extra_user_fields = false
3007
    ) {
3008
        $return = '';
3009
        if ($survey_data['anonymous'] == 0) {
3010
            if (intval($user) !== 0) {
3011
                $userInfo = api_get_user_info($user);
3012
3013
                if (!empty($userInfo)) {
3014
                    $user_displayed = $userInfo['complete_name'];
3015
                } else {
3016
                    $user_displayed = '-';
3017
                }
3018
                $return .= $user_displayed.';';
3019
            } else {
3020
                $return .= $user.';';
3021
            }
3022
        } else {
3023
            $return .= '-;'; // The user column
3024
        }
3025
3026 View Code Duplication
        if ($display_extra_user_fields) {
3027
            // Show user fields data, if any, for this user
3028
            $user_fields_values = UserManager::get_extra_user_data($user,false,false, false, true);
3029
            foreach ($user_fields_values as & $value) {
3030
                $return .= '"'.str_replace('"', '""', api_html_entity_decode(strip_tags($value), ENT_QUOTES)).'";';
3031
            }
3032
        }
3033
3034
        if (is_array($possible_options)) {
3035
            foreach ($possible_options as $question_id => $possible_option) {
3036
                if (is_array($possible_option) && count($possible_option) > 0) {
3037
                    foreach ($possible_option as $option_id => & $value) {
3038
                        $my_answer_of_user = ($answers_of_user[$question_id] == null) ? array() : $answers_of_user[$question_id];
3039
                        $key = array_keys($my_answer_of_user);
3040
                        if (substr($key[0], 0, 4) == 'open') {
3041
                            $return .= '"'.str_replace('"', '""', api_html_entity_decode(strip_tags($answers_of_user[$question_id][$key[0]]['option_id']), ENT_QUOTES)).'"';
3042
                        } elseif (!empty($answers_of_user[$question_id][$option_id])) {
3043
                            //$return .= 'v';
3044
                            if ($answers_of_user[$question_id][$option_id]['value'] != 0) {
3045
                                $return .= $answers_of_user[$question_id][$option_id]['value'];
3046
                            } else {
3047
                                $return .= 'v';
3048
                            }
3049
                        }
3050
                        $return .= ';';
3051
                    }
3052
                }
3053
            }
3054
        }
3055
        $return .= "\n";
3056
        return $return;
3057
    }
3058
3059
    /**
3060
     * Quite similar to display_complete_report(), returns an HTML string
3061
     * that can be used in a csv file
3062
     * @todo consider merging this function with display_complete_report
3063
     * @return	string	The contents of a csv file
3064
     * @author Patrick Cool <[email protected]>, Ghent University
3065
     * @version February 2007
3066
     */
3067
    static function export_complete_report_xls($survey_data, $filename, $user_id = 0)
3068
    {
3069
        $spreadsheet = new PHPExcel();
3070
        $spreadsheet->setActiveSheetIndex(0);
3071
        $worksheet = $spreadsheet->getActiveSheet();
3072
        $line = 1;
3073
        $column = 1; // Skip the first column (row titles)
3074
3075
        // Show extra fields blank space (enough for extra fields on next line)
3076
        // Show user fields section with a big th colspan that spans over all fields
3077
        $extra_user_fields = UserManager::get_extra_fields(0, 0, 5, 'ASC', false, true);
3078
        $num = count($extra_user_fields);
3079
        for ($i = 0; $i < $num; $i++) {
3080
            $worksheet->setCellValueByColumnAndRow($column, $line, '');
3081
            $column++;
3082
        }
3083
        $display_extra_user_fields = true;
3084
3085
        // Database table definitions
3086
        $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
3087
        $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
3088
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
3089
3090
        $course_id = api_get_course_int_id();
3091
3092
        // First line (questions)
3093
        $sql = "SELECT
3094
                    questions.question_id,
3095
                    questions.type,
3096
                    questions.survey_question,
3097
                    count(options.question_option_id) as number_of_options
3098
				FROM $table_survey_question questions
3099
				LEFT JOIN $table_survey_question_option options
3100
                ON questions.question_id = options.question_id AND options.c_id = $course_id
3101
				WHERE
3102
				    questions.survey_id = '".intval($_GET['survey_id'])."' AND
3103
				    questions.c_id = $course_id
3104
				GROUP BY questions.question_id
3105
				ORDER BY questions.sort ASC";
3106
        $result = Database::query($sql);
3107
        while ($row = Database::fetch_array($result)) {
3108
            // We show the questions if
3109
            // 1. there is no question filter and the export button has not been clicked
3110
            // 2. there is a quesiton filter but the question is selected for display
3111
            if (!(isset($_POST['submit_question_filter'])) || (is_array($_POST['questions_filter']) &&
3112
                in_array($row['question_id'], $_POST['questions_filter']))
3113
            ) {
3114
                // We do not show comment and pagebreak question types
3115
                if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
3116
                    if ($row['number_of_options'] == 0 && $row['type'] == 'open') {
3117
                        $worksheet->setCellValueByColumnAndRow(
3118
                            $column,
3119
                            $line,
3120
                            api_html_entity_decode(
3121
                                strip_tags($row['survey_question']),
3122
                                ENT_QUOTES
3123
                            )
3124
                        );
3125
                        $column ++;
3126
                    } else {
3127
                        for ($ii = 0; $ii < $row['number_of_options']; $ii ++) {
3128
                            $worksheet->setCellValueByColumnAndRow(
3129
                                $column,
3130
                                $line,
3131
                                api_html_entity_decode(
3132
                                    strip_tags($row['survey_question']),
3133
                                    ENT_QUOTES
3134
                                )
3135
                            );
3136
                            $column ++;
3137
                        }
3138
                    }
3139
                }
3140
            }
3141
        }
3142
        $line++;
3143
        $column = 1;
3144
3145
        // Show extra field values
3146
        if ($display_extra_user_fields) {
3147
            // Show the fields names for user fields
3148
            foreach ($extra_user_fields as & $field) {
3149
                $worksheet->setCellValueByColumnAndRow(
3150
                    $column,
3151
                    $line,
3152
                    api_html_entity_decode(strip_tags($field[3]), ENT_QUOTES)
3153
                );
3154
                $column++;
3155
            }
3156
        }
3157
3158
        // Getting all the questions and options (second line)
3159
        $sql = "SELECT
3160
                    survey_question.question_id, survey_question.survey_id, survey_question.survey_question, survey_question.display, survey_question.sort, survey_question.type,
3161
                    survey_question_option.question_option_id, survey_question_option.option_text, survey_question_option.sort as option_sort
3162
				FROM $table_survey_question survey_question
3163
				LEFT JOIN $table_survey_question_option survey_question_option
3164
				ON survey_question.question_id = survey_question_option.question_id AND survey_question_option.c_id = $course_id
3165
				WHERE survey_question.survey_id = '".intval($_GET['survey_id'])."' AND
3166
				survey_question.c_id = $course_id
3167
				ORDER BY survey_question.sort ASC, survey_question_option.sort ASC";
3168
        $result = Database::query($sql);
3169
        $possible_answers = array();
3170
        $possible_answers_type = array();
3171
        while ($row = Database::fetch_array($result)) {
3172
            // We show the options if
3173
            // 1. there is no question filter and the export button has not been clicked
3174
            // 2. there is a quesiton filter but the question is selected for display
3175
            if (!(isset($_POST['submit_question_filter'])) ||
3176
                (is_array($_POST['questions_filter']) && in_array($row['question_id'], $_POST['questions_filter']))
3177
            ) {
3178
                // We do not show comment and pagebreak question types
3179
                if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
3180
                    $worksheet->setCellValueByColumnAndRow(
3181
                        $column,
3182
                        $line,
3183
                        api_html_entity_decode(
3184
                            strip_tags($row['option_text']),
3185
                            ENT_QUOTES
3186
                        )
3187
                    );
3188
                    $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
3189
                    $possible_answers_type[$row['question_id']] = $row['type'];
3190
                    $column++;
3191
                }
3192
            }
3193
        }
3194
3195
        // Getting all the answers of the users
3196
        $line ++;
3197
        $column = 0;
3198
        $old_user = '';
3199
        $answers_of_user = array();
3200
        $sql = "SELECT * FROM $table_survey_answer
3201
                WHERE c_id = $course_id AND survey_id='".intval($_GET['survey_id'])."' ";
3202
        if ($user_id != 0) {
3203
            $sql .= "AND user='".intval($user_id)."' ";
3204
        }
3205
        $sql .=	"ORDER BY user ASC";
3206
3207
        $open_question_iterator = 1;
3208
        $result = Database::query($sql);
3209
        while ($row = Database::fetch_array($result)) {
3210
            if ($old_user != $row['user'] && $old_user != '') {
3211
                $return = SurveyUtil::export_complete_report_row_xls(
3212
                    $survey_data,
3213
                    $possible_answers,
3214
                    $answers_of_user,
3215
                    $old_user,
3216
                    true
3217
                );
3218
                foreach ($return as $elem) {
3219
                    $worksheet->setCellValueByColumnAndRow($column, $line, $elem);
3220
                    $column++;
3221
                }
3222
                $answers_of_user = array();
3223
                $line++;
3224
                $column = 0;
3225
            }
3226 View Code Duplication
            if ($possible_answers_type[$row['question_id']] == 'open') {
3227
                $temp_id = 'open'.$open_question_iterator;
3228
                $answers_of_user[$row['question_id']][$temp_id] = $row;
3229
                $open_question_iterator++;
3230
            } else {
3231
                $answers_of_user[$row['question_id']][$row['option_id']] = $row;
3232
            }
3233
            $old_user = $row['user'];
3234
        }
3235
        $return = SurveyUtil::export_complete_report_row_xls(
3236
            $survey_data,
3237
            $possible_answers,
3238
            $answers_of_user,
3239
            $old_user,
3240
            true
3241
        );
3242
3243
        // this is to display the last user
3244
        foreach ($return as $elem) {
3245
            $worksheet->setCellValueByColumnAndRow($column, $line, $elem);
3246
            $column++;
3247
        }
3248
3249
        $file = api_get_path(SYS_ARCHIVE_PATH).api_replace_dangerous_char($filename);
3250
        $writer = new PHPExcel_Writer_Excel2007($spreadsheet);
3251
        $writer->save($file);
3252
        DocumentManager::file_send_for_download($file, true, $filename);
3253
3254
        return null;
3255
    }
3256
3257
    /**
3258
     * Add a line to the csv file
3259
     *
3260
     * @param	array	Possible answers
3261
     * @param	array	User's answers
3262
     * @param 	mixed	User ID or user details as string - Used as a string in the result string
3263
     * @param	boolean	Whether to display user fields or not
3264
     * @return	string	One line of the csv file
3265
     */
3266
    public static function export_complete_report_row_xls(
3267
        $survey_data,
3268
        $possible_options,
3269
        $answers_of_user,
3270
        $user,
3271
        $display_extra_user_fields = false
3272
    ) {
3273
        $return = array();
3274
        if ($survey_data['anonymous'] == 0) {
3275
            if (intval($user) !== 0) {
3276
                $sql = 'SELECT firstname, lastname
3277
                        FROM '.Database::get_main_table(TABLE_MAIN_USER).'
3278
                        WHERE user_id='.intval($user);
3279
                $rs = Database::query($sql);
3280
                if($row = Database::fetch_array($rs)) {
3281
                    $user_displayed = api_get_person_name($row['firstname'], $row['lastname']);
3282
                } else {
3283
                    $user_displayed = '-';
3284
                }
3285
                $return[] = $user_displayed;
3286
            } else {
3287
                $return[] = $user;
3288
            }
3289
        } else {
3290
            $return[] = '-'; // The user column
3291
        }
3292
3293
        if ($display_extra_user_fields) {
3294
            //show user fields data, if any, for this user
3295
            $user_fields_values = UserManager::get_extra_user_data(intval($user),false,false, false, true);
3296
            foreach($user_fields_values as $value) {
3297
                $return[] = api_html_entity_decode(strip_tags($value), ENT_QUOTES);
3298
            }
3299
        }
3300
3301
        if (is_array($possible_options)) {
3302
            foreach ($possible_options as $question_id => & $possible_option) {
3303
                if (is_array($possible_option) && count($possible_option) > 0) {
3304
                    foreach ($possible_option as $option_id => & $value) {
3305
                        $my_answers_of_user = isset($answers_of_user[$question_id]) ? $answers_of_user[$question_id] : [];
3306
                        $key = array_keys($my_answers_of_user);
3307
                        if (isset($key[0]) && substr($key[0], 0, 4) == 'open') {
3308
                            $return[] = api_html_entity_decode(strip_tags($answers_of_user[$question_id][$key[0]]['option_id']), ENT_QUOTES);
3309
                        } elseif (!empty($answers_of_user[$question_id][$option_id])) {
3310
                            //$return .= 'v';
3311
                            if ($answers_of_user[$question_id][$option_id]['value'] != 0) {
3312
                                $return[] = $answers_of_user[$question_id][$option_id]['value'];
3313
                            } else {
3314
                                $return[] = 'v';
3315
                            }
3316
                        } else {
3317
                            $return[] = '';
3318
                        }
3319
                    }
3320
                }
3321
            }
3322
        }
3323
3324
        return $return;
3325
    }
3326
3327
    /**
3328
     * This function displays the comparative report which allows you to compare two questions
3329
     * A comparative report creates a table where one question is on the x axis and a second question is on the y axis.
3330
     * In the intersection is the number of people who have answerd positive on both options.
3331
     *
3332
     * @return	string	HTML code
3333
     *
3334
     * @author Patrick Cool <[email protected]>, Ghent University
3335
     * @version February 2007
3336
     */
3337
    public static function display_comparative_report()
3338
    {
3339
        // Allowed question types for comparative report
3340
        $allowed_question_types = array(
3341
            'yesno',
3342
            'multiplechoice',
3343
            'multipleresponse',
3344
            'dropdown',
3345
            'percentage',
3346
            'score',
3347
        );
3348
3349
        // Getting all the questions
3350
        $questions = SurveyManager::get_questions($_GET['survey_id']);
3351
3352
        // Actions bar
3353
        echo '<div class="actions">';
3354
        echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.intval($_GET['survey_id']).'">'.
3355
                Display::return_icon('back.png', get_lang('BackTo').' '.get_lang('ReportingOverview'),'',ICON_SIZE_MEDIUM).'</a>';
3356
        echo '</div>';
3357
3358
        // Displaying an information message that only the questions with predefined answers can be used in a comparative report
3359
        Display::display_normal_message(get_lang('OnlyQuestionsWithPredefinedAnswers'), false);
3360
3361
        // The form for selecting the axis of the table
3362
        echo '<form id="form1" name="form1" method="get" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.intval($_GET['survey_id']).'&xaxis='.Security::remove_XSS($_GET['xaxis']).'&y='.Security::remove_XSS($_GET['yaxis']).'">';
3363
        // Survey_id
3364
        echo '<input type="hidden" name="action" value="'.Security::remove_XSS($_GET['action']).'"/>';
3365
        echo '<input type="hidden" name="survey_id" value="'.Security::remove_XSS($_GET['survey_id']).'"/>';
3366
        // X axis
3367
        echo get_lang('SelectXAxis').': ';
3368
        echo '<select name="xaxis">';
3369
        echo '<option value="">---</option>';
3370 View Code Duplication
        foreach ($questions as $key => & $question) {
3371
            if (is_array($allowed_question_types)) {
3372
                if (in_array($question['type'], $allowed_question_types)) {
3373
                    echo '<option value="'.$question['question_id'].'"';
3374
                    if (isset($_GET['xaxis']) && $_GET['xaxis'] == $question['question_id']) {
3375
                        echo ' selected="selected"';
3376
                    }
3377
                    echo '">'.api_substr(strip_tags($question['question']), 0, 50).'</option>';
3378
                }
3379
            }
3380
3381
        }
3382
        echo '</select><br /><br />';
3383
        // Y axis
3384
        echo get_lang('SelectYAxis').': ';
3385
        echo '<select name="yaxis">';
3386
        echo '<option value="">---</option>';
3387 View Code Duplication
        foreach ($questions as $key => &$question) {
3388
            if (in_array($question['type'], $allowed_question_types)) {
3389
                echo '<option value="'.$question['question_id'].'"';
3390
                if (isset($_GET['yaxis']) && $_GET['yaxis'] == $question['question_id']) {
3391
                    echo ' selected="selected"';
3392
                }
3393
                echo '">'.api_substr(strip_tags($question['question']), 0, 50).'</option>';
3394
            }
3395
        }
3396
        echo '</select><br /><br />';
3397
        echo '<button class="save" type="submit" name="Submit" value="Submit">'.get_lang('CompareQuestions').'</button>';
3398
        echo '</form>';
3399
3400
        // Getting all the information of the x axis
3401 View Code Duplication
        if (isset($_GET['xaxis']) && is_numeric($_GET['xaxis'])) {
3402
            $question_x = SurveyManager::get_question($_GET['xaxis']);
3403
        }
3404
3405
        // Getting all the information of the y axis
3406 View Code Duplication
        if (isset($_GET['yaxis']) && is_numeric($_GET['yaxis'])) {
3407
            $question_y = SurveyManager::get_question($_GET['yaxis']);
3408
        }
3409
3410
        if (isset($_GET['xaxis']) && is_numeric($_GET['xaxis']) && isset($_GET['yaxis']) && is_numeric($_GET['yaxis'])) {
3411
            // Getting the answers of the two questions
3412
            $answers_x = SurveyUtil::get_answers_of_question_by_user($_GET['survey_id'], $_GET['xaxis']);
3413
            $answers_y = SurveyUtil::get_answers_of_question_by_user($_GET['survey_id'], $_GET['yaxis']);
3414
3415
            // Displaying the table
3416
            $tableHtml = '<table border="1" class="data_table">';
3417
3418
            $xOptions = array();
3419
            // The header
3420
            $tableHtml .=  '	<tr>';
3421
            for ($ii = 0; $ii <= count($question_x['answers']); $ii++) {
3422
                if ($ii == 0) {
3423
                    $tableHtml .=  '		<th>&nbsp;</th>';
3424
                } else {
3425
                    if ($question_x['type'] == 'score') {
3426
                        for ($x = 1; $x <= $question_x['maximum_score']; $x++) {
3427
                            $tableHtml .= '		<th>'.$question_x['answers'][($ii-1)].'<br />'.$x.'</th>';
3428
                        }
3429
                        $x = '';
3430
                    } else {
3431
                        $tableHtml .= '		<th>'.$question_x['answers'][($ii-1)].'</th>';
3432
                    }
3433
                    $optionText = strip_tags($question_x['answers'][$ii-1]);
3434
                    $optionText = html_entity_decode($optionText);
3435
                    array_push($xOptions, trim($optionText));
3436
                }
3437
            }
3438
            $tableHtml .=  '	</tr>';
3439
            $chartData = array();
3440
3441
            // The main part
3442
            for ($ij = 0; $ij < count($question_y['answers']); $ij++) {
3443
                $currentYQuestion = strip_tags($question_y['answers'][$ij]);
3444
                $currentYQuestion = html_entity_decode($currentYQuestion);
3445
                // The Y axis is a scoring question type so we have more rows than the options (actually options * maximum score)
3446
                if ($question_y['type'] == 'score') {
3447
                    for ($y = 1; $y <= $question_y['maximum_score']; $y++) {
3448
                        $tableHtml .=  '	<tr>';
3449
                        for ($ii = 0; $ii <= count($question_x['answers']); $ii++) {
3450
                            if ($question_x['type'] == 'score') {
3451 View Code Duplication
                                for ($x = 1; $x <= $question_x['maximum_score']; $x++) {
3452
                                    if ($ii == 0) {
3453
                                        $tableHtml .=  ' <th>'.$question_y['answers'][($ij)].' '.$y.'</th>';
3454
                                        break;
3455
                                    } else {
3456
                                        $tableHtml .=  ' <td align="center">';
3457
                                        $votes = SurveyUtil::comparative_check(
3458
                                            $answers_x,
3459
                                            $answers_y,
3460
                                            $question_x['answersid'][($ii - 1)],
3461
                                            $question_y['answersid'][($ij)],
3462
                                            $x,
3463
                                            $y
3464
                                        );
3465
                                        $tableHtml .=  $votes;
3466
                                        array_push(
3467
                                            $chartData,
3468
                                            array(
3469
                                                'serie' => array($currentYQuestion, $xOptions[$ii-1]),
3470
                                                'option' => $x,
3471
                                                'votes' => $votes
3472
                                            )
3473
                                        );
3474
                                        $tableHtml .=  '</td>';
3475
                                    }
3476
                                }
3477
                            } else {
3478
                                if ($ii == 0) {
3479
                                    $tableHtml .=  '<th>'.$question_y['answers'][$ij].' '.$y.'</th>';
3480
                                } else {
3481
                                    $tableHtml .=  '<td align="center">';
3482
                                    $votes = SurveyUtil::comparative_check(
3483
                                        $answers_x,
3484
                                        $answers_y,
3485
                                        $question_x['answersid'][($ii - 1)],
3486
                                        $question_y['answersid'][($ij)],
3487
                                        0,
3488
                                        $y
3489
                                    );
3490
                                    $tableHtml .= $votes;
3491
                                    array_push(
3492
                                        $chartData,
3493
                                        array(
3494
                                            'serie' => array($currentYQuestion, $xOptions[$ii-1]),
3495
                                            'option' => $y,
3496
                                            'votes' => $votes
3497
                                        )
3498
                                    );
3499
                                    $tableHtml .=  '</td>';
3500
                                }
3501
                            }
3502
                        }
3503
                        $tableHtml .=  '	</tr>';
3504
                    }
3505
                }
3506
                // The Y axis is NOT a score question type so the number of rows = the number of options
3507
                else {
3508
                    $tableHtml .=  '	<tr>';
3509
                    for ($ii = 0; $ii <= count($question_x['answers']); $ii++) {
3510
                        if ($question_x['type'] == 'score') {
3511 View Code Duplication
                            for ($x = 1; $x <= $question_x['maximum_score']; $x++) {
3512
                                if ($ii == 0) {
3513
                                    $tableHtml .=  '		<th>'.$question_y['answers'][$ij].'</th>';
3514
                                    break;
3515
                                } else {
3516
                                    $tableHtml .=  '		<td align="center">';
3517
                                    $votes =  SurveyUtil::comparative_check($answers_x, $answers_y, $question_x['answersid'][($ii-1)], $question_y['answersid'][($ij)], $x, 0);
3518
                                    $tableHtml .= $votes;
3519
                                    array_push(
3520
                                        $chartData,
3521
                                        array(
3522
                                            'serie' => array($currentYQuestion, $xOptions[$ii-1]),
3523
                                            'option' => $x,
3524
                                            'votes' => $votes
3525
                                        )
3526
                                    );
3527
                                    $tableHtml .=  '</td>';
3528
                                }
3529
                            }
3530
                        } else {
3531
                            if ($ii == 0) {
3532
                                $tableHtml .=  '		<th>'.$question_y['answers'][($ij)].'</th>';
3533
                            } else {
3534
                                $tableHtml .=  '		<td align="center">';
3535
                                $votes = SurveyUtil::comparative_check($answers_x, $answers_y, $question_x['answersid'][($ii-1)], $question_y['answersid'][($ij)]);
3536
                                $tableHtml .= $votes;
3537
                                array_push(
3538
                                    $chartData,
3539
                                    array(
3540
                                        'serie' => $xOptions[$ii-1],
3541
                                        'option' => $currentYQuestion,
3542
                                        'votes' => $votes
3543
                                    )
3544
                                );
3545
                                $tableHtml .=  '</td>';
3546
                            }
3547
                        }
3548
                    }
3549
                    $tableHtml .=  '	</tr>';
3550
                }
3551
            }
3552
            $tableHtml .=  '</table>';
3553
            echo '<div id="chartContainer" class="col-md-12">';
3554
            echo self::drawChart($chartData, true);
3555
            echo '</div>';
3556
            echo $tableHtml;
3557
        }
3558
    }
3559
3560
    /**
3561
     * Get all the answers of a question grouped by user
3562
     *
3563
     * @param	integer	Survey ID
3564
     * @param	integer	Question ID
3565
     * @return 	Array	Array containing all answers of all users, grouped by user
3566
     *
3567
     * @author Patrick Cool <[email protected]>, Ghent University
3568
     * @version February 2007 - Updated March 2008
3569
     */
3570
    public static function get_answers_of_question_by_user($survey_id, $question_id)
3571
    {
3572
        $course_id = api_get_course_int_id();
3573
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
3574
3575
        $sql = "SELECT * FROM $table_survey_answer
3576
                WHERE c_id = $course_id AND survey_id='".intval($survey_id)."'
3577
                AND question_id='".intval($question_id)."'
3578
                ORDER BY USER ASC";
3579
        $result = Database::query($sql);
3580
        while ($row = Database::fetch_array($result)) {
3581
            if ($row['value'] == 0) {
3582
                $return[$row['user']][] = $row['option_id'];
3583
            } else {
3584
                $return[$row['user']][] = $row['option_id'].'*'.$row['value'];
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
        while ($row = Database::fetch_array($res)) {
3662
            $survey_invitation_data[] = $row;
3663
        }
3664
3665
        return $survey_invitation_data;
3666
    }
3667
3668
    /**
3669
     * Get the total number of survey invitations for a given survey (through $_GET['survey_id'])
3670
     *
3671
     * @return	integer	Total number of survey invitations
3672
     *
3673
     * @todo use survey_id parameter instead of $_GET
3674
     *
3675
     * @author Patrick Cool <[email protected]>, Ghent University
3676
     * @version January 2007
3677
     */
3678 View Code Duplication
    public static function get_number_of_survey_invitations()
3679
    {
3680
        $course_id = api_get_course_int_id();
3681
3682
        // Database table definition
3683
        $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
3684
3685
        $sql = "SELECT count(user) AS total
3686
		        FROM $table_survey_invitation
3687
		        WHERE
3688
                    c_id = $course_id AND
3689
                    survey_id='".intval($_GET['survey_id'])."' AND
3690
                    session_id='".api_get_session_id()."' ";
3691
        $res = Database::query($sql);
3692
        $row = Database::fetch_array($res,'ASSOC');
3693
3694
        return $row['total'];
3695
    }
3696
3697
    /**
3698
     * Save the invitation mail
3699
     *
3700
     * @param string 	Text of the e-mail
3701
     * @param integer	Whether the mail contents are for invite mail (0, default) or reminder mail (1)
3702
     *
3703
     * @author Patrick Cool <[email protected]>, Ghent University
3704
     * @version January 2007
3705
     */
3706
    static function save_invite_mail($mailtext, $mail_subject, $reminder = 0)
3707
    {
3708
        $course_id = api_get_course_int_id();
3709
        // Database table definition
3710
        $table_survey = Database :: get_course_table(TABLE_SURVEY);
3711
3712
        // Reminder or not
3713
        if ($reminder == 0) {
3714
            $mail_field = 'invite_mail';
3715
        } else {
3716
            $mail_field = 'reminder_mail';
3717
        }
3718
3719
        $sql = "UPDATE $table_survey
3720
		        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
    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
    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
    static function display_survey_search_form()
4136
    {
4137
        echo '<form class="form-horizontal" method="get" action="'.api_get_path(WEB_CODE_PATH).'survey/survey_list.php?search=advanced">';
4138
        echo '<legend>'.get_lang('SearchASurvey').'</legend>';
4139
        echo '	<div class="control-group">
4140
					<label class="control-label">
4141
						'.get_lang('Title').'
4142
					</label>
4143
					<div class="controls">
4144
						<input type="text" id="search_title" name="keyword_title"/>
4145
					</div>
4146
				</div>';
4147
        echo '	<div class="control-group">
4148
					<label class="control-label">
4149
						'.get_lang('Code').'
4150
					</label>
4151
					<div class="controls">
4152
						<input type="text" name="keyword_code"/>
4153
					</div>
4154
				</div>';
4155
        echo '	<div class="control-group">
4156
					<label class="control-label">
4157
						'.get_lang('Language').'
4158
					</label>
4159
					<div class="controls">';
4160
        echo '			<select name="keyword_language"><option value="%">'.get_lang('All').'</option>';
4161
        $languages = api_get_languages();
4162
        foreach ($languages['name'] as $index => & $name) {
4163
            echo '<option value="'.$languages['folder'][$index].'">'.$name.'</option>';
4164
        }
4165
        echo '			</select>';
4166
        echo '		</div>
4167
				</div>';
4168
        echo '<input type="hidden" name="cidReq" value="'.api_get_course_id().'"/>';
4169
        echo '	<div class="control-group">
4170
					<div class="controls">
4171
						<button class="search" type="submit" name="do_search">'.get_lang('Search').'</button>
4172
					</div>
4173
				</div>';
4174
        echo '</form>';
4175
        echo '<div style="clear: both;margin-bottom: 10px;"></div>';
4176
    }
4177
4178
    /**
4179
     * Show table only visible by DRH users
4180
     */
4181
    public static function displaySurveyListForDrh()
4182
    {
4183
        $parameters = array();
4184
        $parameters['cidReq'] = api_get_course_id();
4185
4186
        // Create a sortable table with survey-data
4187
        $table = new SortableTable('surveys', 'get_number_of_surveys', 'get_survey_data_drh', 2);
4188
        $table->set_additional_parameters($parameters);
4189
        $table->set_header(0, '', false);
4190
        $table->set_header(1, get_lang('SurveyName'));
4191
        $table->set_header(2, get_lang('SurveyCode'));
4192
        $table->set_header(3, get_lang('NumberOfQuestions'));
4193
        $table->set_header(4, get_lang('Author'));
4194
        $table->set_header(5, get_lang('AvailableFrom'));
4195
        $table->set_header(6, get_lang('AvailableUntil'));
4196
        $table->set_header(7, get_lang('Invite'));
4197
        $table->set_header(8, get_lang('Anonymous'));
4198
4199 View Code Duplication
        if (api_get_configuration_value('allow_mandatory_survey')) {
4200
            $table->set_header(9, get_lang('IsMandatory'));
4201
            $table->set_header(10, get_lang('Modify'), false, 'width="150"');
4202
            $table->set_column_filter(9, 'anonymous_filter');
4203
            $table->set_column_filter(10, 'modify_filter_drh');
4204
        } else {
4205
            $table->set_header(9, get_lang('Modify'), false, 'width="150"');
4206
            $table->set_column_filter(9, 'modify_filter_drh');
4207
        }
4208
4209
        $table->set_column_filter(8, 'anonymous_filter');
4210
        $table->display();
4211
    }
4212
4213
    /**
4214
     * This function displays the sortable table with all the surveys
4215
     *
4216
     * @return	void	(direct output)
4217
     *
4218
     * @author Patrick Cool <[email protected]>, Ghent University
4219
     * @version January 2007
4220
     */
4221
    static function display_survey_list()
4222
    {
4223
        $parameters = array();
4224
        $parameters['cidReq'] = api_get_course_id();
4225
        if (isset($_GET['do_search']) && $_GET['do_search']) {
4226
            $message = get_lang('DisplaySearchResults').'<br />';
4227
            $message .= '<a href="'.api_get_self().'?'.api_get_cidreq().'">'.get_lang('DisplayAll').'</a>';
4228
            Display::display_normal_message($message, false);
4229
        }
4230
4231
        // Create a sortable table with survey-data
4232
        $table = new SortableTable('surveys', 'get_number_of_surveys', 'get_survey_data', 2);
4233
        $table->set_additional_parameters($parameters);
4234
        $table->set_header(0, '', false);
4235
        $table->set_header(1, get_lang('SurveyName'));
4236
        $table->set_header(2, get_lang('SurveyCode'));
4237
        $table->set_header(3, get_lang('NumberOfQuestions'));
4238
        $table->set_header(4, get_lang('Author'));
4239
        //$table->set_header(5, get_lang('Language'));
4240
        //$table->set_header(6, get_lang('Shared'));
4241
        $table->set_header(5, get_lang('AvailableFrom'));
4242
        $table->set_header(6, get_lang('AvailableUntil'));
4243
        $table->set_header(7, get_lang('Invite'));
4244
        $table->set_header(8, get_lang('Anonymous'));
4245
4246 View Code Duplication
        if (api_get_configuration_value('allow_mandatory_survey')) {
4247
            $table->set_header(9, get_lang('IsMandatory'));
4248
            $table->set_header(10, get_lang('Modify'), false, 'width="150"');
4249
            $table->set_column_filter(9, 'anonymous_filter');
4250
            $table->set_column_filter(10, 'modify_filter');
4251
        } else {
4252
            $table->set_header(9, get_lang('Modify'), false, 'width="150"');
4253
            $table->set_column_filter(9, 'modify_filter');
4254
        }
4255
4256
        $table->set_column_filter(8, 'anonymous_filter');
4257
        $table->set_form_actions(array('delete' => get_lang('DeleteSurvey')));
4258
        $table->display();
4259
    }
4260
4261
    function display_survey_list_for_coach()
4262
    {
4263
        $parameters = array();
4264
        $parameters['cidReq']=api_get_course_id();
4265
        if (isset($_GET['do_search'])) {
4266
            $message = get_lang('DisplaySearchResults').'<br />';
4267
            $message .= '<a href="'.api_get_self().'?'.api_get_cidreq().'">'.get_lang('DisplayAll').'</a>';
4268
            Display::display_normal_message($message, false);
4269
        }
4270
4271
        // Create a sortable table with survey-data
4272
        $table = new SortableTable('surveys_coach', 'get_number_of_surveys_for_coach', 'get_survey_data_for_coach', 2);
4273
        $table->set_additional_parameters($parameters);
4274
        $table->set_header(0, '', false);
4275
        $table->set_header(1, get_lang('SurveyName'));
4276
        $table->set_header(2, get_lang('SurveyCode'));
4277
        $table->set_header(3, get_lang('NumberOfQuestions'));
4278
        $table->set_header(4, get_lang('Author'));
4279
        //$table->set_header(5, get_lang('Language'));
4280
        //$table->set_header(6, get_lang('Shared'));
4281
        $table->set_header(5, get_lang('AvailableFrom'));
4282
        $table->set_header(6, get_lang('AvailableUntil'));
4283
        $table->set_header(7, get_lang('Invite'));
4284
        $table->set_header(8, get_lang('Anonymous'));
4285
4286 View Code Duplication
        if (api_get_configuration_value('allow_mandatory_survey')) {
4287
            $table->set_header(9, get_lang('Modify'), false, 'width="130"');
4288
            $table->set_header(10, get_lang('Modify'), false, 'width="130"');
4289
            $table->set_column_filter(9, 'anonymous_filter');
4290
            $table->set_column_filter(10, 'modify_filter_for_coach');
4291
        } else {
4292
            $table->set_header(9, get_lang('Modify'), false, 'width="130"');
4293
            $table->set_column_filter(9, 'modify_filter_for_coach');
4294
        }
4295
4296
        $table->set_column_filter(8, 'anonymous_filter');
4297
        $table->display();
4298
    }
4299
4300
    /**
4301
     * This function changes the modify column of the sortable table
4302
     *
4303
     * @param integer $survey_id the id of the survey
4304
     * @param bool $drh
4305
     * @return string html code that are the actions that can be performed on any survey
4306
     *
4307
     * @author Patrick Cool <[email protected]>, Ghent University
4308
     * @version January 2007
4309
     */
4310
    static function modify_filter($survey_id, $drh = false)
4311
    {
4312
        $survey_id = Security::remove_XSS($survey_id);
4313
        $return = '';
4314
4315
        if ($drh) {
4316
            return '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.
4317
            Display::return_icon('stats.png', get_lang('Reporting'),'',ICON_SIZE_SMALL).'</a>';
4318
        }
4319
4320
        // Coach can see that only if the survey is in his session
4321
        if (api_is_allowed_to_edit() ||
4322
            api_is_element_in_the_session(TOOL_SURVEY, $survey_id)
4323
        ) {
4324
            $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>';
4325
            if (SurveyManager::survey_generation_hash_available()) {
4326
                $return .=  Display::url(
4327
                    Display::return_icon('new_link.png', get_lang('GenerateSurveyAccessLink'),'',ICON_SIZE_SMALL),
4328
                    api_get_path(WEB_CODE_PATH).'survey/generate_link.php?survey_id='.$survey_id.'&'.api_get_cidreq()
4329
                );
4330
            }
4331
            $return .= Display::url(
4332
                Display::return_icon('copy.png', get_lang('DuplicateSurvey'), '', ICON_SIZE_SMALL),
4333
                'survey_list.php?action=copy_survey&survey_id='.$survey_id.'&'.api_get_cidreq()
4334
            );
4335
4336
            $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;">'.
4337
                Display::return_icon('clean.png', get_lang('EmptySurvey'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
4338
        }
4339
        $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/preview.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.
4340
            Display::return_icon('preview_view.png', get_lang('Preview'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
4341
        $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_invite.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.
4342
            Display::return_icon('mail_send.png', get_lang('Publish'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
4343
        $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.
4344
            Display::return_icon('stats.png', get_lang('Reporting'),'',ICON_SIZE_SMALL).'</a>';
4345
4346 View Code Duplication
        if (api_is_allowed_to_edit() ||
4347
            api_is_element_in_the_session(TOOL_SURVEY, $survey_id)
4348
        ) {
4349
            $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;">'.
4350
                Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
4351
        }
4352
4353
        return $return;
4354
    }
4355
4356
    static function modify_filter_for_coach($survey_id)
4357
    {
4358
        $survey_id = Security::remove_XSS($survey_id);
4359
        //$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>';
4360
        //$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>';
4361
        //$return .= '<a href="create_survey_in_another_language.php?id_survey='.$survey_id.'">'.Display::return_icon('copy.gif', get_lang('Copy')).'</a>';
4362
        //$return .= '<a href="survey.php?survey_id='.$survey_id.'">'.Display::return_icon('add.gif', get_lang('Add')).'</a>';
4363
        $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;';
4364
        $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;';
4365
        $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;';
4366
        //$return .= '<a href="reporting.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.Display::return_icon('statistics.gif', get_lang('Reporting')).'</a>';
4367
        return $return;
4368
    }
4369
4370
    /**
4371
     * Returns "yes" when given parameter is one, "no" for any other value
4372
     * @param	integer	Whether anonymous or not
4373
     * @return	string	"Yes" or "No" in the current language
4374
     */
4375
    static function anonymous_filter($anonymous)
4376
    {
4377
        if ($anonymous == 1) {
4378
            return get_lang('Yes');
4379
        } else {
4380
            return get_lang('No');
4381
        }
4382
    }
4383
4384
    /**
4385
     * This function handles the search restriction for the SQL statements
4386
     *
4387
     * @return	string	Part of a SQL statement or false on error
4388
     *
4389
     * @author Patrick Cool <[email protected]>, Ghent University
4390
     * @version January 2007
4391
     */
4392
    static function survey_search_restriction()
4393
    {
4394
        if (isset($_GET['do_search'])) {
4395
            if ($_GET['keyword_title'] != '') {
4396
                $search_term[] = 'title like "%" \''.Database::escape_string($_GET['keyword_title']).'\' "%"';
4397
            }
4398
            if ($_GET['keyword_code'] != '') {
4399
                $search_term[] = 'code =\''.Database::escape_string($_GET['keyword_code']).'\'';
4400
            }
4401
            if ($_GET['keyword_language'] != '%') {
4402
                $search_term[] = 'lang =\''.Database::escape_string($_GET['keyword_language']).'\'';
4403
            }
4404
            $my_search_term = ($search_term == null) ? array() : $search_term;
4405
            $search_restriction = implode(' AND ', $my_search_term);
4406
            return $search_restriction;
4407
        } else {
4408
            return false;
4409
        }
4410
    }
4411
4412
    /**
4413
     * This function calculates the total number of surveys
4414
     *
4415
     * @return	integer	Total number of surveys
4416
     *
4417
     * @author Patrick Cool <[email protected]>, Ghent University
4418
     * @version January 2007
4419
     */
4420
    static function get_number_of_surveys()
4421
    {
4422
        $table_survey = Database :: get_course_table(TABLE_SURVEY);
4423
        $course_id = api_get_course_int_id();
4424
4425
        $search_restriction = SurveyUtil::survey_search_restriction();
4426
        if ($search_restriction) {
4427
            $search_restriction = 'WHERE c_id = '.$course_id.' AND '.$search_restriction;
4428
        } else {
4429
            $search_restriction = "WHERE c_id = $course_id";
4430
        }
4431
        $sql = "SELECT count(survey_id) AS total_number_of_items
4432
		        FROM ".$table_survey.' '.$search_restriction;
4433
        $res = Database::query($sql);
4434
        $obj = Database::fetch_object($res);
4435
        return $obj->total_number_of_items;
4436
    }
4437
4438
    static function get_number_of_surveys_for_coach()
4439
    {
4440
        $survey_tree = new SurveyTree();
4441
        return count($survey_tree->get_last_children_from_branch($survey_tree->surveylist));
4442
    }
4443
4444
    /**
4445
     * This function gets all the survey data that is to be displayed in the sortable table
4446
     *
4447
     * @param int $from
4448
     * @param int $number_of_items
4449
     * @param int $column
4450
     * @param string $direction
4451
     * @param bool $isDrh
4452
     * @return unknown
4453
     *
4454
     * @author Patrick Cool <[email protected]>, Ghent University
4455
     * @author Julio Montoya <[email protected]>, Beeznest - Adding intvals
4456
     * @version January 2007
4457
     */
4458
    static function get_survey_data($from, $number_of_items, $column, $direction, $isDrh = false)
4459
    {
4460
        $table_survey = Database :: get_course_table(TABLE_SURVEY);
4461
        $table_user = Database :: get_main_table(TABLE_MAIN_USER);
4462
        $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
4463
        $mandatoryAllowed = api_get_configuration_value('allow_mandatory_survey');
4464
        $_user = api_get_user_info();
4465
4466
        // Searching
4467
        $search_restriction = SurveyUtil::survey_search_restriction();
4468
        if ($search_restriction) {
4469
            $search_restriction = ' AND '.$search_restriction;
4470
        }
4471
        $from = intval($from);
4472
        $number_of_items = intval($number_of_items);
4473
        $column = intval($column);
4474
        if (!in_array(strtolower($direction), array('asc', 'desc'))) {
4475
            $direction = 'asc';
4476
        }
4477
4478
        // Condition for the session
4479
        $session_id = api_get_session_id();
4480
        $condition_session = api_get_session_condition($session_id);
4481
        $course_id = api_get_course_int_id();
4482
4483
        $sql = "SELECT
4484
					survey.survey_id AS col0,
4485
					survey.title AS col1,
4486
					survey.code AS col2,
4487
					count(survey_question.question_id) AS col3,
4488
					".(api_is_western_name_order() ? "CONCAT(user.firstname, ' ', user.lastname)" : "CONCAT(user.lastname, ' ', user.firstname)")."	AS col4,
4489
					survey.avail_from AS col5,
4490
					survey.avail_till AS col6,
4491
					survey.invited AS col7,
4492
					survey.anonymous AS col8,
4493
					survey.survey_id AS col9,
4494
					survey.session_id AS session_id,
4495
					survey.answered,
4496
					survey.invited
4497
				 FROM $table_survey survey
4498
                    LEFT JOIN $table_survey_question survey_question
4499
                    ON (survey.survey_id = survey_question.survey_id AND survey_question.c_id = $course_id)
4500
                    LEFT JOIN $table_user user
4501
                    ON (survey.author = user.user_id)
4502
				 WHERE survey.c_id = $course_id
4503
				 $search_restriction
4504
				 $condition_session ";
4505
        $sql .= " GROUP BY survey.survey_id";
4506
        $sql .= " ORDER BY col$column $direction ";
4507
        $sql .= " LIMIT $from,$number_of_items";
4508
4509
        $res = Database::query($sql);
4510
        $surveys = array();
4511
        $array = array();
4512
        $efv = new ExtraFieldValue('survey');
4513
4514
        while ($survey = Database::fetch_array($res)) {
4515
            $array[0] = $survey[0];
4516
            $array[1] = Display::url(
4517
                $survey[1],
4518
                api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.$survey[0].'&'.api_get_cidreq()
4519
            );
4520
4521
            // Validation when belonging to a session
4522
            $session_img = api_get_session_image($survey['session_id'], $_user['status']);
4523
            $array[2] = $survey[2] . $session_img;
4524
            $array[3] = $survey[3];
4525
            $array[4] = $survey[4];
4526
            $array[5] = $survey[5];
4527
            $array[6] = $survey[6];
4528
            $array[7] =
4529
                Display::url(
4530
                    $survey['answered'],
4531
                    api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?view=answered&survey_id='.$survey[0].'&'.api_get_cidreq()
4532
                ).' / '.
4533
                Display::url(
4534
                    $survey['invited'],
4535
                    api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?view=invited&survey_id='.$survey[0].'&'.api_get_cidreq()
4536
                );
4537
4538
            $array[8] = $survey[8];
4539
4540
            if ($mandatoryAllowed) {
4541
                $efvMandatory = $efv->get_values_by_handler_and_field_variable($survey[9], 'is_mandatory');
4542
4543
                $array[9] = $efvMandatory ? $efvMandatory['value'] : 0;
4544
                $array[10] = $survey[9];
4545
            } else {
4546
                $array[9] = $survey[9];
4547
            }
4548
4549
            if ($isDrh) {
4550
                $array[1] = $survey[1];
4551
                $array[7] = strip_tags($array[7]);
4552
            }
4553
4554
            $surveys[] = $array;
4555
        }
4556
        return $surveys;
4557
    }
4558
4559
    static function get_survey_data_for_coach($from, $number_of_items, $column, $direction)
4560
    {
4561
        $mandatoryAllowed = api_get_configuration_value('allow_mandatory_survey');
4562
        $survey_tree = new SurveyTree();
4563
        $last_version_surveys = $survey_tree->get_last_children_from_branch($survey_tree->surveylist);
4564
        $list = array();
4565
        foreach ($last_version_surveys as & $survey) {
4566
            $list[]=$survey['id'];
4567
        }
4568
        if (count($list) > 0) {
4569
            $list_condition = " AND survey.survey_id IN (".implode(',',$list).") ";
4570
        } else {
4571
            $list_condition = '';
4572
        }
4573
4574
        $from = intval($from);
4575
        $number_of_items = intval($number_of_items);
4576
        $column = intval($column);
4577
        if (!in_array(strtolower($direction), array('asc', 'desc'))) {
4578
            $direction = 'asc';
4579
        }
4580
4581
        $table_survey 			= Database :: get_course_table(TABLE_SURVEY);
4582
        $table_survey_question 	= Database :: get_course_table(TABLE_SURVEY_QUESTION);
4583
        $table_user 			= Database :: get_main_table(TABLE_MAIN_USER);
4584
4585
        $course_id = api_get_course_int_id();
4586
        $efv = new ExtraFieldValue('survey');
4587
4588
        //IF(is_shared<>0,'V','-')	 					AS col6,
4589
        $sql = "SELECT ".
4590
            "survey.survey_id							AS col0, ".
4591
            "survey.title	                            AS col1, ".
4592
            "survey.code									AS col2, ".
4593
            "count(survey_question.question_id)			AS col3, ".
4594
            (api_is_western_name_order() ? "CONCAT(user.firstname, ' ', user.lastname)" : "CONCAT(user.lastname, ' ', user.firstname)")."	AS col4, ".
4595
            "survey.avail_from							AS col5, ".
4596
            "survey.avail_till							AS col6, ".
4597
            "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, ".
4598
            "survey.anonymous							AS col8, ".
4599
            "survey.survey_id							AS col9  ".
4600
            "FROM $table_survey survey ".
4601
            "LEFT JOIN $table_survey_question survey_question
4602
             ON (survey.survey_id = survey_question.survey_id AND survey.c_id = survey_question.c_id) ".
4603
            ", $table_user user
4604
               WHERE survey.author = user.user_id AND survey.c_id = $course_id $list_condition ";
4605
        $sql .= " GROUP BY survey.survey_id";
4606
        $sql .= " ORDER BY col$column $direction ";
4607
        $sql .= " LIMIT $from,$number_of_items";
4608
4609
        $res = Database::query($sql);
4610
        $surveys = array();
4611
        while ($survey = Database::fetch_array($res)) {
4612
            if ($mandatoryAllowed) {
4613
                $survey['col10'] = $survey['col9'];
4614
                $efvMandatory = $efv->get_values_by_handler_and_field_variable($survey['col9'], 'is_mandatory');
4615
                $survey['col9'] = $efvMandatory['value'];
4616
            }
4617
            $surveys[] = $survey;
4618
        }
4619
        return $surveys;
4620
    }
4621
4622
    /**
4623
     * Display all the active surveys for the given course user
4624
     *
4625
     * @param int $user_id
4626
     *
4627
     * @author Patrick Cool <[email protected]>, Ghent University
4628
     * @version April 2007
4629
     */
4630
    public static function getSurveyList($user_id)
4631
    {
4632
        $_course = api_get_course_info();
4633
        $course_id = $_course['real_id'];
4634
        $user_id = intval($user_id);
4635
        $sessionId = api_get_session_id();
4636
        $mandatoryAllowed = api_get_configuration_value('allow_mandatory_survey');
4637
4638
        // Database table definitions
4639
        $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
4640
        $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
4641
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
4642
        $table_survey = Database:: get_course_table(TABLE_SURVEY);
4643
4644
        $sql = 'SELECT question_id
4645
                FROM '.$table_survey_question."
4646
                WHERE c_id = $course_id";
4647
        $result = Database::query($sql);
4648
4649
        $all_question_id = array();
4650
        while ($row = Database::fetch_array($result, 'ASSOC')) {
4651
            $all_question_id[] = $row;
4652
        }
4653
4654
        $count = 0;
4655
        for ($i = 0; $i < count($all_question_id); $i++) {
4656
            $sql = 'SELECT COUNT(*) as count
4657
			        FROM '.$table_survey_answer.'
4658
					WHERE
4659
					    c_id = '.$course_id.' AND
4660
					    question_id='.intval($all_question_id[$i]['question_id']).' AND
4661
					    user = '.$user_id;
4662
            $result = Database::query($sql);
4663
            while ($row = Database::fetch_array($result, 'ASSOC')) {
4664
                if ($row['count'] == 0) {
4665
                    $count++;
4666
                    break;
4667
                }
4668
            }
4669
            if ($count > 0) {
4670
                $link_add = true;
4671
                break;
4672
            }
4673
        }
4674
4675
        echo '<table id="list-survey" class="table ">';
4676
        echo '<tr>';
4677
        echo '	<th>'.get_lang('SurveyName').'</th>';
4678
        echo '	<th>'.get_lang('Anonymous').'</th>';
4679
        if ($mandatoryAllowed) {
4680
            echo '<th class="text-center">'.get_lang('IsMandatory').'</th>';
4681
        }
4682
        echo '</tr>';
4683
4684
        $sql = "SELECT *
4685
                FROM $table_survey survey,
4686
                $table_survey_invitation survey_invitation
4687
				WHERE
4688
                    survey_invitation.user = $user_id AND
4689
                    survey.code = survey_invitation.survey_code AND
4690
                    survey.avail_from <= '".date('Y-m-d H:i:s')."' AND
4691
                    survey.avail_till >= '".date('Y-m-d H:i:s')."' AND
4692
                    survey.c_id = $course_id AND
4693
                    survey.session_id = $sessionId AND
4694
                    survey_invitation.c_id = $course_id
4695
				";
4696
        $result = Database::query($sql);
4697
        $counter = 0;
4698
4699
        $efv = new ExtraFieldValue('survey');
4700
4701
        while ($row = Database::fetch_array($result, 'ASSOC')) {
4702
4703
            // Get the user into survey answer table (user or anonymus)
4704
            $sql = "SELECT user FROM $table_survey_answer
4705
					WHERE c_id = $course_id AND survey_id = (
4706
					    SELECT survey_id from $table_survey
4707
					    WHERE code ='".Database::escape_string($row['code'])." AND c_id = $course_id'
4708
                    )
4709
            ";
4710
            $result_answer = Database::query($sql);
4711
            $row_answer = Database::fetch_array($result_answer,'ASSOC');
4712
            echo '<tr>';
4713
            if ($row['answered'] == 0) {
4714
                echo '<td>';
4715
                echo Display::return_icon('statistics.png', get_lang('CreateNewSurvey'),array('style'=>'inline-block'),ICON_SIZE_TINY);
4716
                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>';
4717
            } else {
4718
                //echo '<td>'.$row['title'].'</td>';
4719
                echo '<td>';
4720
                echo Display::return_icon('statistics_na.png', get_lang('CreateNewSurvey'),array('style'=>'inline-block'),ICON_SIZE_TINY);
4721
                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>';
4722
            }
4723
            echo '<td class="center">';
4724
            echo ($row['anonymous'] == 1) ? get_lang('Yes') : get_lang('No');
4725
            echo '</td>';
4726
            if ($mandatoryAllowed) {
4727
                $efvMandatory = $efv->get_values_by_handler_and_field_variable($row['survey_id'], 'is_mandatory');
4728
                echo '<td class="text-center">'.($efvMandatory['value'] ? get_lang('Yes') : get_lang('No')).'</td>';
4729
            }
4730
            echo '</tr>';
4731
            if ($row['anonymous'] == 1) {
4732
                $current_user_id = $_SESSION['surveyuser'];
4733
            } else {
4734
                $current_user_id = api_get_user_id();
4735
            }
4736
            $link_available = self::show_link_available(api_get_user_id(),$row['code'],$current_user_id);
4737
            //todo check this link
4738
            if ($link_add === true && $link_available === true) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

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

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

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

could be turned into

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

This is much more concise to read.

Loading history...
4739
                //echo '<tr><td><a href="fillsurvey.php?user_id='.api_get_user_id().'&course='.$_course['sysCode'].'&invitationcode='.$row['invitation_code'].'&cidReq='.$_course['sysCode'].'">'.get_lang('CompleteTheSurveysQuestions').'</a></td><td></td></tr>';
4740
            }
4741
        }
4742
        echo '</table>';
4743
    }
4744
4745
    /**
4746
     * Creates a multi array with the user fields that we can show. We look the visibility with the api_get_setting function
4747
     * The username is always NOT able to change it.
4748
     * @author Julio Montoya Armas <[email protected]>, Chamilo: Personality Test modification
4749
     * @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...
4750
     * 		   array[value_name][visibilty]
4751
     */
4752
    static function make_field_list()
4753
    {
4754
        //	LAST NAME and FIRST NAME
4755
        $field_list_array = array();
4756
        $field_list_array['lastname']['name'] = get_lang('LastName');
4757
        $field_list_array['firstname']['name'] = get_lang('FirstName');
4758
4759
        if (api_get_setting('profile', 'name') != 'true') {
4760
            $field_list_array['firstname']['visibility'] = 0;
4761
            $field_list_array['lastname']['visibility'] = 0;
4762
        } else {
4763
            $field_list_array['firstname']['visibility'] = 1;
4764
            $field_list_array['lastname']['visibility'] = 1;
4765
        }
4766
4767
        $field_list_array['username']['name'] = get_lang('Username');
4768
        $field_list_array['username']['visibility'] = 0;
4769
4770
        //	OFFICIAL CODE
4771
        $field_list_array['official_code']['name'] = get_lang('OfficialCode');
4772
4773 View Code Duplication
        if (api_get_setting('profile', 'officialcode') != 'true') {
4774
            $field_list_array['official_code']['visibility'] = 1;
4775
        } else {
4776
            $field_list_array['official_code']['visibility'] = 0;
4777
        }
4778
4779
        // EMAIL
4780
        $field_list_array['email']['name'] = get_lang('Email');
4781 View Code Duplication
        if (api_get_setting('profile', 'email') != 'true') {
4782
            $field_list_array['email']['visibility'] = 1;
4783
        } else {
4784
            $field_list_array['email']['visibility'] = 0;
4785
        }
4786
4787
        // PHONE
4788
        $field_list_array['phone']['name'] = get_lang('Phone');
4789 View Code Duplication
        if (api_get_setting('profile', 'phone') != 'true') {
4790
            $field_list_array['phone']['visibility'] = 0;
4791
        } else {
4792
            $field_list_array['phone']['visibility'] = 1;
4793
        }
4794
        //	LANGUAGE
4795
        $field_list_array['language']['name'] = get_lang('Language');
4796 View Code Duplication
        if (api_get_setting('profile', 'language') != 'true') {
4797
            $field_list_array['language']['visibility'] = 0;
4798
        } else {
4799
            $field_list_array['language']['visibility'] = 1;
4800
        }
4801
4802
        // EXTRA FIELDS
4803
        $extra = UserManager::get_extra_fields(0, 50, 5, 'ASC');
4804
4805
        foreach ($extra as $id => $field_details) {
4806
            if ($field_details[6] == 0) {
4807
                continue;
4808
            }
4809
            switch ($field_details[2]) {
4810 View Code Duplication
                case UserManager::USER_FIELD_TYPE_TEXT:
4811
                    $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4812
                    if ($field_details[7] == 0) {
4813
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4814
                    } else {
4815
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
4816
                    }
4817
                    break;
4818 View Code Duplication
                case UserManager::USER_FIELD_TYPE_TEXTAREA:
4819
                    $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4820
                    if ($field_details[7] == 0) {
4821
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4822
                    } else {
4823
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
4824
                    }
4825
                    break;
4826 View Code Duplication
                case UserManager::USER_FIELD_TYPE_RADIO:
4827
                    $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4828
                    if ($field_details[7] == 0) {
4829
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4830
                    } else {
4831
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
4832
                    }
4833
                    break;
4834
                case UserManager::USER_FIELD_TYPE_SELECT:
4835
                    $get_lang_variables = false;
4836 View Code Duplication
                    if (in_array($field_details[1], array('mail_notify_message', 'mail_notify_invitation', 'mail_notify_group_message'))) {
4837
                        $get_lang_variables = true;
4838
                    }
4839
4840
                    if ($get_lang_variables) {
4841
                        $field_list_array['extra_'.$field_details[1]]['name'] = get_lang($field_details[3]);
4842
                    } else {
4843
                        $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4844
                    }
4845
4846
                    if ($field_details[7] == 0) {
4847
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4848
                    } else {
4849
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
4850
                    }
4851
                    break;
4852 View Code Duplication
                case UserManager::USER_FIELD_TYPE_SELECT_MULTIPLE:
4853
                    $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4854
                    if ($field_details[7] == 0) {
4855
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4856
                    } else {
4857
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
4858
                    }
4859
                    break;
4860 View Code Duplication
                case UserManager::USER_FIELD_TYPE_DATE:
4861
                    $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4862
                    if ($field_details[7] == 0) {
4863
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4864
                    } else {
4865
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
4866
                    }
4867
                    break;
4868 View Code Duplication
                case UserManager::USER_FIELD_TYPE_DATETIME:
4869
                    $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4870
                    if ($field_details[7] == 0) {
4871
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4872
                    } else {
4873
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
4874
                    }
4875
                    break;
4876 View Code Duplication
                case UserManager::USER_FIELD_TYPE_DOUBLE_SELECT:
4877
                    $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4878
                    if ($field_details[7] == 0) {
4879
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4880
                    } else {
4881
                        $field_list_array['extra_'.$field_details[1]]['visibility']=1;
4882
                    }
4883
                    break;
4884
                case UserManager::USER_FIELD_TYPE_DIVIDER:
4885
                    //$form->addElement('static',$field_details[1], '<br /><strong>'.$field_details[3].'</strong>');
4886
                    break;
4887
            }
4888
        }
4889
        return $field_list_array;
4890
    }
4891
4892
    /**
4893
     * @author Isaac Flores Paz <[email protected]>
4894
     * @param int $user_id - User ID
4895
     * @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...
4896
     * @return boolean
4897
     */
4898
    static function show_link_available($user_id, $survey_code, $user_answer)
4899
    {
4900
        $table_survey             = Database :: get_course_table(TABLE_SURVEY);
4901
        $table_survey_invitation  = Database :: get_course_table(TABLE_SURVEY_INVITATION);
4902
        $table_survey_answer      = Database :: get_course_table(TABLE_SURVEY_ANSWER);
4903
        $table_survey_question    = Database :: get_course_table(TABLE_SURVEY_QUESTION);
4904
4905
        $survey_code = Database::escape_string($survey_code);
4906
        $user_id = intval($user_id);
4907
        $user_answer = Database::escape_string($user_answer);
4908
4909
        $course_id = api_get_course_int_id();
4910
4911
        $sql = 'SELECT COUNT(*) as count
4912
                FROM '.$table_survey_invitation.'
4913
		        WHERE user='.$user_id.' AND survey_code="'.$survey_code.'" AND answered="1" AND c_id = '.$course_id.' ';
4914
4915
        $sql2 = 'SELECT COUNT(*) as count FROM '.$table_survey.' s INNER JOIN '.$table_survey_question.' q ON s.survey_id=q.survey_id
4916
				 WHERE s.code="'.$survey_code.'" AND q.type NOT IN("pagebreak","comment") AND s.c_id = '.$course_id.' AND q.c_id = '.$course_id.' ';
4917
4918
        $sql3 = 'SELECT COUNT(DISTINCT question_id) as count FROM '.$table_survey_answer.'
4919
				 WHERE survey_id=(SELECT survey_id FROM '.$table_survey.'
4920
				 WHERE code="'.$survey_code.'" AND c_id = '.$course_id.' ) AND user="'.$user_answer.'" AND c_id = '.$course_id.' ';
4921
4922
        $result  = Database::query($sql);
4923
        $result2 = Database::query($sql2);
4924
        $result3 = Database::query($sql3);
4925
4926
        $row  = Database::fetch_array($result, 'ASSOC');
4927
        $row2 = Database::fetch_array($result2, 'ASSOC');
4928
        $row3 = Database::fetch_array($result3, 'ASSOC');
4929
4930
        if ($row['count'] == 1 && $row3['count'] != $row2['count']) {
4931
            return true;
4932
        } else {
4933
            return false;
4934
        }
4935
    }
4936
4937
    /**
4938
     * Display survey question chart
4939
     * @param	array	Chart data
4940
     * @param	boolean	Tells if the chart has a serie. False by default
4941
     * @return	void 	(direct output)
4942
     */
4943
    public static function drawChart($chartData, $hasSerie = false, $chartContainerId = 'chartContainer')
4944
    {
4945
        $htmlChart = '';
4946
        if (api_browser_support("svg")) {
4947
            $htmlChart .= api_get_js("d3/d3.v3.5.4.min.js");
4948
            $htmlChart .= api_get_js("dimple.v2.1.2.min.js") . '
4949
            <script type="text/javascript">
4950
            var svg = dimple.newSvg("#'.$chartContainerId.'", "100%", 400);
4951
            var data = [';
4952
            $serie = array();
4953
            $order = array();
4954
            foreach ($chartData as $chartDataElement) {
4955
                $htmlChart .= '{"';
4956
                if (!$hasSerie) {
4957
                    $htmlChart .= get_lang("Option") . '":"' . $chartDataElement['option'] . '", "';
4958
                    array_push($order, $chartDataElement['option']);
4959
                } else {
4960
                    if (!is_array($chartDataElement['serie'])) {
4961
                        $htmlChart .= get_lang("Option") . '":"' . $chartDataElement['serie'] . '", "' .
4962
                            get_lang("Score") . '":"' . $chartDataElement['option'] . '", "';
4963
                        array_push($serie, $chartDataElement['serie']);
4964
                    } else {
4965
                        $htmlChart .= get_lang("Serie") . '":"' . $chartDataElement['serie'][0] . '", "' .
4966
                            get_lang("Option") . '":"' . $chartDataElement['serie'][1] . '", "' .
4967
                            get_lang("Score") . '":"' . $chartDataElement['option'] . '", "';
4968
                    }
4969
                }
4970
                $htmlChart .= get_lang("Votes") . '":"' . $chartDataElement['votes'] .
4971
                    '"},';
4972
            }
4973
            rtrim($htmlChart, ",");
4974
            $htmlChart .= '];
4975
                var myChart = new dimple.chart(svg, data);
4976
                myChart.addMeasureAxis("y", "' . get_lang("Votes") . '");';
4977
            if (!$hasSerie) {
4978
                $htmlChart .= 'var xAxisCategory = myChart.addCategoryAxis("x", "' . get_lang("Option") . '");
4979
                    xAxisCategory.addOrderRule(' . json_encode($order) . ');
4980
                    myChart.addSeries("' . get_lang("Option") . '", dimple.plot.bar);';
4981
            } else {
4982
                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 4954. 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...
4983
                    $serie = array_values(array_unique($serie));
4984
                    $htmlChart .= 'var xAxisCategory = myChart.addCategoryAxis("x", ["' . get_lang("Option") . '","' . get_lang("Score") . '"]);
4985
                        xAxisCategory.addOrderRule(' . json_encode($serie) . ');
4986
                        xAxisCategory.addGroupOrderRule("' . get_lang("Score") . '");
4987
                        myChart.addSeries("' . get_lang("Option") . '", dimple.plot.bar);';
4988
                } else {
4989
                    $htmlChart .= 'myChart.addCategoryAxis("x", ["' . get_lang("Option") . '","' . get_lang("Score") . '"]);
4990
                        myChart.addSeries("' . get_lang("Serie") . '", dimple.plot.bar);';
4991
                }
4992
            }
4993
            $htmlChart .= 'myChart.draw();
4994
                </script>';
4995
        }
4996
        return $htmlChart;
4997
    }
4998
4999
    /**
5000
     * Set a flag to the current survey as answered by the current user
5001
     * @param string $surveyCode The survey code
5002
     * @param int $courseId The course ID
5003
     */
5004
    public static function flagSurveyAsAnswered($surveyCode, $courseId)
5005
    {
5006
        $currenUserId = api_get_user_id();
5007
        $flag = sprintf("%s-%s-%d", $courseId, $surveyCode, $currenUserId);
5008
5009
        if (!isset($_SESSION['filled_surveys'])) {
5010
            $_SESSION['filled_surveys'] = array();
5011
        }
5012
5013
        $_SESSION['filled_surveys'][] = $flag;
5014
    }
5015
5016
    /**
5017
     * Check whether a survey was answered by the current user
5018
     * @param string $surveyCode The survey code
5019
     * @param int $courseId The course ID
5020
     * @return boolean
5021
     */
5022
    public static function isSurveyAnsweredFlagged($surveyCode, $courseId)
5023
    {
5024
        $currenUserId = api_get_user_id();
5025
        $flagToCheck = sprintf("%s-%s-%d", $courseId, $surveyCode, $currenUserId);
5026
5027
        if (!isset($_SESSION['filled_surveys'])) {
5028
            return false;
5029
        }
5030
5031
        if (!is_array($_SESSION['filled_surveys'])) {
5032
            return false;
5033
        }
5034
5035
        foreach ($_SESSION['filled_surveys'] as $flag) {
5036
            if ($flagToCheck != $flag) {
5037
                continue;
5038
            }
5039
5040
            return true;
5041
        }
5042
5043
        return false;
5044
    }
5045
}
5046