Passed
Push — 1.10.x ( de380a...891fd1 )
by Angel Fernando Quiroz
44:35
created

SurveyManager::save_shared_question()   B

Complexity

Conditions 3
Paths 2

Size

Total Lines 46
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 31
nc 2
nop 2
dl 0
loc 46
rs 8.9411
c 0
b 0
f 0
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 (isset($GLOBALS['fillingSurvey']) && $GLOBALS['fillingSurvey']) {
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 i.surveyCode = s.code
1718
                    WHERE i.answered = 0
1719
                        AND i.cId = :course
1720
                        AND i.user = :user
1721
                        AND i.sessionId = :session
1722
                        AND :now BETWEEN s.availFrom AND s.availTill
1723
                    ORDER BY i.invitationDate ASC
1724
                ")
1725
                ->setMaxResults(1)
1726
                ->setParameters([
1727
                    'course' => $courseId,
1728
                    'user' => $userId,
1729
                    'session' => $sessionId,
1730
                    'now' => new DateTime('UTC', new DateTimeZone('UTC'))
1731
                ])
1732
                ->getSingleResult();
1733
        } catch (Exception $e) {
1734
            $invitation = null;
1735
        }
1736
1737
        if (!$invitation) {
1738
            return;
1739
        }
1740
1741
        $urlParams = http_build_query([
1742
            'course' => api_get_course_id(),
1743
            'invitationcode' => $invitation->getInvitationCode()
1744
        ]);
1745
1746
        Display::addFlash(
1747
            Display::return_message(get_lang('MandatorySurveyNoAnswered'), 'warning')
1748
        );
1749
1750
        header('Location: '.api_get_path(WEB_CODE_PATH).'survey/fillsurvey.php?'.$urlParams);
1751
        exit;
1752
    }
1753
}
1754
1755
1756
/**
1757
 * This class offers a series of general utility functions for survey querying and display
1758
 * @package chamilo.survey
1759
 */
1760
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...
1761
{
1762
    /**
1763
     * Checks whether the given survey has a pagebreak question as the first or the last question.
1764
     * If so, break the current process, displaying an error message
1765
     * @param	integer	Survey ID (database ID)
1766
     * @param	boolean	Optional. Whether to continue the current process or exit when breaking condition found. Defaults to true (do not break).
1767
     * @return	void
1768
     */
1769
    static function check_first_last_question($survey_id, $continue = true)
1770
    {
1771
        // Table definitions
1772
        $tbl_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
1773
        $course_id = api_get_course_int_id();
1774
1775
        // Getting the information of the question
1776
        $sql = "SELECT * FROM $tbl_survey_question
1777
                WHERE c_id = $course_id AND survey_id='".Database::escape_string($survey_id)."'
1778
                ORDER BY sort ASC";
1779
        $result = Database::query($sql);
1780
        $total = Database::num_rows($result);
1781
        $counter = 1;
1782
        $error = false;
1783
        while ($row = Database::fetch_array($result, 'ASSOC')) {
1784 View Code Duplication
            if ($counter == 1 && $row['type'] == 'pagebreak') {
1785
1786
                Display::display_error_message(get_lang('PagebreakNotFirst'), false);
1787
                $error = true;
1788
            }
1789 View Code Duplication
            if ($counter == $total && $row['type'] == 'pagebreak') {
1790
                Display::display_error_message(get_lang('PagebreakNotLast'), false);
1791
                $error = true;
1792
            }
1793
            $counter++;
1794
        }
1795
1796
        if (!$continue && $error) {
1797
            Display::display_footer();
1798
            exit;
1799
        }
1800
    }
1801
1802
    /**
1803
     * This function removes an (or multiple) answer(s) of a user on a question of a survey
1804
     *
1805
     * @param mixed   The user id or email of the person who fills the survey
1806
     * @param integer The survey id
1807
     * @param integer The question id
1808
     * @param integer The option id
1809
     *
1810
     * @author Patrick Cool <[email protected]>, Ghent University
1811
     * @version January 2007
1812
     */
1813
    static function remove_answer($user, $survey_id, $question_id, $course_id) {
1814
        $course_id = intval($course_id);
1815
        // table definition
1816
        $table_survey_answer 		= Database :: get_course_table(TABLE_SURVEY_ANSWER);
1817
        $sql = "DELETE FROM $table_survey_answer
1818
				WHERE
1819
				    c_id = $course_id AND
1820
                    user = '".Database::escape_string($user)."' AND
1821
                    survey_id = '".intval($survey_id)."' AND
1822
                    question_id = '".intval($question_id)."'";
1823
        Database::query($sql);
1824
    }
1825
1826
    /**
1827
     * This function stores an answer of a user on a question of a survey
1828
     *
1829
     * @param mixed   The user id or email of the person who fills the survey
1830
     * @param integer Survey id
1831
     * @param integer Question id
1832
     * @param integer Option id
1833
     * @param string  Option value
1834
     * @param array	  Survey data settings
1835
     *
1836
     * @author Patrick Cool <[email protected]>, Ghent University
1837
     * @version January 2007
1838
     */
1839
    static function store_answer($user, $survey_id, $question_id, $option_id, $option_value, $survey_data)
1840
    {
1841
        // Table definition
1842
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
1843
1844
        // Make the survey anonymous
1845
        if ($survey_data['anonymous'] == 1) {
1846
            if (!isset($_SESSION['surveyuser'])) {
1847
                $user = md5($user.time());
1848
                $_SESSION['surveyuser'] = $user;
1849
            } else {
1850
                $user = $_SESSION['surveyuser'];
1851
            }
1852
        }
1853
1854
        $course_id = $survey_data['c_id'];
1855
1856
        $sql = "INSERT INTO $table_survey_answer (c_id, user, survey_id, question_id, option_id, value) VALUES (
1857
				$course_id,
1858
				'".Database::escape_string($user)."',
1859
				'".Database::escape_string($survey_id)."',
1860
				'".Database::escape_string($question_id)."',
1861
				'".Database::escape_string($option_id)."',
1862
				'".Database::escape_string($option_value)."'
1863
				)";
1864
        Database::query($sql);
1865
        $insertId = Database::insert_id();
1866
1867
        $sql = "UPDATE $table_survey_answer SET answer_id = $insertId WHERE iid = $insertId";
1868
        Database::query($sql);
1869
    }
1870
1871
    /**
1872
     * This function checks the parameters that are used in this page
1873
     *
1874
     * @return 	string 	The header, an error and the footer if any parameter fails, else it returns true
1875
     * @author Patrick Cool <[email protected]>, Ghent University
1876
     * @version February 2007
1877
     */
1878
    static function check_parameters($people_filled)
1879
    {
1880
        $error = false;
1881
1882
        // Getting the survey data
1883
        $survey_data = SurveyManager::get_survey($_GET['survey_id']);
1884
1885
        // $_GET['survey_id'] has to be numeric
1886
        if (!is_numeric($_GET['survey_id'])) {
1887
            $error = get_lang('IllegalSurveyId');
1888
        }
1889
1890
        // $_GET['action']
1891
        $allowed_actions = array(
1892
            'overview',
1893
            'questionreport',
1894
            'userreport',
1895
            'comparativereport',
1896
            'completereport',
1897
            'deleteuserreport'
1898
        );
1899
        if (isset($_GET['action']) && !in_array($_GET['action'], $allowed_actions)) {
1900
            $error = get_lang('ActionNotAllowed');
1901
        }
1902
1903
        // User report
1904
        if (isset($_GET['action']) && $_GET['action'] == 'userreport') {
1905
            if ($survey_data['anonymous'] == 0) {
1906
                foreach ($people_filled as $key => & $value) {
1907
                    $people_filled_userids[] = $value['invited_user'];
1908
                }
1909
            } else {
1910
                $people_filled_userids = $people_filled;
1911
            }
1912
1913
            if (isset($_GET['user']) && !in_array($_GET['user'], $people_filled_userids)) {
1914
                $error = get_lang('UnknowUser');
1915
            }
1916
        }
1917
1918
        // Question report
1919
        if (isset($_GET['action']) && $_GET['action'] == 'questionreport') {
1920
            if (isset($_GET['question']) && !is_numeric($_GET['question'])) {
1921
                $error = get_lang('UnknowQuestion');
1922
            }
1923
        }
1924
1925
        if ($error) {
1926
            $tool_name = get_lang('Reporting');
1927
            Display::display_header($tool_name);
1928
            Display::display_error_message(get_lang('Error').': '.$error, false);
1929
            Display::display_footer();
1930
            exit;
1931
        } else {
1932
            return true;
1933
        }
1934
    }
1935
1936
    /**
1937
     * This function deals with the action handling
1938
     * @return	void
1939
     * @author Patrick Cool <[email protected]>, Ghent University
1940
     * @version February 2007
1941
     */
1942
    public static function handle_reporting_actions($survey_data, $people_filled)
1943
    {
1944
        $action = isset($_GET['action']) ? $_GET['action'] : null;
1945
1946
        // Getting the number of question
1947
        $temp_questions_data = SurveyManager::get_questions($_GET['survey_id']);
1948
1949
        // Sorting like they should be displayed and removing the non-answer question types (comment and pagebreak)
1950
        $my_temp_questions_data = $temp_questions_data == null ? array() : $temp_questions_data;
1951
        $questions_data = array();
1952
1953
        foreach ($my_temp_questions_data as $key => & $value) {
1954
            if ($value['type'] != 'comment' && $value['type'] != 'pagebreak') {
1955
                $questions_data[$value['sort']] = $value;
1956
            }
1957
        }
1958
1959
        // Counting the number of questions that are relevant for the reporting
1960
        $survey_data['number_of_questions'] = count($questions_data);
1961
1962
        if ($action == 'questionreport') {
1963
            SurveyUtil::display_question_report($survey_data);
1964
        }
1965
        if ($action == 'userreport') {
1966
            SurveyUtil::display_user_report($people_filled, $survey_data);
1967
        }
1968
        if ($action == 'comparativereport') {
1969
            SurveyUtil::display_comparative_report();
1970
        }
1971
        if ($action == 'completereport') {
1972
            SurveyUtil::display_complete_report($survey_data);
1973
        }
1974
        if ($action == 'deleteuserreport') {
1975
            SurveyUtil::delete_user_report($_GET['survey_id'], $_GET['user']);
1976
        }
1977
    }
1978
1979
    /**
1980
     * This function deletes the report of an user who wants to retake the survey
1981
     * @param integer survey_id
1982
     * @param integer user_id
1983
     * @return void
1984
     * @author Christian Fasanando Flores <[email protected]>
1985
     * @version November 2008
1986
     */
1987
    function delete_user_report($survey_id, $user_id)
1988
    {
1989
        $table_survey_answer = Database:: get_course_table(TABLE_SURVEY_ANSWER);
1990
        $table_survey_invitation = Database:: get_course_table(TABLE_SURVEY_INVITATION);
1991
        $table_survey = Database:: get_course_table(TABLE_SURVEY);
1992
1993
        $course_id = api_get_course_int_id();
1994
        $survey_id = (int) $survey_id;
1995
1996
        if (!empty($survey_id) && !empty($user_id)) {
1997
            $user_id = Database::escape_string($user_id);
1998
            // delete data from survey_answer by user_id and survey_id
1999
            $sql = "DELETE FROM $table_survey_answer
2000
			        WHERE c_id = $course_id AND survey_id = '".$survey_id."' AND user = '".$user_id."'";
2001
            Database::query($sql);
2002
            // update field answered from survey_invitation by user_id and survey_id
2003
            $sql = "UPDATE $table_survey_invitation SET answered = '0'
2004
			        WHERE
2005
			            c_id = $course_id AND
2006
			            survey_code = (
2007
                            SELECT code FROM $table_survey
2008
                            WHERE
2009
                                c_id = $course_id AND
2010
                                survey_id = '".(int)$survey_id."'
2011
                        ) AND
2012
			            user = '".$user_id."'";
2013
            $result = Database::query($sql);
2014
        }
2015
2016 View Code Duplication
        if ($result !== false) {
2017
            $message = get_lang('SurveyUserAnswersHaveBeenRemovedSuccessfully').'<br />
2018
					<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action=userreport&survey_id='.Security::remove_XSS($survey_id).'">'.get_lang('GoBack').'</a>';
2019
            Display::display_confirmation_message($message, false);
2020
        }
2021
    }
2022
2023
    /**
2024
     * This function displays the user report which is basically nothing more
2025
     * than a one-page display of all the questions
2026
     * of the survey that is filled with the answers of the person who filled the survey.
2027
     *
2028
     * @return 	string	html code of the one-page survey with the answers of the selected user
2029
     * @author Patrick Cool <[email protected]>, Ghent University
2030
     * @version February 2007 - Updated March 2008
2031
     */
2032
    public static function display_user_report($people_filled, $survey_data)
2033
    {
2034
        // Database table definitions
2035
        $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
2036
        $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
2037
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
2038
2039
        // Actions bar
2040
        echo '<div class="actions">';
2041
        echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.Security::remove_XSS($_GET['survey_id']).'">'.
2042
            Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('ReportingOverview'),'',ICON_SIZE_MEDIUM).'</a>';
2043
        if (isset($_GET['user'])) {
2044
            if (api_is_allowed_to_edit()) {
2045
                // The delete link
2046
                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']).'" >'.
2047
                    Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_MEDIUM).'</a>';
2048
            }
2049
2050
            // Export the user report
2051
            echo '<a href="javascript: void(0);" onclick="document.form1a.submit();">'.
2052
                Display::return_icon('export_csv.png', get_lang('ExportAsCSV'),'',ICON_SIZE_MEDIUM).'</a> ';
2053
            echo '<a href="javascript: void(0);" onclick="document.form1b.submit();">'.
2054
                Display::return_icon('export_excel.png', get_lang('ExportAsXLS'),'',ICON_SIZE_MEDIUM).'</a> ';
2055
            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']).'">';
2056
            echo '<input type="hidden" name="export_report" value="export_report">';
2057
            echo '<input type="hidden" name="export_format" value="csv">';
2058
            echo '</form>';
2059
            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']).'">';
2060
            echo '<input type="hidden" name="export_report" value="export_report">';
2061
            echo '<input type="hidden" name="export_format" value="xls">';
2062
            echo '</form>';
2063
            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']).'">';
2064
        }
2065
        echo '</div>';
2066
2067
        // Step 1: selection of the user
2068
        echo "<script>
2069
        function jumpMenu(targ,selObj,restore) {
2070
            eval(targ+\".location='\"+selObj.options[selObj.selectedIndex].value+\"'\");
2071
            if (restore) selObj.selectedIndex=0;
2072
        }
2073
		</script>";
2074
        echo get_lang('SelectUserWhoFilledSurvey').'<br />';
2075
        echo '<select name="user" onchange="jumpMenu(\'parent\',this,0)">';
2076
        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>';
2077
2078
        foreach ($people_filled as $key => & $person) {
2079
            if ($survey_data['anonymous'] == 0) {
2080
                $name = api_get_person_name($person['firstname'], $person['lastname']);
2081
                $id = $person['user_id'];
2082
                if ($id == '') {
2083
                    $id = $person['invited_user'];
2084
                    $name = $person['invited_user'];
2085
                }
2086
            } else {
2087
                $name  = get_lang('Anonymous') . ' ' . ($key + 1);
2088
                $id = $person;
2089
            }
2090
            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).'" ';
2091
            if (isset($_GET['user']) && $_GET['user'] == $id) {
2092
                echo 'selected="selected"';
2093
            }
2094
            echo '>'.$name.'</option>';
2095
        }
2096
        echo '</select>';
2097
2098
        $course_id = api_get_course_int_id();
2099
        // Step 2: displaying the survey and the answer of the selected users
2100
        if (isset($_GET['user'])) {
2101
            Display::display_normal_message(
2102
                get_lang('AllQuestionsOnOnePage'),
2103
                false
2104
            );
2105
2106
            // Getting all the questions and options
2107
            $sql = "SELECT
2108
			            survey_question.question_id,
2109
			            survey_question.survey_id,
2110
			            survey_question.survey_question,
2111
			            survey_question.display,
2112
			            survey_question.max_value,
2113
			            survey_question.sort,
2114
			            survey_question.type,
2115
                        survey_question_option.question_option_id,
2116
                        survey_question_option.option_text,
2117
                        survey_question_option.sort as option_sort
2118
					FROM $table_survey_question survey_question
2119
					LEFT JOIN $table_survey_question_option survey_question_option
2120
					ON
2121
					    survey_question.question_id = survey_question_option.question_id AND
2122
					    survey_question_option.c_id = $course_id
2123
					WHERE
2124
					    survey_question.survey_id = '".Database::escape_string(
2125
                    $_GET['survey_id']
2126
                )."' AND
2127
                        survey_question.c_id = $course_id
2128
					ORDER BY survey_question.sort, survey_question_option.sort ASC";
2129
            $result = Database::query($sql);
2130 View Code Duplication
            while ($row = Database::fetch_array($result, 'ASSOC')) {
2131
                if ($row['type'] != 'pagebreak') {
2132
                    $questions[$row['sort']]['question_id'] = $row['question_id'];
2133
                    $questions[$row['sort']]['survey_id'] = $row['survey_id'];
2134
                    $questions[$row['sort']]['survey_question'] = $row['survey_question'];
2135
                    $questions[$row['sort']]['display'] = $row['display'];
2136
                    $questions[$row['sort']]['type'] = $row['type'];
2137
                    $questions[$row['sort']]['maximum_score'] = $row['max_value'];
2138
                    $questions[$row['sort']]['options'][$row['question_option_id']] = $row['option_text'];
2139
                }
2140
            }
2141
2142
            // Getting all the answers of the user
2143
            $sql = "SELECT * FROM $table_survey_answer
2144
			        WHERE
2145
                        c_id = $course_id AND
2146
                        survey_id = '".intval($_GET['survey_id'])."' AND
2147
                        user = '".Database::escape_string($_GET['user'])."'";
2148
            $result = Database::query($sql);
2149
            while ($row = Database::fetch_array($result, 'ASSOC')) {
2150
                $answers[$row['question_id']][] = $row['option_id'];
2151
                $all_answers[$row['question_id']][] = $row;
2152
            }
2153
2154
            // Displaying all the questions
2155
2156
            foreach ($questions as & $question) {
2157
                // If the question type is a scoring then we have to format the answers differently
2158
                switch ($question['type']) {
2159
                    case 'score':
2160
                        $finalAnswer = array();
2161
                        if (is_array($question) && is_array($all_answers)) {
2162
                            foreach ($all_answers[$question['question_id']] as $key => & $answer_array) {
2163
                                $finalAnswer[$answer_array['option_id']] = $answer_array['value'];
2164
                            }
2165
                        }
2166
                        break;
2167
                    case 'multipleresponse':
2168
                        $finalAnswer = isset($answers[$question['question_id']]) ? $answers[$question['question_id']] : '';
2169
                        break;
2170
                    default:
2171
                        $finalAnswer = '';
2172
                        if (isset($all_answers[$question['question_id']])) {
2173
                            $finalAnswer = $all_answers[$question['question_id']][0]['option_id'];
2174
                        }
2175
                        break;
2176
                }
2177
2178
                $ch_type = 'ch_'.$question['type'];
2179
                /** @var survey_question $display */
2180
                $display = new $ch_type;
2181
2182
                $url = api_get_self();
2183
                $form = new FormValidator('question', 'post', $url);
2184
                $form->addHtml('<div class="survey_question_wrapper"><div class="survey_question">');
2185
                $form->addHtml($question['survey_question']);
2186
                $display->render($form, $question, $finalAnswer);
2187
                $form->addHtml('</div></div>');
2188
                $form->display();
2189
            }
2190
        }
2191
    }
2192
2193
    /**
2194
     * This function displays the report by question.
2195
     *
2196
     * It displays a table with all the options of the question and the number of users who have answered positively on the option.
2197
     * The number of users who answered positive on a given option is expressed in an absolute number, in a percentage of the total
2198
     * and graphically using bars
2199
     * By clicking on the absolute number you get a list with the persons who have answered this.
2200
     * 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
2201
     * answers of that user.
2202
     *
2203
     * @param 	array 	All the survey data
2204
     * @return 	string	html code that displays the report by question
2205
     * @todo allow switching between horizontal and vertical.
2206
     * @todo multiple response: percentage are probably not OK
2207
     * @todo the question and option text have to be shortened and should expand when the user clicks on it.
2208
     * @todo the pagebreak and comment question types should not be shown => removed from $survey_data before
2209
     * @author Patrick Cool <[email protected]>, Ghent University
2210
     * @version February 2007 - Updated March 2008
2211
     */
2212
    public static function display_question_report($survey_data)
2213
    {
2214
        $singlePage = isset($_GET['single_page']) ? intval($_GET['single_page']) : 0;
2215
        $course_id = api_get_course_int_id();
2216
        // Database table definitions
2217
        $table_survey_question 			= Database :: get_course_table(TABLE_SURVEY_QUESTION);
2218
        $table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
2219
        $table_survey_answer 			= Database :: get_course_table(TABLE_SURVEY_ANSWER);
2220
2221
        // Determining the offset of the sql statement (the n-th question of the survey)
2222
        $offset = !isset($_GET['question']) ? 0 : intval($_GET['question']);
2223
        $currentQuestion = isset($_GET['question']) ? intval($_GET['question']) : 0;
2224
        $questions = array();
2225
        $surveyId = intval($_GET['survey_id']);
2226
        $action = Security::remove_XSS($_GET['action']);
2227
2228
        echo '<div class="actions">';
2229
        echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.$surveyId.'">'.
2230
            Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('ReportingOverview'),'',ICON_SIZE_MEDIUM).'</a>';
2231
        echo '</div>';
2232
2233
        if ($survey_data['number_of_questions'] > 0) {
2234
            $limitStatement = null;
2235
            if (!$singlePage) {
2236
                echo '<div id="question_report_questionnumbers" class="pagination">';
2237
                if ($currentQuestion != 0) {
2238
                    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>';
2239
                }
2240
2241
                for ($i = 1; $i <= $survey_data['number_of_questions']; $i++) {
2242
                    if ($offset != $i - 1) {
2243
                        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>';
2244
                    } else {
2245
                        echo '<li class="disabled"s><a href="#">' . $i . '</a></li>';
2246
                    }
2247
                }
2248
                if ($currentQuestion < ($survey_data['number_of_questions'] - 1)) {
2249
                    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>';
2250
                }
2251
                echo '</ul>';
2252
                echo '</div>';
2253
                $limitStatement = " LIMIT $offset, 1";
2254
            }
2255
2256
            // Getting the question information
2257
            $sql = "SELECT * FROM $table_survey_question
2258
			        WHERE
2259
			            c_id = $course_id AND
2260
                        survey_id='".Database::escape_string($_GET['survey_id'])."' AND
2261
                        type<>'pagebreak' AND type<>'comment'
2262
                    ORDER BY sort ASC
2263
                    $limitStatement";
2264
            $result = Database::query($sql);
2265
2266
            while ($row = Database::fetch_array($result)) {
2267
                $questions[$row['question_id']] = $row;
2268
            }
2269
        }
2270
2271
        foreach ($questions as $question) {
2272
            $chartData = array();
2273
            $options = array();
2274
            echo '<div class="title-question">';
2275
            echo strip_tags(isset($question['survey_question']) ? $question['survey_question'] : null);
2276
            echo '</div>';
2277
2278
            if ($question['type'] == 'score') {
2279
                /** @todo This function should return the options as this is needed further in the code */
2280
                $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...
2281
            } elseif ($question['type'] == 'open') {
2282
                /** @todo Also get the user who has answered this */
2283
                $sql = "SELECT * FROM $table_survey_answer
2284
                        WHERE
2285
                            c_id = $course_id AND
2286
                            survey_id='" . intval($_GET['survey_id']) . "' AND
2287
                            question_id = '" . intval($question['question_id']) . "'";
2288
                $result = Database::query($sql);
2289
                while ($row = Database::fetch_array($result)) {
2290
                    echo $row['option_id'] . '<hr noshade="noshade" size="1" />';
2291
                }
2292
            } else {
2293
                // Getting the options ORDER BY sort ASC
2294
                $sql = "SELECT * FROM $table_survey_question_option
2295
                        WHERE
2296
                            c_id = $course_id AND
2297
                            survey_id='" . intval($_GET['survey_id']) . "'
2298
                            AND question_id = '" . intval($question['question_id']) . "'
2299
                        ORDER BY sort ASC";
2300
                $result = Database::query($sql);
2301
                while ($row = Database::fetch_array($result)) {
2302
                    $options[$row['question_option_id']] = $row;
2303
                }
2304
2305
                // Getting the answers
2306
                $sql = "SELECT *, count(answer_id) as total FROM $table_survey_answer
2307
                        WHERE
2308
                            c_id = $course_id AND
2309
                            survey_id='" . intval($_GET['survey_id']) . "'
2310
                            AND question_id = '" . intval($question['question_id']) . "'
2311
                        GROUP BY option_id, value";
2312
                $result = Database::query($sql);
2313
                $number_of_answers = array();
2314
                $data = array();
2315 View Code Duplication
                while ($row = Database::fetch_array($result)) {
2316
                    if (!isset($number_of_answers[$row['question_id']])) {
2317
                        $number_of_answers[$row['question_id']] = 0;
2318
                    }
2319
                    $number_of_answers[$row['question_id']] += $row['total'];
2320
                    $data[$row['option_id']] = $row;
2321
                }
2322
2323
                foreach ($options as $option) {
2324
                    $optionText = strip_tags($option['option_text']);
2325
                    $optionText = html_entity_decode($optionText);
2326
                    $votes = isset($data[$option['question_option_id']]['total']) ?
2327
                        $data[$option['question_option_id']]['total'] :
2328
                        '0';
2329
                    array_push($chartData, array('option' => $optionText, 'votes' => $votes));
2330
                }
2331
                $chartContainerId = 'chartContainer'.$question['question_id'];
2332
                echo '<div id="'.$chartContainerId.'" class="col-md-12">';
2333
                echo self::drawChart($chartData, false, $chartContainerId);
2334
2335
                // displaying the table: headers
2336
2337
                echo '<table class="display-survey table">';
2338
                echo '	<tr>';
2339
                echo '		<th>&nbsp;</th>';
2340
                echo '		<th>' . get_lang('AbsoluteTotal') . '</th>';
2341
                echo '		<th>' . get_lang('Percentage') . '</th>';
2342
                echo '		<th>' . get_lang('VisualRepresentation') . '</th>';
2343
                echo '	<tr>';
2344
2345
                // Displaying the table: the content
2346
                if (is_array($options)) {
2347
                    foreach ($options as $key => & $value) {
2348
                        $absolute_number = null;
2349
                        if (isset($data[$value['question_option_id']])) {
2350
                            $absolute_number = $data[$value['question_option_id']]['total'];
2351
                        }
2352
                        if ($question['type'] == 'percentage' && empty($absolute_number)) {
2353
                            continue;
2354
                        }
2355
                        if ($number_of_answers[$option['question_id']] == 0) {
2356
                            $answers_number = 0;
2357
                        } else {
2358
                            $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 2323. 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...
2359
                        }
2360
                        echo '	<tr>';
2361
                        echo '		<td class="center">' . $value['option_text'] . '</td>';
2362
                        echo '		<td class="center">';
2363
                        if ($absolute_number != 0) {
2364
                            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>';
2365
                        } else {
2366
                            echo '0';
2367
                        }
2368
2369
                        echo '      </td>';
2370
                        echo '		<td class="center">' . round($answers_number, 2) . ' %</td>';
2371
                        echo '		<td class="center">';
2372
                        $size = $answers_number * 2;
2373
                        if ($size > 0) {
2374
                            echo '<div style="border:1px solid #264269; background-color:#aecaf4; height:10px; width:' . $size . 'px">&nbsp;</div>';
2375
                        } else {
2376
                            echo '<div style="text-align: left;">' . get_lang("NoDataAvailable") . '</div>';
2377
                        }
2378
                        echo ' </td>';
2379
                        echo ' </tr>';
2380
                    }
2381
                }
2382
                // displaying the table: footer (totals)
2383
                echo '	<tr>';
2384
                echo '		<td class="total"><b>' . get_lang('Total') . '</b></td>';
2385
                echo '		<td class="total"><b>' . ($number_of_answers[$option['question_id']] == 0 ? '0' : $number_of_answers[$option['question_id']]) . '</b></td>';
2386
                echo '		<td class="total">&nbsp;</td>';
2387
                echo '		<td class="total">&nbsp;</td>';
2388
                echo '	</tr>';
2389
2390
                echo '</table>';
2391
2392
                echo '</div>';
2393
            }
2394
        }
2395
        if (isset($_GET['viewoption'])) {
2396
            echo '<div class="answered-people">';
2397
2398
            echo '<h4>'.get_lang('PeopleWhoAnswered').': '.strip_tags($options[Security::remove_XSS($_GET['viewoption'])]['option_text']).'</h4>';
2399
2400
            if (is_numeric($_GET['value'])) {
2401
                $sql_restriction = "AND value='".Database::escape_string($_GET['value'])."'";
2402
            }
2403
2404
            $sql = "SELECT user FROM $table_survey_answer
2405
                    WHERE
2406
                        c_id = $course_id AND
2407
                        option_id = '".Database::escape_string($_GET['viewoption'])."'
2408
                        $sql_restriction";
2409
            $result = Database::query($sql);
2410
            echo '<ul>';
2411 View Code Duplication
            while ($row = Database::fetch_array($result)) {
2412
                $user_info = api_get_user_info($row['user']);
2413
                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>';
2414
            }
2415
            echo '</ul>';
2416
            echo '</div>';
2417
        }
2418
    }
2419
2420
    /**
2421
     * Display score data about a survey question
2422
     * @param	array	Question info
2423
     * @param	integer	The offset of results shown
2424
     * @return	void 	(direct output)
2425
     */
2426
    public static function display_question_report_score($survey_data, $question, $offset)
2427
    {
2428
        // Database table definitions
2429
        $table_survey_question_option 	= Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
2430
        $table_survey_answer 			= Database :: get_course_table(TABLE_SURVEY_ANSWER);
2431
2432
        $course_id = api_get_course_int_id();
2433
2434
        // Getting the options
2435
        $sql = "SELECT * FROM $table_survey_question_option
2436
                WHERE
2437
                    c_id = $course_id AND
2438
                    survey_id='".Database::escape_string($_GET['survey_id'])."' AND
2439
                    question_id = '".Database::escape_string($question['question_id'])."'
2440
                ORDER BY sort ASC";
2441
        $result = Database::query($sql);
2442
        while ($row = Database::fetch_array($result)) {
2443
            $options[$row['question_option_id']] = $row;
2444
        }
2445
2446
        // Getting the answers
2447
        $sql = "SELECT *, count(answer_id) as total FROM $table_survey_answer
2448
                WHERE
2449
                   c_id = $course_id AND
2450
                   survey_id='".Database::escape_string($_GET['survey_id'])."' AND
2451
                   question_id = '".Database::escape_string($question['question_id'])."'
2452
                GROUP BY option_id, value";
2453
        $result = Database::query($sql);
2454
        $number_of_answers = 0;
2455 View Code Duplication
        while ($row = Database::fetch_array($result)) {
2456
            $number_of_answers += $row['total'];
2457
            $data[$row['option_id']][$row['value']] = $row;
2458
        }
2459
2460
        $chartData = array();
2461
        foreach ($options as $option) {
2462
            $optionText = strip_tags($option['option_text']);
2463
            $optionText = html_entity_decode($optionText);
2464
            for ($i = 1; $i <= $question['max_value']; $i++) {
2465
                $votes = $data[$option['question_option_id']][$i]['total'];
2466
                if (empty($votes)) {
2467
                    $votes = '0';
2468
                }
2469
                array_push(
2470
                    $chartData,
2471
                    array(
2472
                        'serie' => $optionText,
2473
                        'option' => $i,
2474
                        'votes' => $votes
2475
                    )
2476
                );
2477
            }
2478
        }
2479
        echo '<div id="chartContainer" class="col-md-12">';
2480
        echo self::drawChart($chartData, true);
2481
        echo '</div>';
2482
2483
        // Displaying the table: headers
2484
        echo '<table class="data_table">';
2485
        echo '	<tr>';
2486
        echo '		<th>&nbsp;</th>';
2487
        echo '		<th>'.get_lang('Score').'</th>';
2488
        echo '		<th>'.get_lang('AbsoluteTotal').'</th>';
2489
        echo '		<th>'.get_lang('Percentage').'</th>';
2490
        echo '		<th>'.get_lang('VisualRepresentation').'</th>';
2491
        echo '	<tr>';
2492
        // Displaying the table: the content
2493
        foreach ($options as $key => & $value) {
2494
            for ($i = 1; $i <= $question['max_value']; $i++) {
2495
                $absolute_number = $data[$value['question_option_id']][$i]['total'];
2496
                echo '	<tr>';
2497
                echo '		<td>'.$value['option_text'].'</td>';
2498
                echo '		<td>'.$i.'</td>';
2499
                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...
2500
                echo '		<td>'.round($absolute_number/$number_of_answers*100, 2).' %</td>';
2501
                echo '		<td>';
2502
                $size = ($absolute_number/$number_of_answers*100*2);
2503
                if ($size > 0) {
2504
                    echo '			<div style="border:1px solid #264269; background-color:#aecaf4; height:10px; width:'.$size.'px">&nbsp;</div>';
2505
                }
2506
                echo '		</td>';
2507
                echo '	</tr>';
2508
            }
2509
        }
2510
        // Displaying the table: footer (totals)
2511
        echo '	<tr>';
2512
        echo '		<td style="border-top:1px solid black"><b>'.get_lang('Total').'</b></td>';
2513
        echo '		<td style="border-top:1px solid black">&nbsp;</td>';
2514
        echo '		<td style="border-top:1px solid black"><b>'.$number_of_answers.'</b></td>';
2515
        echo '		<td style="border-top:1px solid black">&nbsp;</td>';
2516
        echo '		<td style="border-top:1px solid black">&nbsp;</td>';
2517
        echo '	</tr>';
2518
2519
        echo '</table>';
2520
    }
2521
2522
    /**
2523
     * This functions displays the complete reporting
2524
     * @return	string	HTML code
2525
     * @todo open questions are not in the complete report yet.
2526
     * @author Patrick Cool <[email protected]>, Ghent University
2527
     * @version February 2007
2528
     */
2529
    public static function display_complete_report($survey_data)
2530
    {
2531
        // Database table definitions
2532
        $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
2533
        $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
2534
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
2535
2536
        // Actions bar
2537
        echo '<div class="actions">';
2538
        echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.Security::remove_XSS($_GET['survey_id']).'">
2539
		'.Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('ReportingOverview'),'',ICON_SIZE_MEDIUM).'</a>';
2540
        echo '<a class="survey_export_link" href="javascript: void(0);" onclick="document.form1a.submit();">
2541
		'.Display::return_icon('export_csv.png',get_lang('ExportAsCSV'),'',ICON_SIZE_MEDIUM).'</a>';
2542
        echo '<a class="survey_export_link" href="javascript: void(0);" onclick="document.form1b.submit();">
2543
		'.Display::return_icon('export_excel.png',get_lang('ExportAsXLS'),'',ICON_SIZE_MEDIUM).'</a>';
2544
        echo '</div>';
2545
2546
        // The form
2547
        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']).'">';
2548
        echo '<input type="hidden" name="export_report" value="export_report">';
2549
        echo '<input type="hidden" name="export_format" value="csv">';
2550
        echo '</form>';
2551
        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']).'">';
2552
        echo '<input type="hidden" name="export_report" value="export_report">';
2553
        echo '<input type="hidden" name="export_format" value="xls">';
2554
        echo '</form>';
2555
2556
        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']).'">';
2557
2558
        // The table
2559
        echo '<br /><table class="data_table" border="1">';
2560
        // Getting the number of options per question
2561
        echo '	<tr>';
2562
        echo '		<th>';
2563
        if (isset($_POST['submit_question_filter']) && $_POST['submit_question_filter'] ||
2564
            isset($_POST['export_report']) && $_POST['export_report']) {
2565
            echo '<button class="cancel" type="submit" name="reset_question_filter" value="'.get_lang('ResetQuestionFilter').'">'.get_lang('ResetQuestionFilter').'</button>';
2566
        }
2567
        echo '<button class="save" type="submit" name="submit_question_filter" value="'.get_lang('SubmitQuestionFilter').'">'.get_lang('SubmitQuestionFilter').'</button>';
2568
        echo '</th>';
2569
2570
        $display_extra_user_fields = false;
2571
        if (!(isset($_POST['submit_question_filter']) && $_POST['submit_question_filter'] ||
2572
                isset($_POST['export_report']) && $_POST['export_report']) || !empty($_POST['fields_filter'])) {
2573
            // Show user fields section with a big th colspan that spans over all fields
2574
            $extra_user_fields = UserManager::get_extra_fields(0, 0, 5, 'ASC', false, true);
2575
            $num = count($extra_user_fields);
2576
            if ($num > 0 ) {
2577
                echo '<th '.($num>0?' colspan="'.$num.'"':'').'>';
2578
                echo '<label><input type="checkbox" name="fields_filter" value="1" checked="checked"/> ';
2579
                echo get_lang('UserFields');
2580
                echo '</label>';
2581
                echo '</th>';
2582
                $display_extra_user_fields = true;
2583
            }
2584
        }
2585
2586
        $course_id = api_get_course_int_id();
2587
2588
        // Get all the questions ordered by the "sort" column
2589
        // <hub> modify the query to display open questions too
2590
        //		$sql = "SELECT q.question_id, q.type, q.survey_question, count(o.question_option_id) as number_of_options
2591
        //				FROM $table_survey_question q LEFT JOIN $table_survey_question_option o
2592
        //				ON q.question_id = o.question_id
2593
        //				WHERE q.question_id = o.question_id
2594
        //				AND q.survey_id = '".Database::escape_string($_GET['survey_id'])."'
2595
        //				GROUP BY q.question_id
2596
        //				ORDER BY q.sort ASC";
2597
        $sql = "SELECT q.question_id, q.type, q.survey_question, count(o.question_option_id) as number_of_options
2598
				FROM $table_survey_question q LEFT JOIN $table_survey_question_option o
2599
				ON q.question_id = o.question_id
2600
				WHERE q.survey_id = '".Database::escape_string($_GET['survey_id'])."' AND
2601
				q.c_id = $course_id AND
2602
				o.c_id = $course_id
2603
				GROUP BY q.question_id
2604
				ORDER BY q.sort ASC";
2605
        // </hub>
2606
        $result = Database::query($sql);
2607
        while ($row = Database::fetch_array($result)) {
2608
            // We show the questions if
2609
            // 1. there is no question filter and the export button has not been clicked
2610
            // 2. there is a quesiton filter but the question is selected for display
2611
            //if (!($_POST['submit_question_filter'] || $_POST['export_report']) || in_array($row['question_id'], $_POST['questions_filter'])) {
2612
            if (!(isset($_POST['submit_question_filter']) && $_POST['submit_question_filter']) ||
2613
                (is_array($_POST['questions_filter']) &&
2614
                    in_array($row['question_id'], $_POST['questions_filter']))) {
2615
                // We do not show comment and pagebreak question types
2616
                if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
2617
                    echo ' <th';
2618
                    // <hub> modified tst to include percentage
2619
                    if ($row['number_of_options'] > 0 && $row['type'] != 'percentage') {
2620
                        // </hub>
2621
                        echo ' colspan="'.$row['number_of_options'].'"';
2622
                    }
2623
                    echo '>';
2624
2625
                    echo '<label><input type="checkbox" name="questions_filter[]" value="'.$row['question_id'].'" checked="checked"/> ';
2626
                    echo $row['survey_question'];
2627
                    echo '</label>';
2628
                    echo '</th>';
2629
                }
2630
                // No column at all if it's not a question
2631
            }
2632
            $questions[$row['question_id']] = $row;
2633
        }
2634
        echo '	</tr>';
2635
        // Getting all the questions and options
2636
        echo '	<tr>';
2637
        echo '		<th>&nbsp;</th>'; // the user column
2638
2639
        if (!(isset($_POST['submit_question_filter']) && $_POST['submit_question_filter'] ||
2640
                isset($_POST['export_report']) && $_POST['export_report']) || !empty($_POST['fields_filter'])) {
2641
            //show the fields names for user fields
2642
            foreach($extra_user_fields as & $field) {
2643
                echo '<th>'.$field[3].'</th>';
2644
            }
2645
        }
2646
2647
        // cells with option (none for open question)
2648
        $sql = "SELECT 	sq.question_id, sq.survey_id,
2649
						sq.survey_question, sq.display,
2650
						sq.sort, sq.type, sqo.question_option_id,
2651
						sqo.option_text, sqo.sort as option_sort
2652
				FROM $table_survey_question sq
2653
				LEFT JOIN $table_survey_question_option sqo
2654
				ON sq.question_id = sqo.question_id
2655
				WHERE
2656
				    sq.survey_id = '".Database::escape_string($_GET['survey_id'])."' AND
2657
                    sq.c_id = $course_id AND
2658
                    sqo.c_id = $course_id
2659
				ORDER BY sq.sort ASC, sqo.sort ASC";
2660
        $result = Database::query($sql);
2661
2662
        $display_percentage_header = 1;	// in order to display only once the cell option (and not 100 times)
2663
        while ($row = Database::fetch_array($result)) {
2664
            // We show the options if
2665
            // 1. there is no question filter and the export button has not been clicked
2666
            // 2. there is a question filter but the question is selected for display
2667
            //if (!($_POST['submit_question_filter'] || $_POST['export_report']) || in_array($row['question_id'], $_POST['questions_filter'])) {
2668
            if (!(isset($_POST['submit_question_filter']) && $_POST['submit_question_filter']) ||
2669
                (is_array($_POST['questions_filter']) && in_array($row['question_id'], $_POST['questions_filter']))
2670
            ) {
2671
                // <hub> modif 05-05-2010
2672
                // we do not show comment and pagebreak question types
2673
                if ($row['type'] == 'open') {
2674
                    echo '<th>&nbsp;-&nbsp;</th>';
2675
                    $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
2676
                    $display_percentage_header = 1;
2677
                } else if ($row['type'] == 'percentage' && $display_percentage_header) {
2678
                    echo '<th>&nbsp;%&nbsp;</th>';
2679
                    $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
2680
                    $display_percentage_header = 0;
2681
                } else if ($row['type'] == 'percentage') {
2682
                    $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
2683
                } else if ($row['type'] <> 'comment' AND $row['type'] <> 'pagebreak' AND $row['type'] <> 'percentage') {
2684
                    echo '<th>';
2685
                    echo $row['option_text'];
2686
                    echo '</th>';
2687
                    $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
2688
                    $display_percentage_header = 1;
2689
                }
2690
                //no column at all if the question was not a question
2691
                // </hub>
2692
            }
2693
        }
2694
2695
        echo '	</tr>';
2696
2697
        // Getting all the answers of the users
2698
        $old_user = '';
2699
        $answers_of_user = array();
2700
        $sql = "SELECT * FROM $table_survey_answer
2701
                WHERE
2702
                    c_id = $course_id AND
2703
                    survey_id='".intval($_GET['survey_id'])."'
2704
                ORDER BY answer_id, user ASC";
2705
        $result = Database::query($sql);
2706
        $i = 1;
2707
        while ($row = Database::fetch_array($result)) {
2708
            if ($old_user != $row['user'] && $old_user != '') {
2709
                $userParam = $old_user;
2710
                if ($survey_data['anonymous'] != 0) {
2711
                    $userParam = $i;
2712
                    $i++;
2713
                }
2714
                SurveyUtil::display_complete_report_row(
2715
                    $survey_data,
2716
                    $possible_answers,
2717
                    $answers_of_user,
2718
                    $userParam,
2719
                    $questions,
2720
                    $display_extra_user_fields
2721
                );
2722
                $answers_of_user=array();
2723
            }
2724
            if (isset($questions[$row['question_id']]) && $questions[$row['question_id']]['type'] != 'open') {
2725
                $answers_of_user[$row['question_id']][$row['option_id']] = $row;
2726
            } else {
2727
                $answers_of_user[$row['question_id']][0] = $row;
2728
            }
2729
            $old_user = $row['user'];
2730
        }
2731
        $userParam = $old_user;
2732
        if ($survey_data['anonymous'] != 0) {
2733
            $userParam = $i;
2734
            $i++;
2735
        }
2736
        SurveyUtil::display_complete_report_row(
2737
            $survey_data,
2738
            $possible_answers,
2739
            $answers_of_user,
2740
            $userParam,
2741
            $questions,
2742
            $display_extra_user_fields
2743
        );
2744
        // This is to display the last user
2745
        echo '</table>';
2746
        echo '</form>';
2747
    }
2748
2749
    /**
2750
     * This function displays a row (= a user and his/her answers) in the table of the complete report.
2751
     *
2752
     * @param array $survey_data
2753
     * @param 	array	Possible options
2754
     * @param 	array 	User answers
2755
     * @param	mixed	User ID or user details string
2756
     * @param	boolean	Whether to show extra user fields or not
2757
     * @author Patrick Cool <[email protected]>, Ghent University
2758
     * @version February 2007 - Updated March 2008
2759
     */
2760
    static function display_complete_report_row(
2761
        $survey_data,
2762
        $possible_options,
2763
        $answers_of_user,
2764
        $user,
2765
        $questions,
2766
        $display_extra_user_fields = false
2767
    ) {
2768
        $user = Security::remove_XSS($user);
2769
        echo '<tr>';
2770
        if ($survey_data['anonymous'] == 0) {
2771
            if (intval($user) !== 0) {
2772
                $userInfo = api_get_user_info($user);
2773
                if (!empty($userInfo)) {
2774
                    $user_displayed = $userInfo['complete_name'];
2775
                } else {
2776
                    $user_displayed = '-';
2777
                }
2778
                echo '<th><a href="'.api_get_self().'?action=userreport&survey_id='.Security::remove_XSS($_GET['survey_id']).'&user='.$user.'">'.
2779
                    $user_displayed.'</a></th>'; // the user column
2780
            } else {
2781
                echo '<th>'.$user.'</th>'; // the user column
2782
            }
2783
        } else {
2784
            echo '<th>' . get_lang('Anonymous') . ' ' . $user . '</th>';
2785
        }
2786
2787
        if ($display_extra_user_fields) {
2788
            // Show user fields data, if any, for this user
2789
            $user_fields_values = UserManager::get_extra_user_data(intval($user), false, false, false, true);
2790
            foreach ($user_fields_values as & $value) {
2791
                echo '<td align="center">'.$value.'</td>';
2792
            }
2793
        }
2794
        if (is_array($possible_options)) {
2795
            // <hub> modified to display open answers and percentage
2796
            foreach ($possible_options as $question_id => & $possible_option) {
2797
                if ($questions[$question_id]['type'] == 'open') {
2798
                    echo '<td align="center">';
2799
                    echo $answers_of_user[$question_id]['0']['option_id'];
2800
                    echo '</td>';
2801
                } else {
2802
                    foreach ($possible_option as $option_id => & $value) {
2803
                        if ($questions[$question_id]['type'] == 'percentage') {
2804 View Code Duplication
                            if (!empty($answers_of_user[$question_id][$option_id])) {
2805
                                echo "<td align='center'>";
2806
                                echo $answers_of_user[$question_id][$option_id]['value'];
2807
                                echo "</td>";
2808
                            }
2809
                        }
2810
                        else {
2811
                            echo '<td align="center">';
2812
                            if (!empty($answers_of_user[$question_id][$option_id])) {
2813 View Code Duplication
                                if ($answers_of_user[$question_id][$option_id]['value'] != 0) {
2814
                                    echo $answers_of_user[$question_id][$option_id]['value'];
2815
                                }
2816
                                else {
2817
                                    echo 'v';
2818
                                }
2819
                            }
2820
                        } // </hub>
2821
                    }
2822
                }
2823
            }
2824
        }
2825
        echo '</tr>';
2826
    }
2827
2828
    /**
2829
     * Quite similar to display_complete_report(), returns an HTML string
2830
     * that can be used in a csv file
2831
     * @todo consider merging this function with display_complete_report
2832
     * @return	string	The contents of a csv file
2833
     * @author Patrick Cool <[email protected]>, Ghent University
2834
     * @version February 2007
2835
     */
2836
    public static function export_complete_report($survey_data, $user_id = 0)
2837
    {
2838
        // Database table definitions
2839
        $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
2840
        $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
2841
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
2842
2843
        // The first column
2844
        $return = ';';
2845
2846
        // Show extra fields blank space (enough for extra fields on next line)
2847
2848
        $extra_user_fields = UserManager::get_extra_fields(0, 0, 5, 'ASC', false, true);
2849
2850
        $num = count($extra_user_fields);
2851
        $return .= str_repeat(';', $num);
2852
2853
        $course_id = api_get_course_int_id();
2854
2855
        $sql = "SELECT
2856
                    questions.question_id,
2857
                    questions.type,
2858
                    questions.survey_question,
2859
                    count(options.question_option_id) as number_of_options
2860
				FROM $table_survey_question questions
2861
                LEFT JOIN $table_survey_question_option options
2862
				ON questions.question_id = options.question_id  AND options.c_id = $course_id
2863
				WHERE
2864
				    questions.survey_id = '".intval($_GET['survey_id'])."' AND
2865
                    questions.c_id = $course_id
2866
				GROUP BY questions.question_id
2867
				ORDER BY questions.sort ASC";
2868
        $result = Database::query($sql);
2869
        while ($row = Database::fetch_array($result)) {
2870
            // We show the questions if
2871
            // 1. there is no question filter and the export button has not been clicked
2872
            // 2. there is a quesiton filter but the question is selected for display
2873
            if (!($_POST['submit_question_filter']) ||
2874
                (is_array($_POST['questions_filter']) &&
2875
                    in_array($row['question_id'], $_POST['questions_filter']))
2876
            ) {
2877
                // We do not show comment and pagebreak question types
2878
                if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
2879
                    if ($row['number_of_options'] == 0 && $row['type'] == 'open') {
2880
                        $return .= str_replace("\r\n",'  ', api_html_entity_decode(strip_tags($row['survey_question']), ENT_QUOTES)).';';
2881
                    } else {
2882
                        for ($ii = 0; $ii < $row['number_of_options']; $ii++) {
2883
                            $return .= str_replace("\r\n",'  ', api_html_entity_decode(strip_tags($row['survey_question']), ENT_QUOTES)).';';
2884
                        }
2885
                    }
2886
                }
2887
            }
2888
        }
2889
        $return .= "\n";
2890
2891
        // Getting all the questions and options
2892
        $return .= ';';
2893
2894
        // Show the fields names for user fields
2895
        if (!empty($extra_user_fields)) {
2896
            foreach ($extra_user_fields as & $field) {
2897
                $return .= '"'.str_replace("\r\n",'  ',api_html_entity_decode(strip_tags($field[3]), ENT_QUOTES)).'";';
2898
            }
2899
        }
2900
2901
        $sql = "SELECT
2902
		            survey_question.question_id,
2903
		            survey_question.survey_id,
2904
		            survey_question.survey_question,
2905
		            survey_question.display,
2906
		            survey_question.sort,
2907
		            survey_question.type,
2908
                    survey_question_option.question_option_id,
2909
                    survey_question_option.option_text,
2910
                    survey_question_option.sort as option_sort
2911
				FROM $table_survey_question survey_question
2912
				LEFT JOIN $table_survey_question_option survey_question_option
2913
				ON
2914
				    survey_question.question_id = survey_question_option.question_id AND
2915
				    survey_question_option.c_id = $course_id
2916
				WHERE
2917
				    survey_question.survey_id = '".intval($_GET['survey_id'])."' AND
2918
				    survey_question.c_id = $course_id
2919
				ORDER BY survey_question.sort ASC, survey_question_option.sort ASC";
2920
        $result = Database::query($sql);
2921
        $possible_answers = array();
2922
        $possible_answers_type = array();
2923
        while ($row = Database::fetch_array($result)) {
2924
            // We show the options if
2925
            // 1. there is no question filter and the export button has not been clicked
2926
            // 2. there is a quesiton filter but the question is selected for display
2927
            if (!($_POST['submit_question_filter']) || (is_array($_POST['questions_filter']) &&
2928
                in_array($row['question_id'], $_POST['questions_filter']))
2929
            ) {
2930
                // We do not show comment and pagebreak question types
2931
                if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
2932
                    $row['option_text'] = str_replace(array("\r","\n"),array('',''),$row['option_text']);
2933
                    $return .= api_html_entity_decode(strip_tags($row['option_text']), ENT_QUOTES).';';
2934
                    $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
2935
                    $possible_answers_type[$row['question_id']] = $row['type'];
2936
                }
2937
            }
2938
        }
2939
        $return .= "\n";
2940
2941
        // Getting all the answers of the users
2942
        $old_user = '';
2943
        $answers_of_user = array();
2944
        $sql = "SELECT * FROM $table_survey_answer
2945
		        WHERE c_id = $course_id AND survey_id='".Database::escape_string($_GET['survey_id'])."'";
2946
        if ($user_id != 0) {
2947
            $sql .= "AND user='".Database::escape_string($user_id)."' ";
2948
        }
2949
        $sql .= "ORDER BY user ASC";
2950
2951
        $open_question_iterator = 1;
2952
        $result = Database::query($sql);
2953
        while ($row = Database::fetch_array($result)) {
2954
            if ($old_user != $row['user'] && $old_user != '') {
2955
                $return .= SurveyUtil::export_complete_report_row(
2956
                    $survey_data,
2957
                    $possible_answers,
2958
                    $answers_of_user,
2959
                    $old_user,
2960
                    true
2961
                );
2962
                $answers_of_user=array();
2963
            }
2964 View Code Duplication
            if($possible_answers_type[$row['question_id']] == 'open') {
2965
                $temp_id = 'open'.$open_question_iterator;
2966
                $answers_of_user[$row['question_id']][$temp_id] = $row;
2967
                $open_question_iterator++;
2968
            } else {
2969
                $answers_of_user[$row['question_id']][$row['option_id']] = $row;
2970
            }
2971
            $old_user = $row['user'];
2972
        }
2973
        // This is to display the last user
2974
        $return .= SurveyUtil::export_complete_report_row(
2975
            $survey_data,
2976
            $possible_answers,
2977
            $answers_of_user,
2978
            $old_user,
2979
            true
2980
        );
2981
2982
        return $return;
2983
    }
2984
2985
    /**
2986
     * Add a line to the csv file
2987
     *
2988
     * @param	array	Possible answers
2989
     * @param	array	User's answers
2990
     * @param 	mixed	User ID or user details as string - Used as a string in the result string
2991
     * @param	boolean	Whether to display user fields or not
2992
     * @return	string	One line of the csv file
2993
     * @author Patrick Cool <[email protected]>, Ghent University
2994
     * @version February 2007
2995
     */
2996
    static function export_complete_report_row(
2997
        $survey_data,
2998
        $possible_options,
2999
        $answers_of_user,
3000
        $user,
3001
        $display_extra_user_fields = false
3002
    ) {
3003
        $return = '';
3004
        if ($survey_data['anonymous'] == 0) {
3005
            if (intval($user) !== 0) {
3006
                $userInfo = api_get_user_info($user);
3007
3008
                if (!empty($userInfo)) {
3009
                    $user_displayed = $userInfo['complete_name'];
3010
                } else {
3011
                    $user_displayed = '-';
3012
                }
3013
                $return .= $user_displayed.';';
3014
            } else {
3015
                $return .= $user.';';
3016
            }
3017
        } else {
3018
            $return .= '-;'; // The user column
3019
        }
3020
3021 View Code Duplication
        if ($display_extra_user_fields) {
3022
            // Show user fields data, if any, for this user
3023
            $user_fields_values = UserManager::get_extra_user_data($user,false,false, false, true);
3024
            foreach ($user_fields_values as & $value) {
3025
                $return .= '"'.str_replace('"', '""', api_html_entity_decode(strip_tags($value), ENT_QUOTES)).'";';
3026
            }
3027
        }
3028
3029
        if (is_array($possible_options)) {
3030
            foreach ($possible_options as $question_id => $possible_option) {
3031
                if (is_array($possible_option) && count($possible_option) > 0) {
3032
                    foreach ($possible_option as $option_id => & $value) {
3033
                        $my_answer_of_user = ($answers_of_user[$question_id] == null) ? array() : $answers_of_user[$question_id];
3034
                        $key = array_keys($my_answer_of_user);
3035
                        if (substr($key[0], 0, 4) == 'open') {
3036
                            $return .= '"'.str_replace('"', '""', api_html_entity_decode(strip_tags($answers_of_user[$question_id][$key[0]]['option_id']), ENT_QUOTES)).'"';
3037
                        } elseif (!empty($answers_of_user[$question_id][$option_id])) {
3038
                            //$return .= 'v';
3039
                            if ($answers_of_user[$question_id][$option_id]['value'] != 0) {
3040
                                $return .= $answers_of_user[$question_id][$option_id]['value'];
3041
                            } else {
3042
                                $return .= 'v';
3043
                            }
3044
                        }
3045
                        $return .= ';';
3046
                    }
3047
                }
3048
            }
3049
        }
3050
        $return .= "\n";
3051
        return $return;
3052
    }
3053
3054
    /**
3055
     * Quite similar to display_complete_report(), returns an HTML string
3056
     * that can be used in a csv file
3057
     * @todo consider merging this function with display_complete_report
3058
     * @return	string	The contents of a csv file
3059
     * @author Patrick Cool <[email protected]>, Ghent University
3060
     * @version February 2007
3061
     */
3062
    static function export_complete_report_xls($survey_data, $filename, $user_id = 0)
3063
    {
3064
        $spreadsheet = new PHPExcel();
3065
        $spreadsheet->setActiveSheetIndex(0);
3066
        $worksheet = $spreadsheet->getActiveSheet();
3067
        $line = 1;
3068
        $column = 1; // Skip the first column (row titles)
3069
3070
        // Show extra fields blank space (enough for extra fields on next line)
3071
        // Show user fields section with a big th colspan that spans over all fields
3072
        $extra_user_fields = UserManager::get_extra_fields(0, 0, 5, 'ASC', false, true);
3073
        $num = count($extra_user_fields);
3074
        for ($i = 0; $i < $num; $i++) {
3075
            $worksheet->setCellValueByColumnAndRow($column, $line, '');
3076
            $column++;
3077
        }
3078
        $display_extra_user_fields = true;
3079
3080
        // Database table definitions
3081
        $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
3082
        $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
3083
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
3084
3085
        $course_id = api_get_course_int_id();
3086
3087
        // First line (questions)
3088
        $sql = "SELECT
3089
                    questions.question_id,
3090
                    questions.type,
3091
                    questions.survey_question,
3092
                    count(options.question_option_id) as number_of_options
3093
				FROM $table_survey_question questions
3094
				LEFT JOIN $table_survey_question_option options
3095
                ON questions.question_id = options.question_id AND options.c_id = $course_id
3096
				WHERE
3097
				    questions.survey_id = '".intval($_GET['survey_id'])."' AND
3098
				    questions.c_id = $course_id
3099
				GROUP BY questions.question_id
3100
				ORDER BY questions.sort ASC";
3101
        $result = Database::query($sql);
3102
        while ($row = Database::fetch_array($result)) {
3103
            // We show the questions if
3104
            // 1. there is no question filter and the export button has not been clicked
3105
            // 2. there is a quesiton filter but the question is selected for display
3106
            if (!(isset($_POST['submit_question_filter'])) || (is_array($_POST['questions_filter']) &&
3107
                in_array($row['question_id'], $_POST['questions_filter']))
3108
            ) {
3109
                // We do not show comment and pagebreak question types
3110
                if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
3111
                    if ($row['number_of_options'] == 0 && $row['type'] == 'open') {
3112
                        $worksheet->setCellValueByColumnAndRow(
3113
                            $column,
3114
                            $line,
3115
                            api_html_entity_decode(
3116
                                strip_tags($row['survey_question']),
3117
                                ENT_QUOTES
3118
                            )
3119
                        );
3120
                        $column ++;
3121
                    } else {
3122
                        for ($ii = 0; $ii < $row['number_of_options']; $ii ++) {
3123
                            $worksheet->setCellValueByColumnAndRow(
3124
                                $column,
3125
                                $line,
3126
                                api_html_entity_decode(
3127
                                    strip_tags($row['survey_question']),
3128
                                    ENT_QUOTES
3129
                                )
3130
                            );
3131
                            $column ++;
3132
                        }
3133
                    }
3134
                }
3135
            }
3136
        }
3137
        $line++;
3138
        $column = 1;
3139
3140
        // Show extra field values
3141
        if ($display_extra_user_fields) {
3142
            // Show the fields names for user fields
3143
            foreach ($extra_user_fields as & $field) {
3144
                $worksheet->setCellValueByColumnAndRow(
3145
                    $column,
3146
                    $line,
3147
                    api_html_entity_decode(strip_tags($field[3]), ENT_QUOTES)
3148
                );
3149
                $column++;
3150
            }
3151
        }
3152
3153
        // Getting all the questions and options (second line)
3154
        $sql = "SELECT
3155
                    survey_question.question_id, survey_question.survey_id, survey_question.survey_question, survey_question.display, survey_question.sort, survey_question.type,
3156
                    survey_question_option.question_option_id, survey_question_option.option_text, survey_question_option.sort as option_sort
3157
				FROM $table_survey_question survey_question
3158
				LEFT JOIN $table_survey_question_option survey_question_option
3159
				ON survey_question.question_id = survey_question_option.question_id AND survey_question_option.c_id = $course_id
3160
				WHERE survey_question.survey_id = '".intval($_GET['survey_id'])."' AND
3161
				survey_question.c_id = $course_id
3162
				ORDER BY survey_question.sort ASC, survey_question_option.sort ASC";
3163
        $result = Database::query($sql);
3164
        $possible_answers = array();
3165
        $possible_answers_type = array();
3166
        while ($row = Database::fetch_array($result)) {
3167
            // We show the options if
3168
            // 1. there is no question filter and the export button has not been clicked
3169
            // 2. there is a quesiton filter but the question is selected for display
3170
            if (!(isset($_POST['submit_question_filter'])) ||
3171
                (is_array($_POST['questions_filter']) && in_array($row['question_id'], $_POST['questions_filter']))
3172
            ) {
3173
                // We do not show comment and pagebreak question types
3174
                if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
3175
                    $worksheet->setCellValueByColumnAndRow(
3176
                        $column,
3177
                        $line,
3178
                        api_html_entity_decode(
3179
                            strip_tags($row['option_text']),
3180
                            ENT_QUOTES
3181
                        )
3182
                    );
3183
                    $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
3184
                    $possible_answers_type[$row['question_id']] = $row['type'];
3185
                    $column++;
3186
                }
3187
            }
3188
        }
3189
3190
        // Getting all the answers of the users
3191
        $line ++;
3192
        $column = 0;
3193
        $old_user = '';
3194
        $answers_of_user = array();
3195
        $sql = "SELECT * FROM $table_survey_answer
3196
                WHERE c_id = $course_id AND survey_id='".intval($_GET['survey_id'])."' ";
3197
        if ($user_id != 0) {
3198
            $sql .= "AND user='".intval($user_id)."' ";
3199
        }
3200
        $sql .=	"ORDER BY user ASC";
3201
3202
        $open_question_iterator = 1;
3203
        $result = Database::query($sql);
3204
        while ($row = Database::fetch_array($result)) {
3205
            if ($old_user != $row['user'] && $old_user != '') {
3206
                $return = SurveyUtil::export_complete_report_row_xls(
3207
                    $survey_data,
3208
                    $possible_answers,
3209
                    $answers_of_user,
3210
                    $old_user,
3211
                    true
3212
                );
3213
                foreach ($return as $elem) {
3214
                    $worksheet->setCellValueByColumnAndRow($column, $line, $elem);
3215
                    $column++;
3216
                }
3217
                $answers_of_user = array();
3218
                $line++;
3219
                $column = 0;
3220
            }
3221 View Code Duplication
            if ($possible_answers_type[$row['question_id']] == 'open') {
3222
                $temp_id = 'open'.$open_question_iterator;
3223
                $answers_of_user[$row['question_id']][$temp_id] = $row;
3224
                $open_question_iterator++;
3225
            } else {
3226
                $answers_of_user[$row['question_id']][$row['option_id']] = $row;
3227
            }
3228
            $old_user = $row['user'];
3229
        }
3230
        $return = SurveyUtil::export_complete_report_row_xls(
3231
            $survey_data,
3232
            $possible_answers,
3233
            $answers_of_user,
3234
            $old_user,
3235
            true
3236
        );
3237
3238
        // this is to display the last user
3239
        foreach ($return as $elem) {
3240
            $worksheet->setCellValueByColumnAndRow($column, $line, $elem);
3241
            $column++;
3242
        }
3243
3244
        $file = api_get_path(SYS_ARCHIVE_PATH).api_replace_dangerous_char($filename);
3245
        $writer = new PHPExcel_Writer_Excel2007($spreadsheet);
3246
        $writer->save($file);
3247
        DocumentManager::file_send_for_download($file, true, $filename);
3248
3249
        return null;
3250
    }
3251
3252
    /**
3253
     * Add a line to the csv file
3254
     *
3255
     * @param	array	Possible answers
3256
     * @param	array	User's answers
3257
     * @param 	mixed	User ID or user details as string - Used as a string in the result string
3258
     * @param	boolean	Whether to display user fields or not
3259
     * @return	string	One line of the csv file
3260
     */
3261
    public static function export_complete_report_row_xls(
3262
        $survey_data,
3263
        $possible_options,
3264
        $answers_of_user,
3265
        $user,
3266
        $display_extra_user_fields = false
3267
    ) {
3268
        $return = array();
3269
        if ($survey_data['anonymous'] == 0) {
3270
            if (intval($user) !== 0) {
3271
                $sql = 'SELECT firstname, lastname
3272
                        FROM '.Database::get_main_table(TABLE_MAIN_USER).'
3273
                        WHERE user_id='.intval($user);
3274
                $rs = Database::query($sql);
3275
                if($row = Database::fetch_array($rs)) {
3276
                    $user_displayed = api_get_person_name($row['firstname'], $row['lastname']);
3277
                } else {
3278
                    $user_displayed = '-';
3279
                }
3280
                $return[] = $user_displayed;
3281
            } else {
3282
                $return[] = $user;
3283
            }
3284
        } else {
3285
            $return[] = '-'; // The user column
3286
        }
3287
3288
        if ($display_extra_user_fields) {
3289
            //show user fields data, if any, for this user
3290
            $user_fields_values = UserManager::get_extra_user_data(intval($user),false,false, false, true);
3291
            foreach($user_fields_values as $value) {
3292
                $return[] = api_html_entity_decode(strip_tags($value), ENT_QUOTES);
3293
            }
3294
        }
3295
3296
        if (is_array($possible_options)) {
3297
            foreach ($possible_options as $question_id => & $possible_option) {
3298
                if (is_array($possible_option) && count($possible_option) > 0) {
3299
                    foreach ($possible_option as $option_id => & $value) {
3300
                        $my_answers_of_user = isset($answers_of_user[$question_id]) ? $answers_of_user[$question_id] : [];
3301
                        $key = array_keys($my_answers_of_user);
3302
                        if (isset($key[0]) && substr($key[0], 0, 4) == 'open') {
3303
                            $return[] = api_html_entity_decode(strip_tags($answers_of_user[$question_id][$key[0]]['option_id']), ENT_QUOTES);
3304
                        } elseif (!empty($answers_of_user[$question_id][$option_id])) {
3305
                            //$return .= 'v';
3306
                            if ($answers_of_user[$question_id][$option_id]['value'] != 0) {
3307
                                $return[] = $answers_of_user[$question_id][$option_id]['value'];
3308
                            } else {
3309
                                $return[] = 'v';
3310
                            }
3311
                        } else {
3312
                            $return[] = '';
3313
                        }
3314
                    }
3315
                }
3316
            }
3317
        }
3318
3319
        return $return;
3320
    }
3321
3322
    /**
3323
     * This function displays the comparative report which allows you to compare two questions
3324
     * A comparative report creates a table where one question is on the x axis and a second question is on the y axis.
3325
     * In the intersection is the number of people who have answerd positive on both options.
3326
     *
3327
     * @return	string	HTML code
3328
     *
3329
     * @author Patrick Cool <[email protected]>, Ghent University
3330
     * @version February 2007
3331
     */
3332
    public static function display_comparative_report()
3333
    {
3334
        // Allowed question types for comparative report
3335
        $allowed_question_types = array(
3336
            'yesno',
3337
            'multiplechoice',
3338
            'multipleresponse',
3339
            'dropdown',
3340
            'percentage',
3341
            'score',
3342
        );
3343
3344
        // Getting all the questions
3345
        $questions = SurveyManager::get_questions($_GET['survey_id']);
3346
3347
        // Actions bar
3348
        echo '<div class="actions">';
3349
        echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.intval($_GET['survey_id']).'">'.
3350
                Display::return_icon('back.png', get_lang('BackTo').' '.get_lang('ReportingOverview'),'',ICON_SIZE_MEDIUM).'</a>';
3351
        echo '</div>';
3352
3353
        // Displaying an information message that only the questions with predefined answers can be used in a comparative report
3354
        Display::display_normal_message(get_lang('OnlyQuestionsWithPredefinedAnswers'), false);
3355
3356
        // The form for selecting the axis of the table
3357
        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']).'">';
3358
        // Survey_id
3359
        echo '<input type="hidden" name="action" value="'.Security::remove_XSS($_GET['action']).'"/>';
3360
        echo '<input type="hidden" name="survey_id" value="'.Security::remove_XSS($_GET['survey_id']).'"/>';
3361
        // X axis
3362
        echo get_lang('SelectXAxis').': ';
3363
        echo '<select name="xaxis">';
3364
        echo '<option value="">---</option>';
3365 View Code Duplication
        foreach ($questions as $key => & $question) {
3366
            if (is_array($allowed_question_types)) {
3367
                if (in_array($question['type'], $allowed_question_types)) {
3368
                    echo '<option value="'.$question['question_id'].'"';
3369
                    if (isset($_GET['xaxis']) && $_GET['xaxis'] == $question['question_id']) {
3370
                        echo ' selected="selected"';
3371
                    }
3372
                    echo '">'.api_substr(strip_tags($question['question']), 0, 50).'</option>';
3373
                }
3374
            }
3375
3376
        }
3377
        echo '</select><br /><br />';
3378
        // Y axis
3379
        echo get_lang('SelectYAxis').': ';
3380
        echo '<select name="yaxis">';
3381
        echo '<option value="">---</option>';
3382 View Code Duplication
        foreach ($questions as $key => &$question) {
3383
            if (in_array($question['type'], $allowed_question_types)) {
3384
                echo '<option value="'.$question['question_id'].'"';
3385
                if (isset($_GET['yaxis']) && $_GET['yaxis'] == $question['question_id']) {
3386
                    echo ' selected="selected"';
3387
                }
3388
                echo '">'.api_substr(strip_tags($question['question']), 0, 50).'</option>';
3389
            }
3390
        }
3391
        echo '</select><br /><br />';
3392
        echo '<button class="save" type="submit" name="Submit" value="Submit">'.get_lang('CompareQuestions').'</button>';
3393
        echo '</form>';
3394
3395
        // Getting all the information of the x axis
3396 View Code Duplication
        if (isset($_GET['xaxis']) && is_numeric($_GET['xaxis'])) {
3397
            $question_x = SurveyManager::get_question($_GET['xaxis']);
3398
        }
3399
3400
        // Getting all the information of the y axis
3401 View Code Duplication
        if (isset($_GET['yaxis']) && is_numeric($_GET['yaxis'])) {
3402
            $question_y = SurveyManager::get_question($_GET['yaxis']);
3403
        }
3404
3405
        if (isset($_GET['xaxis']) && is_numeric($_GET['xaxis']) && isset($_GET['yaxis']) && is_numeric($_GET['yaxis'])) {
3406
            // Getting the answers of the two questions
3407
            $answers_x = SurveyUtil::get_answers_of_question_by_user($_GET['survey_id'], $_GET['xaxis']);
3408
            $answers_y = SurveyUtil::get_answers_of_question_by_user($_GET['survey_id'], $_GET['yaxis']);
3409
3410
            // Displaying the table
3411
            $tableHtml = '<table border="1" class="data_table">';
3412
3413
            $xOptions = array();
3414
            // The header
3415
            $tableHtml .=  '	<tr>';
3416
            for ($ii = 0; $ii <= count($question_x['answers']); $ii++) {
3417
                if ($ii == 0) {
3418
                    $tableHtml .=  '		<th>&nbsp;</th>';
3419
                } else {
3420
                    if ($question_x['type'] == 'score') {
3421
                        for ($x = 1; $x <= $question_x['maximum_score']; $x++) {
3422
                            $tableHtml .= '		<th>'.$question_x['answers'][($ii-1)].'<br />'.$x.'</th>';
3423
                        }
3424
                        $x = '';
3425
                    } else {
3426
                        $tableHtml .= '		<th>'.$question_x['answers'][($ii-1)].'</th>';
3427
                    }
3428
                    $optionText = strip_tags($question_x['answers'][$ii-1]);
3429
                    $optionText = html_entity_decode($optionText);
3430
                    array_push($xOptions, trim($optionText));
3431
                }
3432
            }
3433
            $tableHtml .=  '	</tr>';
3434
            $chartData = array();
3435
3436
            // The main part
3437
            for ($ij = 0; $ij < count($question_y['answers']); $ij++) {
3438
                $currentYQuestion = strip_tags($question_y['answers'][$ij]);
3439
                $currentYQuestion = html_entity_decode($currentYQuestion);
3440
                // The Y axis is a scoring question type so we have more rows than the options (actually options * maximum score)
3441
                if ($question_y['type'] == 'score') {
3442
                    for ($y = 1; $y <= $question_y['maximum_score']; $y++) {
3443
                        $tableHtml .=  '	<tr>';
3444
                        for ($ii = 0; $ii <= count($question_x['answers']); $ii++) {
3445
                            if ($question_x['type'] == 'score') {
3446 View Code Duplication
                                for ($x = 1; $x <= $question_x['maximum_score']; $x++) {
3447
                                    if ($ii == 0) {
3448
                                        $tableHtml .=  ' <th>'.$question_y['answers'][($ij)].' '.$y.'</th>';
3449
                                        break;
3450
                                    } else {
3451
                                        $tableHtml .=  ' <td align="center">';
3452
                                        $votes = SurveyUtil::comparative_check(
3453
                                            $answers_x,
3454
                                            $answers_y,
3455
                                            $question_x['answersid'][($ii - 1)],
3456
                                            $question_y['answersid'][($ij)],
3457
                                            $x,
3458
                                            $y
3459
                                        );
3460
                                        $tableHtml .=  $votes;
3461
                                        array_push(
3462
                                            $chartData,
3463
                                            array(
3464
                                                'serie' => array($currentYQuestion, $xOptions[$ii-1]),
3465
                                                'option' => $x,
3466
                                                'votes' => $votes
3467
                                            )
3468
                                        );
3469
                                        $tableHtml .=  '</td>';
3470
                                    }
3471
                                }
3472
                            } else {
3473
                                if ($ii == 0) {
3474
                                    $tableHtml .=  '<th>'.$question_y['answers'][$ij].' '.$y.'</th>';
3475
                                } else {
3476
                                    $tableHtml .=  '<td align="center">';
3477
                                    $votes = SurveyUtil::comparative_check(
3478
                                        $answers_x,
3479
                                        $answers_y,
3480
                                        $question_x['answersid'][($ii - 1)],
3481
                                        $question_y['answersid'][($ij)],
3482
                                        0,
3483
                                        $y
3484
                                    );
3485
                                    $tableHtml .= $votes;
3486
                                    array_push(
3487
                                        $chartData,
3488
                                        array(
3489
                                            'serie' => array($currentYQuestion, $xOptions[$ii-1]),
3490
                                            'option' => $y,
3491
                                            'votes' => $votes
3492
                                        )
3493
                                    );
3494
                                    $tableHtml .=  '</td>';
3495
                                }
3496
                            }
3497
                        }
3498
                        $tableHtml .=  '	</tr>';
3499
                    }
3500
                }
3501
                // The Y axis is NOT a score question type so the number of rows = the number of options
3502
                else {
3503
                    $tableHtml .=  '	<tr>';
3504
                    for ($ii = 0; $ii <= count($question_x['answers']); $ii++) {
3505
                        if ($question_x['type'] == 'score') {
3506 View Code Duplication
                            for ($x = 1; $x <= $question_x['maximum_score']; $x++) {
3507
                                if ($ii == 0) {
3508
                                    $tableHtml .=  '		<th>'.$question_y['answers'][$ij].'</th>';
3509
                                    break;
3510
                                } else {
3511
                                    $tableHtml .=  '		<td align="center">';
3512
                                    $votes =  SurveyUtil::comparative_check($answers_x, $answers_y, $question_x['answersid'][($ii-1)], $question_y['answersid'][($ij)], $x, 0);
3513
                                    $tableHtml .= $votes;
3514
                                    array_push(
3515
                                        $chartData,
3516
                                        array(
3517
                                            'serie' => array($currentYQuestion, $xOptions[$ii-1]),
3518
                                            'option' => $x,
3519
                                            'votes' => $votes
3520
                                        )
3521
                                    );
3522
                                    $tableHtml .=  '</td>';
3523
                                }
3524
                            }
3525
                        } else {
3526
                            if ($ii == 0) {
3527
                                $tableHtml .=  '		<th>'.$question_y['answers'][($ij)].'</th>';
3528
                            } else {
3529
                                $tableHtml .=  '		<td align="center">';
3530
                                $votes = SurveyUtil::comparative_check($answers_x, $answers_y, $question_x['answersid'][($ii-1)], $question_y['answersid'][($ij)]);
3531
                                $tableHtml .= $votes;
3532
                                array_push(
3533
                                    $chartData,
3534
                                    array(
3535
                                        'serie' => $xOptions[$ii-1],
3536
                                        'option' => $currentYQuestion,
3537
                                        'votes' => $votes
3538
                                    )
3539
                                );
3540
                                $tableHtml .=  '</td>';
3541
                            }
3542
                        }
3543
                    }
3544
                    $tableHtml .=  '	</tr>';
3545
                }
3546
            }
3547
            $tableHtml .=  '</table>';
3548
            echo '<div id="chartContainer" class="col-md-12">';
3549
            echo self::drawChart($chartData, true);
3550
            echo '</div>';
3551
            echo $tableHtml;
3552
        }
3553
    }
3554
3555
    /**
3556
     * Get all the answers of a question grouped by user
3557
     *
3558
     * @param	integer	Survey ID
3559
     * @param	integer	Question ID
3560
     * @return 	Array	Array containing all answers of all users, grouped by user
3561
     *
3562
     * @author Patrick Cool <[email protected]>, Ghent University
3563
     * @version February 2007 - Updated March 2008
3564
     */
3565
    public static function get_answers_of_question_by_user($survey_id, $question_id)
3566
    {
3567
        $course_id = api_get_course_int_id();
3568
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
3569
3570
        $sql = "SELECT * FROM $table_survey_answer
3571
                WHERE c_id = $course_id AND survey_id='".intval($survey_id)."'
3572
                AND question_id='".intval($question_id)."'
3573
                ORDER BY USER ASC";
3574
        $result = Database::query($sql);
3575
        while ($row = Database::fetch_array($result)) {
3576
            if ($row['value'] == 0) {
3577
                $return[$row['user']][] = $row['option_id'];
3578
            } else {
3579
                $return[$row['user']][] = $row['option_id'].'*'.$row['value'];
3580
            }
3581
        }
3582
        return $return;
3583
    }
3584
3585
    /**
3586
     * Count the number of users who answer positively on both options
3587
     *
3588
     * @param	array	All answers of the x axis
3589
     * @param	array	All answers of the y axis
3590
     * @param	integer x axis value (= the option_id of the first question)
3591
     * @param	integer y axis value (= the option_id of the second question)
3592
     * @return	integer Number of users who have answered positively to both options
3593
     *
3594
     * @author Patrick Cool <[email protected]>, Ghent University
3595
     * @version February 2007
3596
     */
3597
    public static function comparative_check($answers_x, $answers_y, $option_x, $option_y, $value_x = 0, $value_y = 0)
3598
    {
3599
        if ($value_x == 0) {
3600
            $check_x = $option_x;
3601
        } else {
3602
            $check_x = $option_x.'*'.$value_x;
3603
        }
3604
        if ($value_y == 0) {
3605
            $check_y = $option_y;
3606
        } else {
3607
            $check_y = $option_y.'*'.$value_y;
3608
        }
3609
3610
        $counter = 0;
3611
        if (is_array($answers_x)) {
3612
            foreach ($answers_x as $user => & $answers) {
3613
                // Check if the user has given $option_x as answer
3614
                if (in_array($check_x, $answers)) {
3615
                    // Check if the user has given $option_y as an answer
3616
                    if (!is_null($answers_y[$user]) && in_array($check_y, $answers_y[$user])) {
3617
                        $counter++;
3618
                    }
3619
                }
3620
            }
3621
        }
3622
3623
        return $counter;
3624
    }
3625
3626
    /**
3627
     * Get all the information about the invitations of a certain survey
3628
     *
3629
     * @return	array	Lines of invitation [user, code, date, empty element]
3630
     *
3631
     * @author Patrick Cool <[email protected]>, Ghent University
3632
     * @version January 2007
3633
     *
3634
     * @todo use survey_id parameter instead of $_GET
3635
     */
3636
    public static function get_survey_invitations_data()
3637
    {
3638
        $course_id = api_get_course_int_id();
3639
        // Database table definition
3640
        $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
3641
        $table_user = Database :: get_main_table(TABLE_MAIN_USER);
3642
3643
        $sql = "SELECT
3644
					survey_invitation.user as col1,
3645
					survey_invitation.invitation_code as col2,
3646
					survey_invitation.invitation_date as col3,
3647
					'' as col4
3648
					FROM $table_survey_invitation survey_invitation
3649
                LEFT JOIN $table_user user
3650
                ON survey_invitation.user = user.user_id
3651
                WHERE
3652
                    survey_invitation.c_id = $course_id AND
3653
                    survey_invitation.survey_id = '".intval($_GET['survey_id'])."' AND
3654
                    session_id='".api_get_session_id()."'  ";
3655
        $res = Database::query($sql);
3656
        while ($row = Database::fetch_array($res)) {
3657
            $survey_invitation_data[] = $row;
3658
        }
3659
3660
        return $survey_invitation_data;
3661
    }
3662
3663
    /**
3664
     * Get the total number of survey invitations for a given survey (through $_GET['survey_id'])
3665
     *
3666
     * @return	integer	Total number of survey invitations
3667
     *
3668
     * @todo use survey_id parameter instead of $_GET
3669
     *
3670
     * @author Patrick Cool <[email protected]>, Ghent University
3671
     * @version January 2007
3672
     */
3673 View Code Duplication
    public static function get_number_of_survey_invitations()
3674
    {
3675
        $course_id = api_get_course_int_id();
3676
3677
        // Database table definition
3678
        $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
3679
3680
        $sql = "SELECT count(user) AS total
3681
		        FROM $table_survey_invitation
3682
		        WHERE
3683
                    c_id = $course_id AND
3684
                    survey_id='".intval($_GET['survey_id'])."' AND
3685
                    session_id='".api_get_session_id()."' ";
3686
        $res = Database::query($sql);
3687
        $row = Database::fetch_array($res,'ASSOC');
3688
3689
        return $row['total'];
3690
    }
3691
3692
    /**
3693
     * Save the invitation mail
3694
     *
3695
     * @param string 	Text of the e-mail
3696
     * @param integer	Whether the mail contents are for invite mail (0, default) or reminder mail (1)
3697
     *
3698
     * @author Patrick Cool <[email protected]>, Ghent University
3699
     * @version January 2007
3700
     */
3701
    static function save_invite_mail($mailtext, $mail_subject, $reminder = 0)
3702
    {
3703
        $course_id = api_get_course_int_id();
3704
        // Database table definition
3705
        $table_survey = Database :: get_course_table(TABLE_SURVEY);
3706
3707
        // Reminder or not
3708
        if ($reminder == 0) {
3709
            $mail_field = 'invite_mail';
3710
        } else {
3711
            $mail_field = 'reminder_mail';
3712
        }
3713
3714
        $sql = "UPDATE $table_survey
3715
		        SET
3716
		        mail_subject='".Database::escape_string($mail_subject)."',
3717
		        $mail_field = '".Database::escape_string($mailtext)."'
3718
		        WHERE c_id = $course_id AND survey_id = '".intval($_GET['survey_id'])."'";
3719
        Database::query($sql);
3720
    }
3721
3722
    /**
3723
     * This function saves all the invitations of course users and additional users in the database
3724
     * and sends the invitations by email
3725
     *
3726
     * @param	array	Users array can be both a list of course uids AND a list of additional emailaddresses
3727
     * @param 	string	Title of the invitation, used as the title of the mail
3728
     * @param 	string	Text of the invitation, used as the text of the mail.
3729
     * 				 The text has to contain a **link** string or this will automatically be added to the end
3730
     *
3731
     * @author Patrick Cool <[email protected]>, Ghent University
3732
     * @author Julio Montoya - Adding auto-generated link support
3733
     * @version January 2007
3734
     *
3735
     */
3736
    public static function saveInvitations(
3737
        $users_array,
3738
        $invitation_title,
3739
        $invitation_text,
3740
        $reminder = 0,
3741
        $sendmail = 0,
3742
        $remindUnAnswered = 0
3743
    ) {
3744
        if (!is_array($users_array)) {
3745
            // Should not happen
3746
3747
            return 0;
3748
        }
3749
3750
        // Getting the survey information
3751
        $survey_data = SurveyManager::get_survey($_GET['survey_id']);
3752
        $survey_invitations = SurveyUtil::get_invitations($survey_data['survey_code']);
3753
        $already_invited = SurveyUtil::get_invited_users($survey_data['code']);
3754
3755
        // Remind unanswered is a special version of remind all reminder
3756
        $exclude_users = array();
3757
        if ($remindUnAnswered == 1) { // Remind only unanswered users
3758
            $reminder = 1;
3759
            $exclude_users = SurveyManager::get_people_who_filled_survey($_GET['survey_id']);
3760
        }
3761
3762
        $counter = 0;  // Nr of invitations "sent" (if sendmail option)
3763
        $course_id = api_get_course_int_id();
3764
        $session_id = api_get_session_id();
3765
3766
        $result = CourseManager::separateUsersGroups($users_array);
3767
3768
        $groupList = $result['groups'];
3769
        $users_array = $result['users'];
3770
3771
        foreach ($groupList as $groupId) {
3772
            $userGroupList = GroupManager::getStudents($groupId);
3773
            $userGroupIdList = array_column($userGroupList, 'user_id');
3774
            $users_array = array_merge($users_array, $userGroupIdList);
3775
3776
            $params = array(
3777
                'c_id' => $course_id,
3778
                'session_id' => $session_id,
3779
                'group_id' => $groupId,
3780
                'survey_code' => $survey_data['code']
3781
            );
3782
3783
            $invitationExists = self::invitationExists(
3784
                $course_id,
3785
                $session_id,
3786
                $groupId,
3787
                $survey_data['code']
3788
            );
3789
            if (empty($invitationExists)) {
3790
                self::save_invitation($params);
3791
            }
3792
        }
3793
3794
        $users_array = array_unique($users_array);
3795
3796
        foreach ($users_array as $key => $value) {
3797
            if (!isset($value) || $value == '') {
3798
                continue;
3799
            }
3800
3801
            // Skip user if reminding only unanswered people
3802
            if (in_array($value, $exclude_users)) {
3803
                continue;
3804
            }
3805
3806
            // Get the unique invitation code if we already have it
3807
            if ($reminder == 1 && array_key_exists($value, $survey_invitations)) {
3808
                $invitation_code = $survey_invitations[$value]['invitation_code'];
3809
            } else {
3810
                $invitation_code = md5($value.microtime());
3811
            }
3812
            $new_user = false; // User not already invited
3813
            // Store the invitation if user_id not in $already_invited['course_users'] OR email is not in $already_invited['additional_users']
3814
            $addit_users_array = isset($already_invited['additional_users']) && !empty($already_invited['additional_users']) ? explode(';', $already_invited['additional_users']) : array();
3815
3816
            $my_alredy_invited = $already_invited['course_users'] == null ? array() : $already_invited['course_users'];
3817
            if ((is_numeric($value) && !in_array($value, $my_alredy_invited)) ||
3818
                (!is_numeric($value) && !in_array($value, $addit_users_array))
3819
            ) {
3820
                $new_user = true;
3821
                if (!array_key_exists($value, $survey_invitations)) {
3822
                    $params = array(
3823
                        'c_id' => $course_id,
3824
                        'session_id' => $session_id,
3825
                        'user' => $value,
3826
                        'survey_code' => $survey_data['code'],
3827
                        'invitation_code' => $invitation_code,
3828
                        'invitation_date' => api_get_utc_datetime()
3829
                    );
3830
                    self::save_invitation($params);
3831
                }
3832
            }
3833
3834
            // Send the email if checkboxed
3835
            if (($new_user || $reminder == 1) && $sendmail != 0) {
3836
                // Make a change for absolute url
3837
                if (isset($invitation_text)) {
3838
                    $invitation_text = api_html_entity_decode($invitation_text, ENT_QUOTES);
3839
                    $invitation_text = str_replace('src="../../', 'src="'.api_get_path(WEB_PATH), $invitation_text);
3840
                    $invitation_text = trim(stripslashes($invitation_text));
3841
                }
3842
                SurveyUtil::send_invitation_mail($value, $invitation_code, $invitation_title, $invitation_text);
3843
                $counter++;
3844
            }
3845
        }
3846
3847
        return $counter; // Number of invitations sent
3848
    }
3849
3850
    /**
3851
     * @param $params
3852
     * @return bool|int
3853
     */
3854
    public static function save_invitation($params)
3855
    {
3856
        // Database table to store the invitations data
3857
        $table = Database::get_course_table(TABLE_SURVEY_INVITATION);
3858
        if (!empty($params['c_id']) &&
3859
            (!empty($params['user']) || !empty($params['group_id'])) &&
3860
            !empty($params['survey_code'])
3861
        ) {
3862
            $insertId = Database::insert($table, $params);
3863
            if ($insertId) {
3864
3865
                $sql = "UPDATE $table SET survey_invitation_id = $insertId
3866
                        WHERE iid = $insertId";
3867
                Database::query($sql);
3868
            }
3869
            return $insertId;
3870
        }
3871
        return false;
3872
    }
3873
3874
    /**
3875
     * @param int $courseId
3876
     * @param int $sessionId
3877
     * @param int $groupId
3878
     * @param string $surveyCode
3879
     * @return int
3880
     */
3881
    public static function invitationExists($courseId, $sessionId, $groupId, $surveyCode)
3882
    {
3883
        $table = Database::get_course_table(TABLE_SURVEY_INVITATION);
3884
        $courseId = intval($courseId);
3885
        $sessionId = intval($sessionId);
3886
        $groupId = intval($groupId);
3887
        $surveyCode = Database::escape_string($surveyCode);
3888
3889
        $sql = "SELECT survey_invitation_id FROM $table
3890
                WHERE
3891
                    c_id = $courseId AND
3892
                    session_id = $sessionId AND
3893
                    group_id = $groupId AND
3894
                    survey_code = '$surveyCode'
3895
                ";
3896
        $result = Database::query($sql);
3897
3898
        return Database::num_rows($result);
3899
    }
3900
3901
    /**
3902
     * Send the invitation by mail.
3903
     *
3904
     * @param int invitedUser - the userId (course user) or emailaddress of additional user
3905
     * $param string $invitation_code - the unique invitation code for the URL
3906
     * @return	void
3907
     */
3908
    public static function send_invitation_mail($invitedUser, $invitation_code, $invitation_title, $invitation_text)
3909
    {
3910
        $_user = api_get_user_info();
3911
        $_course = api_get_course_info();
3912
3913
        // Replacing the **link** part with a valid link for the user
3914
        $survey_link = api_get_path(WEB_CODE_PATH).'survey/fillsurvey.php?course='.$_course['code'].'&invitationcode='.$invitation_code;
3915
        $text_link = '<a href="'.$survey_link.'">'.get_lang('ClickHereToAnswerTheSurvey')."</a><br />\r\n<br />\r\n".get_lang('OrCopyPasteTheFollowingUrl')." <br />\r\n ".$survey_link;
3916
3917
        $replace_count = 0;
3918
        $full_invitation_text = api_str_ireplace('**link**', $text_link ,$invitation_text, $replace_count);
3919
        if ($replace_count < 1) {
3920
            $full_invitation_text = $full_invitation_text."<br />\r\n<br />\r\n".$text_link;
3921
        }
3922
3923
        // Sending the mail
3924
        $sender_name  = api_get_person_name($_user['firstName'], $_user['lastName'], null, PERSON_NAME_EMAIL_ADDRESS);
3925
        $sender_email = $_user['mail'];
3926
        $sender_user_id = api_get_user_id();
3927
3928
        $replyto = array();
3929
        if (api_get_setting('survey_email_sender_noreply') == 'noreply') {
3930
            $noreply = api_get_setting('noreply_email_address');
3931
            if (!empty($noreply)) {
3932
                $replyto['Reply-to'] = $noreply;
3933
                $sender_name = $noreply;
3934
                $sender_email = $noreply;
3935
                $sender_user_id = null;
3936
            }
3937
        }
3938
3939
        // Optionally: finding the e-mail of the course user
3940
        if (is_numeric($invitedUser)) {
3941
            $table_user = Database :: get_main_table(TABLE_MAIN_USER);
3942
            $sql = "SELECT firstname, lastname, email FROM $table_user
3943
                    WHERE user_id='".Database::escape_string($invitedUser)."'";
3944
            $result = Database::query($sql);
3945
            $row = Database::fetch_array($result);
3946
            $recipient_email = $row['email'];
3947
            $recipient_name = api_get_person_name($row['firstname'], $row['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);
3948
3949
            MessageManager::send_message(
3950
                $invitedUser,
3951
                $invitation_title,
3952
                $full_invitation_text,
3953
                [],
3954
                [],
3955
                null,
3956
                null,
3957
                null,
3958
                null,
3959
                $sender_user_id
3960
            );
3961
3962
        } else {
3963
            /** @todo check if the address is a valid email	 */
3964
            $recipient_email = $invitedUser;
3965
            @api_mail_html(
3966
                $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...
3967
                $recipient_email,
3968
                $invitation_title,
3969
                $full_invitation_text,
3970
                $sender_name,
3971
                $sender_email,
3972
                $replyto
3973
            );
3974
        }
3975
    }
3976
3977
    /**
3978
     * This function recalculates the number of users who have been invited and updates the survey table with this value.
3979
     *
3980
     * @param	string	Survey code
3981
     * @return	void
3982
     * @author Patrick Cool <[email protected]>, Ghent University
3983
     * @version January 2007
3984
     */
3985
    static function update_count_invited($survey_code)
3986
    {
3987
        $course_id = api_get_course_int_id();
3988
3989
        // Database table definition
3990
        $table_survey_invitation 	= Database :: get_course_table(TABLE_SURVEY_INVITATION);
3991
        $table_survey 				= Database :: get_course_table(TABLE_SURVEY);
3992
3993
        // Counting the number of people that are invited
3994
        $sql = "SELECT count(user) as total
3995
                FROM $table_survey_invitation
3996
		        WHERE
3997
		            c_id = $course_id AND
3998
		            survey_code = '".Database::escape_string($survey_code)."' AND
3999
		            user <> ''
4000
                ";
4001
        $result = Database::query($sql);
4002
        $row = Database::fetch_array($result);
4003
        $total_invited = $row['total'];
4004
4005
        // Updating the field in the survey table
4006
        $sql = "UPDATE $table_survey
4007
		        SET invited = '".Database::escape_string($total_invited)."'
4008
		        WHERE
4009
		            c_id = $course_id AND
4010
		            code = '".Database::escape_string($survey_code)."'
4011
                ";
4012
        Database::query($sql);
4013
    }
4014
4015
    /**
4016
     * This function gets all the invited users for a given survey code.
4017
     *
4018
     * @param	string	Survey code
4019
     * @param	string	optional - course database
4020
     * @return 	array	Array containing the course users and additional users (non course users)
4021
     *
4022
     * @todo consider making $defaults['additional_users'] also an array
4023
     *
4024
     * @author Patrick Cool <[email protected]>, Ghent University
4025
     * @author Julio Montoya, adding c_id fixes - Dec 2012
4026
     * @version January 2007
4027
     */
4028
    public static function get_invited_users($survey_code, $course_code = '', $session_id = 0)
4029
    {
4030
        if (!empty($course_code)) {
4031
            $course_info = api_get_course_info($course_code);
4032
            $course_id = $course_info['real_id'];
4033
        } else {
4034
            $course_id = api_get_course_int_id();
4035
        }
4036
4037
        if (empty($session_id)) {
4038
            $session_id = api_get_session_id();
4039
        }
4040
4041
        $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
4042
        $table_user = Database :: get_main_table(TABLE_MAIN_USER);
4043
4044
        // Selecting all the invitations of this survey AND the additional emailaddresses (the left join)
4045
        $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname' : ' ORDER BY lastname, firstname';
4046
        $sql = "SELECT user, group_id
4047
				FROM $table_survey_invitation as table_invitation
4048
				WHERE
4049
				    table_invitation.c_id = $course_id AND
4050
                    survey_code='".Database::escape_string($survey_code)."' AND
4051
                    session_id = $session_id
4052
                ";
4053
4054
        $defaults = array();
4055
        $defaults['course_users'] = array();
4056
        $defaults['additional_users'] = array(); // Textarea
4057
        $defaults['users'] = array(); // user and groups
4058
4059
        $result = Database::query($sql);
4060
        while ($row = Database::fetch_array($result)) {
4061
            if (is_numeric($row['user'])) {
4062
                $defaults['course_users'][] = $row['user'];
4063
                $defaults['users'][] = 'USER:'.$row['user'];
4064
            } else {
4065
                if (!empty($row['user'])) {
4066
                    $defaults['additional_users'][] = $row['user'];
4067
                }
4068
            }
4069
4070 View Code Duplication
            if (isset($row['group_id']) && !empty($row['group_id'])) {
4071
                $defaults['users'][] = 'GROUP:'.$row['group_id'];
4072
            }
4073
        }
4074
4075 View Code Duplication
        if (!empty($defaults['course_users'])) {
4076
            $user_ids = implode("','", $defaults['course_users']);
4077
            $sql = "SELECT user_id FROM $table_user WHERE user_id IN ('$user_ids') $order_clause";
4078
            $result = Database::query($sql);
4079
            $fixed_users = array();
4080
            while ($row = Database::fetch_array($result)) {
4081
                $fixed_users[] = $row['user_id'];
4082
            }
4083
            $defaults['course_users'] = $fixed_users;
4084
        }
4085
4086
        if (!empty($defaults['additional_users'])) {
4087
            $defaults['additional_users'] = implode(';', $defaults['additional_users']);
4088
        }
4089
        return $defaults;
4090
    }
4091
4092
    /**
4093
     * Get all the invitations
4094
     *
4095
     * @param	string	Survey code
4096
     * @return	array	Database rows matching the survey code
4097
     *
4098
     * @author Patrick Cool <[email protected]>, Ghent University
4099
     * @version September 2007
4100
     */
4101
    static function get_invitations($survey_code)
4102
    {
4103
        $course_id = api_get_course_int_id();
4104
        // Database table definition
4105
        $table_survey_invitation 	= Database :: get_course_table(TABLE_SURVEY_INVITATION);
4106
4107
        $sql = "SELECT * FROM $table_survey_invitation
4108
		        WHERE
4109
		            c_id = $course_id AND
4110
		            survey_code = '".Database::escape_string($survey_code)."'";
4111
        $result = Database::query($sql);
4112
        $return = array();
4113
        while ($row = Database::fetch_array($result)) {
4114
            $return[$row['user']] = $row;
4115
        }
4116
        return $return;
4117
    }
4118
4119
    /**
4120
     * This function displays the form for searching a survey
4121
     *
4122
     * @return	void	(direct output)
4123
     *
4124
     * @author Patrick Cool <[email protected]>, Ghent University
4125
     * @version January 2007
4126
     *
4127
     * @todo use quickforms
4128
     * @todo consider moving this to surveymanager.inc.lib.php
4129
     */
4130
    static function display_survey_search_form()
4131
    {
4132
        echo '<form class="form-horizontal" method="get" action="'.api_get_path(WEB_CODE_PATH).'survey/survey_list.php?search=advanced">';
4133
        echo '<legend>'.get_lang('SearchASurvey').'</legend>';
4134
        echo '	<div class="control-group">
4135
					<label class="control-label">
4136
						'.get_lang('Title').'
4137
					</label>
4138
					<div class="controls">
4139
						<input type="text" id="search_title" name="keyword_title"/>
4140
					</div>
4141
				</div>';
4142
        echo '	<div class="control-group">
4143
					<label class="control-label">
4144
						'.get_lang('Code').'
4145
					</label>
4146
					<div class="controls">
4147
						<input type="text" name="keyword_code"/>
4148
					</div>
4149
				</div>';
4150
        echo '	<div class="control-group">
4151
					<label class="control-label">
4152
						'.get_lang('Language').'
4153
					</label>
4154
					<div class="controls">';
4155
        echo '			<select name="keyword_language"><option value="%">'.get_lang('All').'</option>';
4156
        $languages = api_get_languages();
4157
        foreach ($languages['name'] as $index => & $name) {
4158
            echo '<option value="'.$languages['folder'][$index].'">'.$name.'</option>';
4159
        }
4160
        echo '			</select>';
4161
        echo '		</div>
4162
				</div>';
4163
        echo '<input type="hidden" name="cidReq" value="'.api_get_course_id().'"/>';
4164
        echo '	<div class="control-group">
4165
					<div class="controls">
4166
						<button class="search" type="submit" name="do_search">'.get_lang('Search').'</button>
4167
					</div>
4168
				</div>';
4169
        echo '</form>';
4170
        echo '<div style="clear: both;margin-bottom: 10px;"></div>';
4171
    }
4172
4173
    /**
4174
     * Show table only visible by DRH users
4175
     */
4176
    public static function displaySurveyListForDrh()
4177
    {
4178
        $parameters = array();
4179
        $parameters['cidReq'] = api_get_course_id();
4180
4181
        // Create a sortable table with survey-data
4182
        $table = new SortableTable('surveys', 'get_number_of_surveys', 'get_survey_data_drh', 2);
4183
        $table->set_additional_parameters($parameters);
4184
        $table->set_header(0, '', false);
4185
        $table->set_header(1, get_lang('SurveyName'));
4186
        $table->set_header(2, get_lang('SurveyCode'));
4187
        $table->set_header(3, get_lang('NumberOfQuestions'));
4188
        $table->set_header(4, get_lang('Author'));
4189
        $table->set_header(5, get_lang('AvailableFrom'));
4190
        $table->set_header(6, get_lang('AvailableUntil'));
4191
        $table->set_header(7, get_lang('Invite'));
4192
        $table->set_header(8, get_lang('Anonymous'));
4193
        $table->set_header(9, get_lang('Modify'), false, 'width="150"');
4194
        $table->set_column_filter(8, 'anonymous_filter');
4195
        $table->set_column_filter(9, 'modify_filter_drh');
4196
        $table->display();
4197
    }
4198
4199
    /**
4200
     * This function displays the sortable table with all the surveys
4201
     *
4202
     * @return	void	(direct output)
4203
     *
4204
     * @author Patrick Cool <[email protected]>, Ghent University
4205
     * @version January 2007
4206
     */
4207
    static function display_survey_list()
4208
    {
4209
        $parameters = array();
4210
        $parameters['cidReq'] = api_get_course_id();
4211
        if (isset($_GET['do_search']) && $_GET['do_search']) {
4212
            $message = get_lang('DisplaySearchResults').'<br />';
4213
            $message .= '<a href="'.api_get_self().'?'.api_get_cidreq().'">'.get_lang('DisplayAll').'</a>';
4214
            Display::display_normal_message($message, false);
4215
        }
4216
4217
        // Create a sortable table with survey-data
4218
        $table = new SortableTable('surveys', 'get_number_of_surveys', 'get_survey_data', 2);
4219
        $table->set_additional_parameters($parameters);
4220
        $table->set_header(0, '', false);
4221
        $table->set_header(1, get_lang('SurveyName'));
4222
        $table->set_header(2, get_lang('SurveyCode'));
4223
        $table->set_header(3, get_lang('NumberOfQuestions'));
4224
        $table->set_header(4, get_lang('Author'));
4225
        //$table->set_header(5, get_lang('Language'));
4226
        //$table->set_header(6, get_lang('Shared'));
4227
        $table->set_header(5, get_lang('AvailableFrom'));
4228
        $table->set_header(6, get_lang('AvailableUntil'));
4229
        $table->set_header(7, get_lang('Invite'));
4230
        $table->set_header(8, get_lang('Anonymous'));
4231
        $table->set_header(9, get_lang('Modify'), false, 'width="150"');
4232
        $table->set_column_filter(8, 'anonymous_filter');
4233
        $table->set_column_filter(9, 'modify_filter');
4234
        $table->set_form_actions(array('delete' => get_lang('DeleteSurvey')));
4235
        $table->display();
4236
    }
4237
4238
    function display_survey_list_for_coach()
4239
    {
4240
        $parameters = array();
4241
        $parameters['cidReq']=api_get_course_id();
4242
        if (isset($_GET['do_search'])) {
4243
            $message = get_lang('DisplaySearchResults').'<br />';
4244
            $message .= '<a href="'.api_get_self().'?'.api_get_cidreq().'">'.get_lang('DisplayAll').'</a>';
4245
            Display::display_normal_message($message, false);
4246
        }
4247
4248
        // Create a sortable table with survey-data
4249
        $table = new SortableTable('surveys_coach', 'get_number_of_surveys_for_coach', 'get_survey_data_for_coach', 2);
4250
        $table->set_additional_parameters($parameters);
4251
        $table->set_header(0, '', false);
4252
        $table->set_header(1, get_lang('SurveyName'));
4253
        $table->set_header(2, get_lang('SurveyCode'));
4254
        $table->set_header(3, get_lang('NumberOfQuestions'));
4255
        $table->set_header(4, get_lang('Author'));
4256
        //$table->set_header(5, get_lang('Language'));
4257
        //$table->set_header(6, get_lang('Shared'));
4258
        $table->set_header(5, get_lang('AvailableFrom'));
4259
        $table->set_header(6, get_lang('AvailableUntil'));
4260
        $table->set_header(7, get_lang('Invite'));
4261
        $table->set_header(8, get_lang('Anonymous'));
4262
        $table->set_header(9, get_lang('Modify'), false, 'width="130"');
4263
        $table->set_column_filter(8, 'anonymous_filter');
4264
        $table->set_column_filter(9, 'modify_filter_for_coach');
4265
        $table->display();
4266
    }
4267
4268
    /**
4269
     * This function changes the modify column of the sortable table
4270
     *
4271
     * @param integer $survey_id the id of the survey
4272
     * @param bool $drh
4273
     * @return string html code that are the actions that can be performed on any survey
4274
     *
4275
     * @author Patrick Cool <[email protected]>, Ghent University
4276
     * @version January 2007
4277
     */
4278
    static function modify_filter($survey_id, $drh = false)
4279
    {
4280
        $survey_id = Security::remove_XSS($survey_id);
4281
        $return = '';
4282
4283
        if ($drh) {
4284
            return '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.
4285
            Display::return_icon('stats.png', get_lang('Reporting'),'',ICON_SIZE_SMALL).'</a>';
4286
        }
4287
4288
        // Coach can see that only if the survey is in his session
4289
        if (api_is_allowed_to_edit() ||
4290
            api_is_element_in_the_session(TOOL_SURVEY, $survey_id)
4291
        ) {
4292
            $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>';
4293
            if (SurveyManager::survey_generation_hash_available()) {
4294
                $return .=  Display::url(
4295
                    Display::return_icon('new_link.png', get_lang('GenerateSurveyAccessLink'),'',ICON_SIZE_SMALL),
4296
                    api_get_path(WEB_CODE_PATH).'survey/generate_link.php?survey_id='.$survey_id.'&'.api_get_cidreq()
4297
                );
4298
            }
4299
            $return .= Display::url(
4300
                Display::return_icon('copy.png', get_lang('DuplicateSurvey'), '', ICON_SIZE_SMALL),
4301
                'survey_list.php?action=copy_survey&survey_id='.$survey_id.'&'.api_get_cidreq()
4302
            );
4303
4304
            $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;">'.
4305
                Display::return_icon('clean.png', get_lang('EmptySurvey'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
4306
        }
4307
        $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/preview.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.
4308
            Display::return_icon('preview_view.png', get_lang('Preview'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
4309
        $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_invite.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.
4310
            Display::return_icon('mail_send.png', get_lang('Publish'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
4311
        $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.
4312
            Display::return_icon('stats.png', get_lang('Reporting'),'',ICON_SIZE_SMALL).'</a>';
4313
4314 View Code Duplication
        if (api_is_allowed_to_edit() ||
4315
            api_is_element_in_the_session(TOOL_SURVEY, $survey_id)
4316
        ) {
4317
            $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;">'.
4318
                Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
4319
        }
4320
4321
        return $return;
4322
    }
4323
4324
    static function modify_filter_for_coach($survey_id)
4325
    {
4326
        $survey_id = Security::remove_XSS($survey_id);
4327
        //$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>';
4328
        //$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>';
4329
        //$return .= '<a href="create_survey_in_another_language.php?id_survey='.$survey_id.'">'.Display::return_icon('copy.gif', get_lang('Copy')).'</a>';
4330
        //$return .= '<a href="survey.php?survey_id='.$survey_id.'">'.Display::return_icon('add.gif', get_lang('Add')).'</a>';
4331
        $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;';
4332
        $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;';
4333
        $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;';
4334
        //$return .= '<a href="reporting.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.Display::return_icon('statistics.gif', get_lang('Reporting')).'</a>';
4335
        return $return;
4336
    }
4337
4338
    /**
4339
     * Returns "yes" when given parameter is one, "no" for any other value
4340
     * @param	integer	Whether anonymous or not
4341
     * @return	string	"Yes" or "No" in the current language
4342
     */
4343
    static function anonymous_filter($anonymous)
4344
    {
4345
        if ($anonymous == 1) {
4346
            return get_lang('Yes');
4347
        } else {
4348
            return get_lang('No');
4349
        }
4350
    }
4351
4352
    /**
4353
     * This function handles the search restriction for the SQL statements
4354
     *
4355
     * @return	string	Part of a SQL statement or false on error
4356
     *
4357
     * @author Patrick Cool <[email protected]>, Ghent University
4358
     * @version January 2007
4359
     */
4360
    static function survey_search_restriction()
4361
    {
4362
        if (isset($_GET['do_search'])) {
4363
            if ($_GET['keyword_title'] != '') {
4364
                $search_term[] = 'title like "%" \''.Database::escape_string($_GET['keyword_title']).'\' "%"';
4365
            }
4366
            if ($_GET['keyword_code'] != '') {
4367
                $search_term[] = 'code =\''.Database::escape_string($_GET['keyword_code']).'\'';
4368
            }
4369
            if ($_GET['keyword_language'] != '%') {
4370
                $search_term[] = 'lang =\''.Database::escape_string($_GET['keyword_language']).'\'';
4371
            }
4372
            $my_search_term = ($search_term == null) ? array() : $search_term;
4373
            $search_restriction = implode(' AND ', $my_search_term);
4374
            return $search_restriction;
4375
        } else {
4376
            return false;
4377
        }
4378
    }
4379
4380
    /**
4381
     * This function calculates the total number of surveys
4382
     *
4383
     * @return	integer	Total number of surveys
4384
     *
4385
     * @author Patrick Cool <[email protected]>, Ghent University
4386
     * @version January 2007
4387
     */
4388
    static function get_number_of_surveys()
4389
    {
4390
        $table_survey = Database :: get_course_table(TABLE_SURVEY);
4391
        $course_id = api_get_course_int_id();
4392
4393
        $search_restriction = SurveyUtil::survey_search_restriction();
4394
        if ($search_restriction) {
4395
            $search_restriction = 'WHERE c_id = '.$course_id.' AND '.$search_restriction;
4396
        } else {
4397
            $search_restriction = "WHERE c_id = $course_id";
4398
        }
4399
        $sql = "SELECT count(survey_id) AS total_number_of_items
4400
		        FROM ".$table_survey.' '.$search_restriction;
4401
        $res = Database::query($sql);
4402
        $obj = Database::fetch_object($res);
4403
        return $obj->total_number_of_items;
4404
    }
4405
4406
    static function get_number_of_surveys_for_coach()
4407
    {
4408
        $survey_tree = new SurveyTree();
4409
        return count($survey_tree->get_last_children_from_branch($survey_tree->surveylist));
4410
    }
4411
4412
    /**
4413
     * This function gets all the survey data that is to be displayed in the sortable table
4414
     *
4415
     * @param int $from
4416
     * @param int $number_of_items
4417
     * @param int $column
4418
     * @param string $direction
4419
     * @param bool $isDrh
4420
     * @return unknown
4421
     *
4422
     * @author Patrick Cool <[email protected]>, Ghent University
4423
     * @author Julio Montoya <[email protected]>, Beeznest - Adding intvals
4424
     * @version January 2007
4425
     */
4426
    static function get_survey_data($from, $number_of_items, $column, $direction, $isDrh = false)
4427
    {
4428
        $table_survey = Database :: get_course_table(TABLE_SURVEY);
4429
        $table_user = Database :: get_main_table(TABLE_MAIN_USER);
4430
        $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
4431
        $_user = api_get_user_info();
4432
4433
        // Searching
4434
        $search_restriction = SurveyUtil::survey_search_restriction();
4435
        if ($search_restriction) {
4436
            $search_restriction = ' AND '.$search_restriction;
4437
        }
4438
        $from = intval($from);
4439
        $number_of_items = intval($number_of_items);
4440
        $column = intval($column);
4441
        if (!in_array(strtolower($direction), array('asc', 'desc'))) {
4442
            $direction = 'asc';
4443
        }
4444
4445
        // Condition for the session
4446
        $session_id = api_get_session_id();
4447
        $condition_session = api_get_session_condition($session_id);
4448
        $course_id = api_get_course_int_id();
4449
4450
        $sql = "SELECT
4451
					survey.survey_id AS col0,
4452
					survey.title AS col1,
4453
					survey.code AS col2,
4454
					count(survey_question.question_id) AS col3,
4455
					".(api_is_western_name_order() ? "CONCAT(user.firstname, ' ', user.lastname)" : "CONCAT(user.lastname, ' ', user.firstname)")."	AS col4,
4456
					survey.avail_from AS col5,
4457
					survey.avail_till AS col6,
4458
					survey.invited AS col7,
4459
					survey.anonymous AS col8,
4460
					survey.survey_id AS col9,
4461
					survey.session_id AS session_id,
4462
					survey.answered,
4463
					survey.invited
4464
				 FROM $table_survey survey
4465
                    LEFT JOIN $table_survey_question survey_question
4466
                    ON (survey.survey_id = survey_question.survey_id AND survey_question.c_id = $course_id)
4467
                    LEFT JOIN $table_user user
4468
                    ON (survey.author = user.user_id)
4469
				 WHERE survey.c_id = $course_id
4470
				 $search_restriction
4471
				 $condition_session ";
4472
        $sql .= " GROUP BY survey.survey_id";
4473
        $sql .= " ORDER BY col$column $direction ";
4474
        $sql .= " LIMIT $from,$number_of_items";
4475
4476
        $res = Database::query($sql);
4477
        $surveys = array();
4478
        $array = array();
4479
        while ($survey = Database::fetch_array($res)) {
4480
            $array[0] = $survey[0];
4481
            $array[1] = Display::url(
4482
                $survey[1],
4483
                api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.$survey[0].'&'.api_get_cidreq()
4484
            );
4485
4486
            // Validation when belonging to a session
4487
            $session_img = api_get_session_image($survey['session_id'], $_user['status']);
4488
            $array[2] = $survey[2] . $session_img;
4489
            $array[3] = $survey[3];
4490
            $array[4] = $survey[4];
4491
            $array[5] = $survey[5];
4492
            $array[6] = $survey[6];
4493
            $array[7] =
4494
                Display::url(
4495
                    $survey['answered'],
4496
                    api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?view=answered&survey_id='.$survey[0].'&'.api_get_cidreq()
4497
                ).' / '.
4498
                Display::url(
4499
                    $survey['invited'],
4500
                    api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?view=invited&survey_id='.$survey[0].'&'.api_get_cidreq()
4501
                );
4502
4503
            $array[8] = $survey[8];
4504
            $array[9] = $survey[9];
4505
4506
            if ($isDrh) {
4507
                $array[1] = $survey[1];
4508
                $array[7] = strip_tags($array[7]);
4509
            }
4510
4511
            $surveys[] = $array;
4512
        }
4513
        return $surveys;
4514
    }
4515
4516
    static function get_survey_data_for_coach($from, $number_of_items, $column, $direction)
4517
    {
4518
        $survey_tree = new SurveyTree();
4519
        $last_version_surveys = $survey_tree->get_last_children_from_branch($survey_tree->surveylist);
4520
        $list = array();
4521
        foreach ($last_version_surveys as & $survey) {
4522
            $list[]=$survey['id'];
4523
        }
4524
        if (count($list) > 0) {
4525
            $list_condition = " AND survey.survey_id IN (".implode(',',$list).") ";
4526
        } else {
4527
            $list_condition = '';
4528
        }
4529
4530
        $from = intval($from);
4531
        $number_of_items = intval($number_of_items);
4532
        $column = intval($column);
4533
        if (!in_array(strtolower($direction), array('asc', 'desc'))) {
4534
            $direction = 'asc';
4535
        }
4536
4537
        $table_survey 			= Database :: get_course_table(TABLE_SURVEY);
4538
        $table_survey_question 	= Database :: get_course_table(TABLE_SURVEY_QUESTION);
4539
        $table_user 			= Database :: get_main_table(TABLE_MAIN_USER);
4540
4541
        $course_id = api_get_course_int_id();
4542
4543
        //IF(is_shared<>0,'V','-')	 					AS col6,
4544
        $sql = "SELECT ".
4545
            "survey.survey_id							AS col0, ".
4546
            "survey.title	                            AS col1, ".
4547
            "survey.code									AS col2, ".
4548
            "count(survey_question.question_id)			AS col3, ".
4549
            (api_is_western_name_order() ? "CONCAT(user.firstname, ' ', user.lastname)" : "CONCAT(user.lastname, ' ', user.firstname)")."	AS col4, ".
4550
            "survey.avail_from							AS col5, ".
4551
            "survey.avail_till							AS col6, ".
4552
            "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, ".
4553
            "survey.anonymous							AS col8, ".
4554
            "survey.survey_id							AS col9  ".
4555
            "FROM $table_survey survey ".
4556
            "LEFT JOIN $table_survey_question survey_question
4557
             ON (survey.survey_id = survey_question.survey_id AND survey.c_id = survey_question.c_id) ".
4558
            ", $table_user user
4559
               WHERE survey.author = user.user_id AND survey.c_id = $course_id $list_condition ";
4560
        $sql .= " GROUP BY survey.survey_id";
4561
        $sql .= " ORDER BY col$column $direction ";
4562
        $sql .= " LIMIT $from,$number_of_items";
4563
4564
        $res = Database::query($sql);
4565
        $surveys = array();
4566
        while ($survey = Database::fetch_array($res)) {
4567
            $surveys[] = $survey;
4568
        }
4569
        return $surveys;
4570
    }
4571
4572
    /**
4573
     * Display all the active surveys for the given course user
4574
     *
4575
     * @param int $user_id
4576
     *
4577
     * @author Patrick Cool <[email protected]>, Ghent University
4578
     * @version April 2007
4579
     */
4580
    public static function getSurveyList($user_id)
4581
    {
4582
        $_course = api_get_course_info();
4583
        $course_id = $_course['real_id'];
4584
        $user_id = intval($user_id);
4585
        $sessionId = api_get_session_id();
4586
4587
        // Database table definitions
4588
        $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
4589
        $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
4590
        $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
4591
        $table_survey = Database:: get_course_table(TABLE_SURVEY);
4592
4593
        $sql = 'SELECT question_id
4594
                FROM '.$table_survey_question."
4595
                WHERE c_id = $course_id";
4596
        $result = Database::query($sql);
4597
4598
        $all_question_id = array();
4599
        while ($row = Database::fetch_array($result, 'ASSOC')) {
4600
            $all_question_id[] = $row;
4601
        }
4602
4603
        $count = 0;
4604
        for ($i = 0; $i < count($all_question_id); $i++) {
4605
            $sql = 'SELECT COUNT(*) as count
4606
			        FROM '.$table_survey_answer.'
4607
					WHERE
4608
					    c_id = '.$course_id.' AND
4609
					    question_id='.intval($all_question_id[$i]['question_id']).' AND
4610
					    user = '.$user_id;
4611
            $result = Database::query($sql);
4612
            while ($row = Database::fetch_array($result, 'ASSOC')) {
4613
                if ($row['count'] == 0) {
4614
                    $count++;
4615
                    break;
4616
                }
4617
            }
4618
            if ($count > 0) {
4619
                $link_add = true;
4620
                break;
4621
            }
4622
        }
4623
4624
        echo '<table id="list-survey" class="table ">';
4625
        echo '<tr>';
4626
        echo '	<th>'.get_lang('SurveyName').'</th>';
4627
        echo '	<th>'.get_lang('Anonymous').'</th>';
4628
        echo '</tr>';
4629
4630
        $sql = "SELECT *
4631
                FROM $table_survey survey,
4632
                $table_survey_invitation survey_invitation
4633
				WHERE
4634
                    survey_invitation.user = $user_id AND
4635
                    survey.code = survey_invitation.survey_code AND
4636
                    survey.avail_from <= '".date('Y-m-d H:i:s')."' AND
4637
                    survey.avail_till >= '".date('Y-m-d H:i:s')."' AND
4638
                    survey.c_id = $course_id AND
4639
                    survey.session_id = $sessionId AND
4640
                    survey_invitation.c_id = $course_id
4641
				";
4642
        $result = Database::query($sql);
4643
        $counter = 0;
4644
        while ($row = Database::fetch_array($result, 'ASSOC')) {
4645
4646
            // Get the user into survey answer table (user or anonymus)
4647
            $sql = "SELECT user FROM $table_survey_answer
4648
					WHERE c_id = $course_id AND survey_id = (
4649
					    SELECT survey_id from $table_survey
4650
					    WHERE code ='".Database::escape_string($row['code'])." AND c_id = $course_id'
4651
                    )
4652
            ";
4653
            $result_answer = Database::query($sql);
4654
            $row_answer = Database::fetch_array($result_answer,'ASSOC');
4655
            echo '<tr>';
4656
            if ($row['answered'] == 0) {
4657
                echo '<td>';
4658
                echo Display::return_icon('statistics.png', get_lang('CreateNewSurvey'),array('style'=>'inline-block'),ICON_SIZE_TINY);
4659
                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>';
4660
            } else {
4661
                //echo '<td>'.$row['title'].'</td>';
4662
                echo '<td>';
4663
                echo Display::return_icon('statistics_na.png', get_lang('CreateNewSurvey'),array('style'=>'inline-block'),ICON_SIZE_TINY);
4664
                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>';
4665
            }
4666
            echo '<td class="center">';
4667
            echo ($row['anonymous'] == 1) ? get_lang('Yes') : get_lang('No');
4668
            echo '</td>';
4669
            echo '</tr>';
4670
            if ($row['anonymous'] == 1) {
4671
                $current_user_id = $_SESSION['surveyuser'];
4672
            } else {
4673
                $current_user_id = api_get_user_id();
4674
            }
4675
            $link_available = self::show_link_available(api_get_user_id(),$row['code'],$current_user_id);
4676
            //todo check this link
4677
            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...
4678
                //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>';
4679
            }
4680
        }
4681
        echo '</table>';
4682
    }
4683
4684
    /**
4685
     * Creates a multi array with the user fields that we can show. We look the visibility with the api_get_setting function
4686
     * The username is always NOT able to change it.
4687
     * @author Julio Montoya Armas <[email protected]>, Chamilo: Personality Test modification
4688
     * @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...
4689
     * 		   array[value_name][visibilty]
4690
     */
4691
    static function make_field_list()
4692
    {
4693
        //	LAST NAME and FIRST NAME
4694
        $field_list_array = array();
4695
        $field_list_array['lastname']['name'] = get_lang('LastName');
4696
        $field_list_array['firstname']['name'] = get_lang('FirstName');
4697
4698
        if (api_get_setting('profile', 'name') != 'true') {
4699
            $field_list_array['firstname']['visibility'] = 0;
4700
            $field_list_array['lastname']['visibility'] = 0;
4701
        } else {
4702
            $field_list_array['firstname']['visibility'] = 1;
4703
            $field_list_array['lastname']['visibility'] = 1;
4704
        }
4705
4706
        $field_list_array['username']['name'] = get_lang('Username');
4707
        $field_list_array['username']['visibility'] = 0;
4708
4709
        //	OFFICIAL CODE
4710
        $field_list_array['official_code']['name'] = get_lang('OfficialCode');
4711
4712 View Code Duplication
        if (api_get_setting('profile', 'officialcode') != 'true') {
4713
            $field_list_array['official_code']['visibility'] = 1;
4714
        } else {
4715
            $field_list_array['official_code']['visibility'] = 0;
4716
        }
4717
4718
        // EMAIL
4719
        $field_list_array['email']['name'] = get_lang('Email');
4720 View Code Duplication
        if (api_get_setting('profile', 'email') != 'true') {
4721
            $field_list_array['email']['visibility'] = 1;
4722
        } else {
4723
            $field_list_array['email']['visibility'] = 0;
4724
        }
4725
4726
        // PHONE
4727
        $field_list_array['phone']['name'] = get_lang('Phone');
4728 View Code Duplication
        if (api_get_setting('profile', 'phone') != 'true') {
4729
            $field_list_array['phone']['visibility'] = 0;
4730
        } else {
4731
            $field_list_array['phone']['visibility'] = 1;
4732
        }
4733
        //	LANGUAGE
4734
        $field_list_array['language']['name'] = get_lang('Language');
4735 View Code Duplication
        if (api_get_setting('profile', 'language') != 'true') {
4736
            $field_list_array['language']['visibility'] = 0;
4737
        } else {
4738
            $field_list_array['language']['visibility'] = 1;
4739
        }
4740
4741
        // EXTRA FIELDS
4742
        $extra = UserManager::get_extra_fields(0, 50, 5, 'ASC');
4743
4744
        foreach ($extra as $id => $field_details) {
4745
            if ($field_details[6] == 0) {
4746
                continue;
4747
            }
4748
            switch ($field_details[2]) {
4749 View Code Duplication
                case UserManager::USER_FIELD_TYPE_TEXT:
4750
                    $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4751
                    if ($field_details[7] == 0) {
4752
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4753
                    } else {
4754
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
4755
                    }
4756
                    break;
4757 View Code Duplication
                case UserManager::USER_FIELD_TYPE_TEXTAREA:
4758
                    $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4759
                    if ($field_details[7] == 0) {
4760
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4761
                    } else {
4762
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
4763
                    }
4764
                    break;
4765 View Code Duplication
                case UserManager::USER_FIELD_TYPE_RADIO:
4766
                    $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4767
                    if ($field_details[7] == 0) {
4768
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4769
                    } else {
4770
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
4771
                    }
4772
                    break;
4773
                case UserManager::USER_FIELD_TYPE_SELECT:
4774
                    $get_lang_variables = false;
4775 View Code Duplication
                    if (in_array($field_details[1], array('mail_notify_message', 'mail_notify_invitation', 'mail_notify_group_message'))) {
4776
                        $get_lang_variables = true;
4777
                    }
4778
4779
                    if ($get_lang_variables) {
4780
                        $field_list_array['extra_'.$field_details[1]]['name'] = get_lang($field_details[3]);
4781
                    } else {
4782
                        $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4783
                    }
4784
4785
                    if ($field_details[7] == 0) {
4786
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4787
                    } else {
4788
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
4789
                    }
4790
                    break;
4791 View Code Duplication
                case UserManager::USER_FIELD_TYPE_SELECT_MULTIPLE:
4792
                    $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4793
                    if ($field_details[7] == 0) {
4794
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4795
                    } else {
4796
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
4797
                    }
4798
                    break;
4799 View Code Duplication
                case UserManager::USER_FIELD_TYPE_DATE:
4800
                    $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4801
                    if ($field_details[7] == 0) {
4802
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4803
                    } else {
4804
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
4805
                    }
4806
                    break;
4807 View Code Duplication
                case UserManager::USER_FIELD_TYPE_DATETIME:
4808
                    $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4809
                    if ($field_details[7] == 0) {
4810
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4811
                    } else {
4812
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
4813
                    }
4814
                    break;
4815 View Code Duplication
                case UserManager::USER_FIELD_TYPE_DOUBLE_SELECT:
4816
                    $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
4817
                    if ($field_details[7] == 0) {
4818
                        $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
4819
                    } else {
4820
                        $field_list_array['extra_'.$field_details[1]]['visibility']=1;
4821
                    }
4822
                    break;
4823
                case UserManager::USER_FIELD_TYPE_DIVIDER:
4824
                    //$form->addElement('static',$field_details[1], '<br /><strong>'.$field_details[3].'</strong>');
4825
                    break;
4826
            }
4827
        }
4828
        return $field_list_array;
4829
    }
4830
4831
    /**
4832
     * @author Isaac Flores Paz <[email protected]>
4833
     * @param int $user_id - User ID
4834
     * @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...
4835
     * @return boolean
4836
     */
4837
    static function show_link_available($user_id, $survey_code, $user_answer)
4838
    {
4839
        $table_survey             = Database :: get_course_table(TABLE_SURVEY);
4840
        $table_survey_invitation  = Database :: get_course_table(TABLE_SURVEY_INVITATION);
4841
        $table_survey_answer      = Database :: get_course_table(TABLE_SURVEY_ANSWER);
4842
        $table_survey_question    = Database :: get_course_table(TABLE_SURVEY_QUESTION);
4843
4844
        $survey_code = Database::escape_string($survey_code);
4845
        $user_id = intval($user_id);
4846
        $user_answer = Database::escape_string($user_answer);
4847
4848
        $course_id = api_get_course_int_id();
4849
4850
        $sql = 'SELECT COUNT(*) as count
4851
                FROM '.$table_survey_invitation.'
4852
		        WHERE user='.$user_id.' AND survey_code="'.$survey_code.'" AND answered="1" AND c_id = '.$course_id.' ';
4853
4854
        $sql2 = 'SELECT COUNT(*) as count FROM '.$table_survey.' s INNER JOIN '.$table_survey_question.' q ON s.survey_id=q.survey_id
4855
				 WHERE s.code="'.$survey_code.'" AND q.type NOT IN("pagebreak","comment") AND s.c_id = '.$course_id.' AND q.c_id = '.$course_id.' ';
4856
4857
        $sql3 = 'SELECT COUNT(DISTINCT question_id) as count FROM '.$table_survey_answer.'
4858
				 WHERE survey_id=(SELECT survey_id FROM '.$table_survey.'
4859
				 WHERE code="'.$survey_code.'" AND c_id = '.$course_id.' ) AND user="'.$user_answer.'" AND c_id = '.$course_id.' ';
4860
4861
        $result  = Database::query($sql);
4862
        $result2 = Database::query($sql2);
4863
        $result3 = Database::query($sql3);
4864
4865
        $row  = Database::fetch_array($result, 'ASSOC');
4866
        $row2 = Database::fetch_array($result2, 'ASSOC');
4867
        $row3 = Database::fetch_array($result3, 'ASSOC');
4868
4869
        if ($row['count'] == 1 && $row3['count'] != $row2['count']) {
4870
            return true;
4871
        } else {
4872
            return false;
4873
        }
4874
    }
4875
4876
    /**
4877
     * Display survey question chart
4878
     * @param	array	Chart data
4879
     * @param	boolean	Tells if the chart has a serie. False by default
4880
     * @return	void 	(direct output)
4881
     */
4882
    public static function drawChart($chartData, $hasSerie = false, $chartContainerId = 'chartContainer')
4883
    {
4884
        $htmlChart = '';
4885
        if (api_browser_support("svg")) {
4886
            $htmlChart .= api_get_js("d3/d3.v3.5.4.min.js");
4887
            $htmlChart .= api_get_js("dimple.v2.1.2.min.js") . '
4888
            <script type="text/javascript">
4889
            var svg = dimple.newSvg("#'.$chartContainerId.'", "100%", 400);
4890
            var data = [';
4891
            $serie = array();
4892
            $order = array();
4893
            foreach ($chartData as $chartDataElement) {
4894
                $htmlChart .= '{"';
4895
                if (!$hasSerie) {
4896
                    $htmlChart .= get_lang("Option") . '":"' . $chartDataElement['option'] . '", "';
4897
                    array_push($order, $chartDataElement['option']);
4898
                } else {
4899
                    if (!is_array($chartDataElement['serie'])) {
4900
                        $htmlChart .= get_lang("Option") . '":"' . $chartDataElement['serie'] . '", "' .
4901
                            get_lang("Score") . '":"' . $chartDataElement['option'] . '", "';
4902
                        array_push($serie, $chartDataElement['serie']);
4903
                    } else {
4904
                        $htmlChart .= get_lang("Serie") . '":"' . $chartDataElement['serie'][0] . '", "' .
4905
                            get_lang("Option") . '":"' . $chartDataElement['serie'][1] . '", "' .
4906
                            get_lang("Score") . '":"' . $chartDataElement['option'] . '", "';
4907
                    }
4908
                }
4909
                $htmlChart .= get_lang("Votes") . '":"' . $chartDataElement['votes'] .
4910
                    '"},';
4911
            }
4912
            rtrim($htmlChart, ",");
4913
            $htmlChart .= '];
4914
                var myChart = new dimple.chart(svg, data);
4915
                myChart.addMeasureAxis("y", "' . get_lang("Votes") . '");';
4916
            if (!$hasSerie) {
4917
                $htmlChart .= 'var xAxisCategory = myChart.addCategoryAxis("x", "' . get_lang("Option") . '");
4918
                    xAxisCategory.addOrderRule(' . json_encode($order) . ');
4919
                    myChart.addSeries("' . get_lang("Option") . '", dimple.plot.bar);';
4920
            } else {
4921
                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 4893. 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...
4922
                    $serie = array_values(array_unique($serie));
4923
                    $htmlChart .= 'var xAxisCategory = myChart.addCategoryAxis("x", ["' . get_lang("Option") . '","' . get_lang("Score") . '"]);
4924
                        xAxisCategory.addOrderRule(' . json_encode($serie) . ');
4925
                        xAxisCategory.addGroupOrderRule("' . get_lang("Score") . '");
4926
                        myChart.addSeries("' . get_lang("Option") . '", dimple.plot.bar);';
4927
                } else {
4928
                    $htmlChart .= 'myChart.addCategoryAxis("x", ["' . get_lang("Option") . '","' . get_lang("Score") . '"]);
4929
                        myChart.addSeries("' . get_lang("Serie") . '", dimple.plot.bar);';
4930
                }
4931
            }
4932
            $htmlChart .= 'myChart.draw();
4933
                </script>';
4934
        }
4935
        return $htmlChart;
4936
    }
4937
4938
    /**
4939
     * Set a flag to the current survey as answered by the current user
4940
     * @param string $surveyCode The survey code
4941
     * @param int $courseId The course ID
4942
     */
4943
    public static function flagSurveyAsAnswered($surveyCode, $courseId)
4944
    {
4945
        $currenUserId = api_get_user_id();
4946
        $flag = sprintf("%s-%s-%d", $courseId, $surveyCode, $currenUserId);
4947
4948
        if (!isset($_SESSION['filled_surveys'])) {
4949
            $_SESSION['filled_surveys'] = array();
4950
        }
4951
4952
        $_SESSION['filled_surveys'][] = $flag;
4953
    }
4954
4955
    /**
4956
     * Check whether a survey was answered by the current user
4957
     * @param string $surveyCode The survey code
4958
     * @param int $courseId The course ID
4959
     * @return boolean
4960
     */
4961
    public static function isSurveyAnsweredFlagged($surveyCode, $courseId)
4962
    {
4963
        $currenUserId = api_get_user_id();
4964
        $flagToCheck = sprintf("%s-%s-%d", $courseId, $surveyCode, $currenUserId);
4965
4966
        if (!isset($_SESSION['filled_surveys'])) {
4967
            return false;
4968
        }
4969
4970
        if (!is_array($_SESSION['filled_surveys'])) {
4971
            return false;
4972
        }
4973
4974
        foreach ($_SESSION['filled_surveys'] as $flag) {
4975
            if ($flagToCheck != $flag) {
4976
                continue;
4977
            }
4978
4979
            return true;
4980
        }
4981
4982
        return false;
4983
    }
4984
}
4985