Completed
Push — master ( 88715c...d7c14e )
by Julito
09:34
created

check_time_availability()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 28
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 21
nc 8
nop 1
dl 0
loc 28
rs 9.584
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use ChamiloSession as Session;
5
6
/**
7
 * @package chamilo.survey
8
 *
9
 * @author unknown, the initial survey that did not make it in 1.8 because of bad code
10
 * @author Patrick Cool <[email protected]>, Ghent University: cleanup,
11
 * refactoring and rewriting large parts of the code
12
 * @author Julio Montoya <[email protected]>, Chamilo: Personality Test
13
 * modification and rewriting large parts of the code as well
14
 *
15
 * @todo check if the user already filled the survey and if this
16
 * is the case then the answers have to be updated and not stored again.
17
 * @todo performance could be improved if not the survey_id was
18
 * stored with the invitation but the survey_code
19
 */
20
21
// Unsetting the course id (because it is in the URL)
22
if (!isset($_GET['cidReq'])) {
23
    $cidReset = true;
24
} else {
25
    $_cid = $_GET['cidReq'];
26
}
27
28
require_once __DIR__.'/../inc/global.inc.php';
29
30
// Database table definitions
31
$table_survey = Database::get_course_table(TABLE_SURVEY);
32
$table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
33
$table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
34
$table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
35
$table_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
36
$table_user = Database::get_main_table(TABLE_MAIN_USER);
37
38
$allowRequiredSurveyQuestions = api_get_configuration_value('allow_required_survey_questions');
39
40
// Check if user is anonymous or not
41
$isAnonymous = false;
42
if (api_is_anonymous(api_get_user_id(), true)) {
43
    $isAnonymous = true;
44
}
45
46
// getting all the course information
47
if (isset($_GET['course'])) {
48
    $courseInfo = api_get_course_info($_GET['course']);
49
} else {
50
    $courseInfo = api_get_course_info();
51
}
52
53
if (empty($courseInfo)) {
54
    api_not_allowed(true);
55
}
56
57
$userInfo = api_get_user_info();
58
$sessionId = isset($_GET['id_session']) ? (int) $_GET['id_session'] : api_get_session_id();
59
60
// Breadcrumbs
61
if (!empty($userInfo)) {
62
    $interbreadcrumb[] = [
63
        'url' => api_get_path(WEB_CODE_PATH).'survey/survey_list.php?cidReq='.$courseInfo['code'].'&id_session='.$sessionId,
64
        'name' => get_lang('SurveyList'),
65
    ];
66
}
67
68
$course_id = $courseInfo['real_id'];
69
$surveyCode = isset($_GET['scode']) ? Database::escape_string($_GET['scode']) : '';
70
71
if ($surveyCode != '') {
72
    // Firstly we check if this survey is ready for anonymous use:
73
    $sql = "SELECT anonymous FROM $table_survey
74
            WHERE c_id = $course_id AND code ='".$surveyCode."'";
75
    $resultAnonymous = Database::query($sql);
76
    $rowAnonymous = Database::fetch_array($resultAnonymous, 'ASSOC');
77
    // If is anonymous and is not allowed to take the survey to anonymous users, forbid access:
78
    if (!isset($rowAnonymous['anonymous']) ||
79
        ($rowAnonymous['anonymous'] == 0 && api_is_anonymous()) ||
80
        count($rowAnonymous) == 0
81
    ) {
82
        api_not_allowed(true);
83
    }
84
    // If is anonymous and it is allowed to take the survey as anonymous, mark survey as anonymous.
85
}
86
87
// First we check if the needed parameters are present
88
if ((!isset($_GET['course']) || !isset($_GET['invitationcode'])) && !isset($_GET['user_id'])) {
89
    api_not_allowed(true, get_lang('SurveyParametersMissingUseCopyPaste'));
90
}
91
92
$invitationcode = $_GET['invitationcode'];
93
94
// Start auto-invitation feature FS#3403 (all-users-can-do-the-survey-URL handling)
95
if ($invitationcode == 'auto' && isset($_GET['scode'])) {
96
    $userid = api_get_user_id();
97
    // Survey_code of the survey
98
    $surveyCode = $_GET['scode'];
99
    if ($isAnonymous) {
100
        $autoInvitationcode = 'auto-ANONY_'.md5(time())."-$surveyCode";
101
    } else {
102
        // New invitation code from userid
103
        $autoInvitationcode = "auto-$userid-$surveyCode";
104
    }
105
106
    // The survey code must exist in this course, or the URL is invalid
107
    $sql = "SELECT * FROM $table_survey
108
            WHERE c_id = $course_id AND code = '".Database::escape_string($surveyCode)."'";
109
    $result = Database::query($sql);
110
    if (Database :: num_rows($result) > 0) {
111
        // Check availability
112
        $row = Database :: fetch_array($result, 'ASSOC');
113
        $tempdata = SurveyManager :: get_survey($row['survey_id']);
114
        SurveyManager::checkTimeAvailability($tempdata);
115
        // Check for double invitation records (insert should be done once)
116
        $sql = "SELECT user
117
                FROM $table_survey_invitation
118
                WHERE
119
                    c_id = $course_id AND
120
                    invitation_code = '".Database::escape_string($autoInvitationcode)."'";
121
        $result = Database::query($sql);
122
        $now = api_get_utc_datetime();
123
        if (Database :: num_rows($result) == 0) {
124
            $params = [
125
                'c_id' => $course_id,
126
                'survey_code' => $surveyCode,
127
                'user' => $userid,
128
                'invitation_code' => $autoInvitationcode,
129
                'invitation_date' => $now,
130
            ];
131
            Database::insert($table_survey_invitation, $params);
132
        }
133
        // From here we use the new invitationcode auto-userid-surveycode string
134
        $_GET['invitationcode'] = $autoInvitationcode;
135
        $invitationcode = $autoInvitationcode;
136
    }
137
}
138
139
// Now we check if the invitation code is valid
140
$sql = "SELECT * FROM $table_survey_invitation
141
        WHERE
142
            c_id = $course_id AND
143
            invitation_code = '".Database::escape_string($invitationcode)."'";
144
$result = Database::query($sql);
145
if (Database::num_rows($result) < 1) {
146
    api_not_allowed(true, get_lang('WrongInvitationCode'));
147
}
148
149
$survey_invitation = Database::fetch_array($result, 'ASSOC');
150
$surveyUserFromSession = Session::read('surveyuser');
151
// Now we check if the user already filled the survey
152
if (!isset($_POST['finish_survey']) &&
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: (! IssetNode && $isAnony...d'] == 1 && ! IssetNode, Probably Intended Meaning: ! IssetNode && ($isAnony...'] == 1 && ! IssetNode)
Loading history...
153
    (
154
        $isAnonymous &&
155
        !empty($surveyUserFromSession) &&
156
        SurveyUtil::isSurveyAnsweredFlagged($survey_invitation['survey_code'], $survey_invitation['c_id'])
157
    ) ||
158
    ($survey_invitation['answered'] == 1 && !isset($_GET['user_id']))
159
) {
160
    api_not_allowed(true, Display::return_message(get_lang('YouAlreadyFilledThisSurvey')));
161
}
162
163
$logInfo = [
164
    'tool' => TOOL_SURVEY,
165
    'tool_id' => $survey_invitation['survey_invitation_id'],
166
    'tool_id_detail' => 0,
167
    'action' => 'invitationcode',
168
    'action_details' => $invitationcode,
169
    'current_id' => 0,
170
    'info' => '',
171
];
172
Event::registerLog($logInfo);
173
174
// Checking if there is another survey with this code.
175
// If this is the case there will be a language choice
176
$sql = "SELECT * FROM $table_survey
177
        WHERE
178
            c_id = $course_id AND
179
            code = '".Database::escape_string($survey_invitation['survey_code'])."'";
180
$sql .= api_get_session_condition($sessionId);
181
$result = Database::query($sql);
182
183
if (Database::num_rows($result) > 1) {
184
    if ($_POST['language']) {
185
        $survey_invitation['survey_id'] = $_POST['language'];
186
    } else {
187
        Display :: display_header(get_lang('ToolSurvey'));
188
        $frmLangUrl = api_get_self().'?'.api_get_cidreq().'&'
189
            .http_build_query([
190
                'course' => Security::remove_XSS($_GET['course']),
191
                'invitationcode' => Security::remove_XSS($_GET['invitationcode']),
192
            ]);
193
194
        echo '<form id="language" name="language" method="POST" action="'.$frmLangUrl.'">';
195
        echo '<select name="language">';
196
        while ($row = Database::fetch_array($result, 'ASSOC')) {
197
            echo '<option value="'.$row['survey_id'].'">'.$row['lang'].'</option>';
198
        }
199
        echo '</select>';
200
        echo '<button type="submit" name="Submit" class="next">'.get_lang('Ok').'</button>';
201
        echo '</form>';
202
        Display::display_footer();
203
        exit();
204
    }
205
} else {
206
    $row = Database::fetch_array($result, 'ASSOC');
207
    $survey_invitation['survey_id'] = $row['survey_id'];
208
}
209
210
// Getting the survey information
211
$survey_data = SurveyManager::get_survey($survey_invitation['survey_id']);
212
if (empty($survey_data)) {
213
    api_not_allowed(true);
214
}
215
216
// Checking time availability
217
SurveyManager::checkTimeAvailability($survey_data);
218
$survey_data['survey_id'] = $survey_invitation['survey_id'];
219
220
if ($survey_data['survey_type'] == '3') {
221
    header('Location: '.
222
        api_get_path(WEB_CODE_PATH).
223
        'survey/meeting.php?cidReq='.$courseInfo['code'].'&id_session='.$sessionId.'&invitationcode='.Security::remove_XSS($invitationcode)
224
    );
225
    exit;
226
}
227
228
// Storing the answers
229
if (count($_POST) > 0) {
230
    if ($survey_data['survey_type'] === '0') {
231
        $types = [];
232
        $required = [];
233
        // Getting all the types of the question
234
        // (because of the special treatment of the score question type
235
        $sql = "SELECT * FROM $table_survey_question
236
                WHERE
237
                    c_id = $course_id AND
238
                    survey_id = '".intval($survey_invitation['survey_id'])."'";
239
        $result = Database::query($sql);
240
241
        while ($row = Database::fetch_array($result, 'ASSOC')) {
242
            $types[$row['question_id']] = $row['type'];
243
            $required[$row['question_id']] = $allowRequiredSurveyQuestions && $row['is_required'];
244
        }
245
246
        // Looping through all the post values
247
        foreach ($_POST as $key => &$value) {
248
            // If the post value key contains the string 'question' then it is an answer on a question
249
            if (strpos($key, 'question') !== false && ($key != '_qf__question')) {
250
                // Finding the question id by removing 'question'
251
                $survey_question_id = str_replace('question', '', $key);
252
                // If not question ID was defined, we're on the start
253
                // screen or something else that doesn't require
254
                // saving an answer
255
                if (empty($survey_question_id)) {
256
                    continue;
257
                }
258
                /* If the post value is an array then we have a multiple response question or a scoring question type
259
                remark: when it is a multiple response then the value of the array is the option_id
260
                when it is a scoring question then the key of the array is the option_id and the value is the value
261
                */
262
                if (is_array($value)) {
263
                    SurveyUtil::remove_answer(
264
                        $survey_invitation['user'],
265
                        $survey_invitation['survey_id'],
266
                        $survey_question_id,
267
                        $course_id
268
                    );
269
270
                    foreach ($value as $answer_key => &$answer_value) {
271
                        if ($types[$survey_question_id] == 'score') {
272
                            $option_id = $answer_key;
273
                            $option_value = $answer_value;
274
                        } else {
275
                            $option_id = $answer_value;
276
                            $option_value = '';
277
                        }
278
279
                        SurveyUtil::store_answer(
280
                            $survey_invitation['user'],
281
                            $survey_invitation['survey_id'],
282
                            $survey_question_id,
283
                            $option_id,
284
                            $option_value,
285
                            $survey_data
286
                        );
287
                    }
288
                } else {
289
                    // All the other question types (open question, multiple choice, percentage, ...)
290
                    if (isset($types[$survey_question_id]) &&
291
                        $types[$survey_question_id] == 'percentage') {
292
                        $sql = "SELECT * FROM $table_survey_question_option
293
                                WHERE
294
                                    c_id = $course_id AND
295
                                    question_option_id='".intval($value)."'";
296
                        $result = Database::query($sql);
297
                        $row = Database::fetch_array($result, 'ASSOC');
298
                        $option_value = $row['option_text'];
299
                    } else {
300
                        $option_value = 0;
301
                        if (isset($types[$survey_question_id]) &&
302
                            $types[$survey_question_id] == 'open'
303
                        ) {
304
                            $option_value = $value;
305
                        }
306
                    }
307
308
                    $survey_question_answer = $value;
309
310
                    SurveyUtil::remove_answer(
311
                        $survey_invitation['user'],
312
                        $survey_invitation['survey_id'],
313
                        $survey_question_id,
314
                        $course_id
315
                    );
316
317
                    SurveyUtil::store_answer(
318
                        $survey_invitation['user'],
319
                        $survey_invitation['survey_id'],
320
                        $survey_question_id,
321
                        $value,
322
                        $option_value,
323
                        $survey_data
324
                    );
325
                }
326
            }
327
        }
328
    } elseif ($survey_data['survey_type'] === '1') {
329
        //conditional/personality-test type surveys
330
        // Getting all the types of the question (because of the special treatment of the score question type
331
        $shuffle = '';
332
        if ($survey_data['shuffle'] == '1') {
333
            $shuffle = ' ORDER BY RAND() ';
334
        }
335
        $sql = "SELECT * FROM $table_survey_question
336
                WHERE
337
                    c_id = $course_id AND
338
                    survey_id = '".intval($survey_invitation['survey_id'])."' AND
339
                    survey_group_pri = '0' $shuffle";
340
        $result = Database::query($sql);
341
        // There is only one question type for conditional surveys
342
        while ($row = Database::fetch_array($result, 'ASSOC')) {
343
            $types[$row['question_id']] = $row['type'];
344
        }
345
346
        // Looping through all the post values
347
        foreach ($_POST as $key => &$value) {
348
            // If the post value key contains the string 'question' then it is an answer to a question
349
            if (strpos($key, 'question') !== false) {
350
                // Finding the question id by removing 'question'
351
                $survey_question_id = str_replace('question', '', $key);
352
                // If not question ID was defined, we're on the start
353
                // screen or something else that doesn't require
354
                // saving an answer
355
                if (empty($survey_question_id)) {
356
                    continue;
357
                }
358
                // We select the correct answer and the puntuacion
359
                $sql = "SELECT value FROM $table_survey_question_option
360
                        WHERE c_id = $course_id AND question_option_id='".intval($value)."'";
361
                $result = Database::query($sql);
362
                $row = Database::fetch_array($result, 'ASSOC');
363
                $option_value = $row['value'];
364
                //$option_value = 0;
365
                $survey_question_answer = $value;
366
367
                // We save the answer after making sure that a possible previous attempt is deleted
368
                SurveyUtil::remove_answer(
369
                    $survey_invitation['user'],
370
                    $survey_invitation['survey_id'],
371
                    $survey_question_id,
372
                    $course_id
373
                );
374
375
                SurveyUtil::store_answer(
376
                    $survey_invitation['user'],
377
                    $survey_invitation['survey_id'],
378
                    $survey_question_id,
379
                    $value,
380
                    $option_value,
381
                    $survey_data
382
                );
383
            }
384
        }
385
    } else {
386
        // In case it's another type than 0 or 1
387
        api_not_allowed(true, get_lang('ErrorSurveyTypeUnknown'));
388
    }
389
}
390
391
$user_id = api_get_user_id();
392
393
if ($user_id == 0) {
394
    $user_id = $survey_invitation['user'];
395
}
396
$user_data = api_get_user_info($user_id);
397
398
if ($survey_data['form_fields'] != '' &&
399
    $survey_data['anonymous'] == 0 &&
400
    is_array($user_data)
401
) {
402
    $form_fields = explode('@', $survey_data['form_fields']);
403
    $list = [];
404
    foreach ($form_fields as $field) {
405
        $field_value = explode(':', $field);
406
        if (isset($field_value[1]) && $field_value[1] == 1) {
407
            if ($field_value[0] != '') {
408
                $val = api_substr($field_value[0], 8, api_strlen($field_value[0]));
409
                $list[$val] = 1;
410
            }
411
        }
412
    }
413
414
    $url = api_get_self().
415
        '?cidReq='.$courseInfo['code'].
416
        '&id_session='.$sessionId;
417
    $listQueryParams = preg_split('/&/', $_SERVER['QUERY_STRING']);
418
    foreach ($listQueryParams as $param) {
419
        $url .= '&'.Security::remove_XSS($param);
420
    }
421
422
    // We use the same form as in auth/profile.php
423
    $form = new FormValidator('profile', 'post', $url);
424
    if (api_is_western_name_order()) {
425
        if (isset($list['firstname']) && $list['firstname'] == 1) {
426
            //FIRST NAME
427
            $form->addElement('text', 'firstname', get_lang('FirstName'), ['size' => 40]);
428
            if (api_get_setting('profile', 'name') !== 'true') {
429
                $form->freeze(['firstname']);
430
            }
431
            $form->applyFilter(['firstname'], 'stripslashes');
432
            $form->applyFilter(['firstname'], 'trim');
433
            $form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
434
        }
435
        if (isset($list['lastname']) && $list['lastname'] == 1) {
436
            //    LAST NAME
437
            $form->addElement('text', 'lastname', get_lang('LastName'), ['size' => 40]);
438
            if (api_get_setting('profile', 'name') !== 'true') {
439
                $form->freeze(['lastname']);
440
            }
441
            $form->applyFilter(['lastname'], 'stripslashes');
442
            $form->applyFilter(['lastname'], 'trim');
443
            $form->addRule('lastname', get_lang('ThisFieldIsRequired'), 'required');
444
        }
445
    } else {
446
        if (isset($list['lastname']) && $list['lastname'] == 1) {
447
            //    LAST NAME
448
            $form->addElement('text', 'lastname', get_lang('LastName'), ['size' => 40]);
449
            if (api_get_setting('profile', 'name') !== 'true') {
450
                $form->freeze(['lastname']);
451
            }
452
            $form->applyFilter(['lastname'], 'stripslashes');
453
            $form->applyFilter(['lastname'], 'trim');
454
            $form->addRule('lastname', get_lang('ThisFieldIsRequired'), 'required');
455
        }
456
        if (isset($list['firstname']) && $list['firstname'] == 1) {
457
            //FIRST NAME
458
            $form->addElement('text', 'firstname', get_lang('FirstName'), ['size' => 40]);
459
            if (api_get_setting('profile', 'name') !== 'true') {
460
                $form->freeze(['firstname']);
461
            }
462
            $form->applyFilter(['firstname'], 'stripslashes');
463
            $form->applyFilter(['firstname'], 'trim');
464
            $form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
465
        }
466
    }
467
468
    if (isset($list['official_code']) && $list['official_code'] == 1) {
469
        //    OFFICIAL CODE
470
        $form->addElement('text', 'official_code', get_lang('OfficialCode'), ['size' => 40]);
471
        if (api_get_setting('profile', 'officialcode') !== 'true') {
472
            $form->freeze('official_code');
473
        }
474
        $form->applyFilter('official_code', 'stripslashes');
475
        $form->applyFilter('official_code', 'trim');
476
        if (api_get_setting('registration', 'officialcode') == 'true' &&
477
            api_get_setting('profile', 'officialcode') == 'true'
478
        ) {
479
            $form->addRule('official_code', get_lang('ThisFieldIsRequired'), 'required');
480
        }
481
    }
482
483
    if (isset($list['email']) && $list['email'] == 1) {
484
        //    EMAIL
485
        $form->addElement('text', 'email', get_lang('Email'), ['size' => 40]);
486
        if (api_get_setting('profile', 'email') !== 'true') {
487
            $form->freeze('email');
488
        }
489
        $form->applyFilter('email', 'stripslashes');
490
        $form->applyFilter('email', 'trim');
491
        if (api_get_setting('registration', 'email') == 'true') {
492
            $form->addRule('email', get_lang('ThisFieldIsRequired'), 'required');
493
        }
494
        $form->addRule('email', get_lang('EmailWrong'), 'email');
495
    }
496
497
    if (isset($list['phone']) && $list['phone'] == 1) {
498
        // PHONE
499
        $form->addElement('text', 'phone', get_lang('Phone'), ['size' => 20]);
500
        if (api_get_setting('profile', 'phone') !== 'true') {
501
            $form->freeze('phone');
502
        }
503
        $form->applyFilter('phone', 'stripslashes');
504
        $form->applyFilter('phone', 'trim');
505
        if (api_get_setting('profile', 'phone') == 'true') {
506
            $form->addRule('phone', get_lang('ThisFieldIsRequired'), 'required');
507
        }
508
    }
509
510
    if (isset($list['language']) && $list['language'] == 1) {
511
        // LANGUAGE
512
        $form->addSelectLanguage('language', get_lang('Language'));
513
        if (api_get_setting('profile', 'language') !== 'true') {
514
            $form->freeze('language');
515
        }
516
        if (api_get_setting('profile', 'language') == 'true') {
517
            $form->addRule('language', get_lang('ThisFieldIsRequired'), 'required');
518
        }
519
    }
520
521
    // EXTRA FIELDS
522
    $extraField = new ExtraField('user');
523
    $returnParams = $extraField->addElements($form, api_get_user_id());
524
    $jquery_ready_content = $returnParams['jquery_ready_content'];
525
526
    // the $jquery_ready_content variable collects all functions
527
    // that will be load in the $(document).ready javascript function
528
    $htmlHeadXtra[] = '<script>
529
    $(document).ready(function(){
530
        '.$jquery_ready_content.'
531
    });
532
    </script>';
533
534
    $form->addButtonNext(get_lang('Next'));
535
    $form->setDefaults($user_data);
536
}
537
538
Display::display_header(get_lang('ToolSurvey'));
539
540
// Displaying the survey title and subtitle (appears on every page)
541
echo '<div class="survey-block">';
542
echo '<div class="page-header">';
543
echo '<h2>';
544
echo strip_tags($survey_data['survey_title']).'</h2></div>';
545
if (!empty($survey_data['survey_subtitle'])) {
546
    echo '<div class="survey_subtitle"><p>'.strip_tags($survey_data['survey_subtitle']).'</p></div>';
547
}
548
549
// Displaying the survey introduction
550
if (
551
    !isset($_GET['show']) ||
552
    (isset($_GET['show'])) && $_GET['show'] == '') {
553
    // The first thing we do is delete the session
554
    Session::erase('paged_questions');
555
    Session::erase('page_questions_sec');
556
    $paged_questions_sec = [];
557
    if (!empty($survey_data['survey_introduction'])) {
558
        echo '<div class="survey_content">'.$survey_data['survey_introduction'].'</div>';
559
    }
560
    $limit = 0;
561
}
562
563
if ($survey_data['form_fields'] &&
564
    $survey_data['anonymous'] == 0 &&
565
    is_array($user_data) &&
566
    !isset($_GET['show'])
567
) {
568
    if ($form->validate()) {
569
        $user_data = $form->exportValues();
570
        if (is_array($user_data)) {
571
            if (count($user_data) > 0) {
572
                $extras = [];
573
                // Build SQL query
574
                $sql = "UPDATE $table_user SET";
575
                $update = false;
576
                $allowedFields = [
577
                    'firstname',
578
                    'lastname',
579
                    'official_code',
580
                    'email',
581
                    'phone',
582
                    'language',
583
                ];
584
585
                foreach ($user_data as $key => $value) {
586
                    if (in_array($key, $allowedFields)) {
587
                        $sql .= " $key = '".Database :: escape_string($value)."',";
588
                        $update = true;
589
                    }
590
                }
591
                // Remove trailing , from the query we have so far
592
                $sql = rtrim($sql, ',');
593
                $sql .= " WHERE id  = $user_id";
594
595
                if ($update) {
596
                    Database::query($sql);
597
                }
598
599
                $extraFieldValue = new ExtraFieldValue('user');
600
                $extraFieldValue->saveFieldValues($user_data);
601
602
                echo '<div id="survey_content" class="survey_content">'.
603
                    get_lang('InformationUpdated').' '.get_lang('PleaseFillSurvey').'</div>';
604
            }
605
        }
606
        $_GET['show'] = 0;
607
        $show = 0;
608
        // We unset the sessions
609
        Session::erase('paged_questions');
610
        Session::erase('page_questions_sec');
611
        $paged_questions_sec = [];
612
    } else {
613
        echo '<div id="survey_content" class="survey_content">'.get_lang('UpdateInformation').'</div>';
614
        // We unset the sessions
615
        Session::erase('paged_questions');
616
        Session::erase('page_questions_sec');
617
        $paged_questions_sec = [];
618
        $form->display();
619
    }
620
}
621
622
// Displaying the survey thanks message
623
if (isset($_POST['finish_survey'])) {
624
    echo Display::return_message(get_lang('SurveyFinished'), 'confirm');
625
    echo $survey_data['survey_thanks'];
626
627
    SurveyManager::update_survey_answered(
628
        $survey_data,
629
        $survey_invitation['user'],
630
        $survey_invitation['survey_code']
631
    );
632
633
    SurveyUtil::flagSurveyAsAnswered(
634
        $survey_invitation['survey_code'],
635
        $survey_invitation['c_id']
636
    );
637
638
    if ($courseInfo) {
639
        echo Display::toolbarButton(
640
            get_lang('ReturnToCourseHomepage'),
641
            api_get_course_url($courseInfo['code']),
642
            'home'
643
        );
644
    }
645
646
    Session::erase('paged_questions');
647
    Session::erase('page_questions_sec');
648
    Display::display_footer();
649
    exit();
650
}
651
652
// Sets the random questions
653
$shuffle = '';
654
if ($survey_data['shuffle'] == 1) {
655
    $shuffle = ' BY RAND() ';
656
}
657
658
if ((isset($_GET['show']) && $_GET['show'] != '') ||
659
    isset($_POST['personality'])
660
) {
661
    // Getting all the questions for this page and add them to a
662
    // multidimensional array where the first index is the page.
663
    // As long as there is no pagebreak fount we keep adding questions to the page
664
    $questions_displayed = [];
665
    $counter = 0;
666
    // If non-conditional survey
667
    $paged_questions = [];
668
    // If non-conditional survey
669
    if ($survey_data['survey_type'] == '0') {
670
        if (empty($paged_questions)) {
671
            $sql = "SELECT * FROM $table_survey_question
672
                    WHERE
673
                        survey_question NOT LIKE '%{{%' AND 
674
                        c_id = $course_id AND 
675
                        survey_id = '".intval($survey_invitation['survey_id'])."'
676
                    ORDER BY sort ASC";
677
            $result = Database::query($sql);
678
            while ($row = Database::fetch_array($result, 'ASSOC')) {
679
                if ($survey_data['one_question_per_page'] == 1) {
680
                    if ($row['type'] != 'pagebreak') {
681
                        $paged_questions[$counter][] = $row['question_id'];
682
                        $counter++;
683
                        continue;
684
                    }
685
                } else {
686
                    if ($row['type'] == 'pagebreak') {
687
                        $counter++;
688
                    } else {
689
                        $paged_questions[$counter][] = $row['question_id'];
690
                    }
691
                }
692
            }
693
            Session::write('paged_questions', $paged_questions);
694
        }
695
696
        // Redefinition of variables and session ids to fix issue of survey not
697
        //  showing questions - see support.chamilo.org #5529
698
        $course_id = $survey_invitation['c_id'];
699
        Session::write('_cid', $course_id);
700
        Session::write('_real_cid', $course_id);
701
702
        if (array_key_exists($_GET['show'], $paged_questions)) {
703
            if (isset($_GET['user_id'])) {
704
                // Get the user into survey answer table (user or anonymus)
705
                $my_user_id = $survey_data['anonymous'] == 1 ? $surveyUserFromSession : api_get_user_id();
706
707
                $sql = "SELECT
708
                            survey_question.survey_group_sec1,
709
                            survey_question.survey_group_sec2,
710
                            survey_question.survey_group_pri,
711
                            survey_question.question_id,
712
                            survey_question.survey_id,
713
                            survey_question.survey_question,
714
                            survey_question.display,
715
                            survey_question.sort,
716
                            survey_question.type,
717
                            survey_question.max_value,
718
                            survey_question_option.question_option_id,
719
                            survey_question_option.option_text,
720
                            survey_question_option.sort as option_sort
721
                        FROM $table_survey_question survey_question
722
                        LEFT JOIN $table_survey_question_option survey_question_option
723
                        ON survey_question.question_id = survey_question_option.question_id AND
724
                        survey_question_option.c_id = $course_id
725
                        WHERE
726
                            survey_question.survey_id = '".Database::escape_string($survey_invitation['survey_id'])."' AND
727
                            survey_question.question_id NOT IN (
728
                                SELECT sa.question_id
729
                                FROM ".$table_survey_answer." sa
730
                                WHERE
731
                                    sa.user='".$my_user_id."') AND
732
                                    survey_question.c_id =  $course_id
733
                                ORDER BY survey_question.sort, survey_question_option.sort ASC";
734
            } else {
735
                $sql = "SELECT
736
                            survey_question.survey_group_sec1,
737
                            survey_question.survey_group_sec2,
738
                            survey_question.survey_group_pri,
739
                            survey_question.question_id,
740
                            survey_question.survey_id,
741
                            survey_question.survey_question,
742
                            survey_question.display,
743
                            survey_question.sort,
744
                            survey_question.type,
745
                            survey_question.max_value,
746
                            survey_question_option.question_option_id,
747
                            survey_question_option.option_text,
748
                            survey_question_option.sort as option_sort
749
                            ".($allowRequiredSurveyQuestions ? ', survey_question.is_required' : '')."
750
                        FROM $table_survey_question survey_question
751
                        LEFT JOIN $table_survey_question_option survey_question_option
752
                            ON survey_question.question_id = survey_question_option.question_id AND
753
                            survey_question_option.c_id = $course_id
754
                        WHERE
755
                            survey_question NOT LIKE '%{{%' AND
756
                            survey_question.survey_id = '".intval($survey_invitation['survey_id'])."' AND
757
                            survey_question.question_id IN (".implode(',', $paged_questions[$_GET['show']]).") AND
758
                            survey_question.c_id =  $course_id
759
                        ORDER BY survey_question.sort, survey_question_option.sort ASC";
760
            }
761
762
            $result = Database::query($sql);
763
            $question_counter_max = Database::num_rows($result);
764
            $counter = 0;
765
            $limit = 0;
766
            $questions = [];
767
            while ($row = Database :: fetch_array($result, 'ASSOC')) {
768
                // If the type is not a pagebreak we store it in the $questions array
769
                if ($row['type'] != 'pagebreak') {
770
                    $questions[$row['sort']]['question_id'] = $row['question_id'];
771
                    $questions[$row['sort']]['survey_id'] = $row['survey_id'];
772
                    $questions[$row['sort']]['survey_question'] = $row['survey_question'];
773
                    $questions[$row['sort']]['display'] = $row['display'];
774
                    $questions[$row['sort']]['type'] = $row['type'];
775
                    $questions[$row['sort']]['options'][$row['question_option_id']] = $row['option_text'];
776
                    $questions[$row['sort']]['maximum_score'] = $row['max_value'];
777
                    $questions[$row['sort']]['sort'] = $row['sort'];
778
                    $questions[$row['sort']]['is_required'] = $allowRequiredSurveyQuestions && $row['is_required'];
779
                }
780
                $counter++;
781
            }
782
        }
783
    } elseif ($survey_data['survey_type'] === '1') {
784
        $my_survey_id = (int) $survey_invitation['survey_id'];
785
        $current_user = Database::escape_string($survey_invitation['user']);
786
787
        if (isset($_POST['personality'])) {
788
            // Compute the results to get the 3 groups nearest to the user's personality
789
            if ($shuffle == '') {
790
                $order = 'BY sort ASC ';
791
            } else {
792
                $order = $shuffle;
793
            }
794
            $answer_list = [];
795
            // Get current user results
796
            $results = [];
797
            $sql = "SELECT 
798
                      survey_group_pri, 
799
                      user, 
800
                      SUM(value) as value
801
                    FROM $table_survey_answer as survey_answer
802
                    INNER JOIN $table_survey_question as survey_question
803
                    ON (survey_question.question_id = survey_answer.question_id)
804
                    WHERE
805
                        survey_answer.survey_id='".$my_survey_id."' AND
806
                        survey_answer.user='".$current_user."' AND
807
                        survey_answer.c_id = $course_id AND
808
                        survey_question.c_id = $course_id AND
809
                    GROUP BY survey_group_pri
810
                    ORDER BY survey_group_pri
811
                    ";
812
813
            $result = Database::query($sql);
814
            while ($row = Database :: fetch_array($result)) {
815
                $answer_list['value'] = $row['value'];
816
                $answer_list['group'] = $row['survey_group_pri'];
817
                $results[] = $answer_list;
818
            }
819
            //echo '<br />'; print_r($results); echo '<br />';
820
            // Get the total score for each group of questions
821
            $totals = [];
822
            $sql = "SELECT SUM(temp.value) as value, temp.survey_group_pri FROM
823
                    (
824
                        SELECT
825
                            MAX(value) as value,
826
                            survey_group_pri,
827
                            survey_question.question_id
828
                        FROM $table_survey_question as survey_question
829
                        INNER JOIN $table_survey_question_option as survey_question_option
830
                        ON (survey_question.question_id = survey_question_option.question_id)
831
                        WHERE
832
                            survey_question.survey_id='".$my_survey_id."'  AND
833
                            survey_question.c_id = $course_id AND
834
                            survey_question_option.c_id = $course_id AND
835
                            survey_group_sec1='0' AND
836
                            survey_group_sec2='0'
837
                        GROUP BY survey_group_pri, survey_question.question_id
838
                    ) as temp
839
                    GROUP BY temp.survey_group_pri
840
                    ORDER BY temp.survey_group_pri";
841
842
            $result = Database::query($sql);
843
            while ($row = Database::fetch_array($result)) {
844
                $list['value'] = $row['value'];
845
                $list['group'] = $row['survey_group_pri'];
846
                $totals[] = $list;
847
            }
848
            $final_results = [];
849
            // Get a percentage score for each group
850
            for ($i = 0; $i < count($totals); $i++) {
851
                for ($j = 0; $j < count($results); $j++) {
852
                    if ($totals[$i]['group'] == $results[$j]['group']) {
853
                        $group = $totals[$i]['group'];
854
                        $porcen = ($results[$j]['value'] / $totals[$i]['value']);
855
                        $final_results[$group] = $porcen;
856
                    }
857
                }
858
            }
859
860
            // Sort the results by score (getting a list of group IDs by score into $groups)
861
            arsort($final_results);
862
            $groups = array_keys($final_results);
863
            $result = [];
864
            $count_result = 0;
865
            foreach ($final_results as $key => &$sub_result) {
866
                $result[] = ['group' => $key, 'value' => $sub_result];
867
                $count_result++;
868
            }
869
870
            /*
871
              //i.e 70% - 70% -70% 70%  $equal_count =3
872
              while (1) {
873
              if ($result[$i]['value']  == $result[$i+1]['value']) {
874
              $equal_count++;
875
              } else {
876
              break;
877
              }
878
              $i++;
879
              }
880
              echo 'eq'. $equal_count;
881
              echo '<br />';
882
              if     ($equal_count == 0) {
883
              //i.e 70% 70% -60% 60%  $equal_count = 1 only we get the first 2 options
884
              if (($result[0]['value'] == $result[1]['value'])  &&  ($result[2]['value'] == $result[3]['value'])) {
885
              $group_cant = 1;
886
              } else {
887
              // By default we chose the highest 3
888
              $group_cant=2;
889
              }
890
              } elseif ($equal_count == 2) {
891
              $group_cant = 2;
892
              } else {
893
              $group_cant = -1;
894
              }
895
             */
896
897
            // i.e 70% - 70% -70% 70%  $equal_count =3
898
            $i = 0;
899
            $group_cant = 0;
900
            $equal_count = 0;
901
            // This is the case if the user does not select any question
902
            if ($count_result > 0) {
903
                // Count the number of scores equal to the first
904
                while (1) {
905
                    if ($result[$i]['value'] == $result[$i + 1]['value']) {
906
                        $equal_count++;
907
                    } else {
908
                        break;
909
                    }
910
                    $i++;
911
                }
912
            } else {
913
                // We force the exit of the survey undeterminated
914
                $equal_count = 10;
915
            }
916
917
            // If we have only 3 or less equal scores (i.e. 0,1 or 2 equalities), then we can use the three first groups
918
            if ($equal_count < 4) {
919
                // If there is one or less score equalities
920
                if ($equal_count === 0 || $equal_count === 1) {
921
                    // i.e 70% - 70% -60% - 60%  $equal_count = 1 we only get the first 2 options
922
                    if (($result[0]['value'] == $result[1]['value']) &&
923
                        ($result[2]['value'] == $result[3]['value'])
924
                    ) {
925
                        $group_cant = 1;
926
                    } elseif (($result[0]['value'] != $result[1]['value']) &&
927
                        ($result[1]['value'] == $result[2]['value']) && ($result[2]['value'] == $result[3]['value'])
928
                    ) {
929
                        // i.e 70% - 70% -0% - 0%     -    $equal_count = 0 we only get the first 2 options
930
                        /* elseif (($result[0]['value'] == $result[1]['value']) && ($result[1]['value'] != $result[2]['value'])) {
931
                          $group_cant = 0;
932
                          } */
933
                        /*
934
                          // i.e 70% - 70% -60% - 60%  $equal_count = 0 we only get the first 2 options
935
                          elseif (($result[0]['value'] == $result[1]['value'])  &&  ($result[2]['value'] == $result[3]['value'])) {
936
                          $group_cant = 0;
937
                          } */
938
                        // i.e. 80% - 70% - 70% - 70%
939
                        $group_cant = 0;
940
                    } else {
941
                        // i.e. 80% - 70% - 70% - 50
942
                        // i.e. 80% - 80% - 70% - 50
943
                        // By default we choose the highest 3
944
                        $group_cant = 2;
945
                    }
946
                } else {
947
                    // If there are two score equalities
948
                    $group_cant = $equal_count;
949
                }
950
951
                //@todo Translate these comments.
952
                // conditional_status
953
                // 0 no determinado
954
                // 1 determinado
955
                // 2 un solo valor
956
                // 3 valores iguales
957
                if ($group_cant > 0) {
958
                    //echo '$equal_count'.$group_cant;
959
                    // We only get highest 3
960
                    $secondary = '';
961
                    $combi = '';
962
                    for ($i = 0; $i <= $group_cant; $i++) {
963
                        $group1 = $groups[$i];
964
                        $group2 = $groups[$i + 1];
965
                        // Here we made all the posibilities with the 3 groups
966
                        if ($group_cant == 2 && $i == $group_cant) {
967
                            $group2 = $groups[0];
968
                            $secondary .= " OR ( survey_group_sec1 = '$group1' AND  survey_group_sec2 = '$group2') ";
969
                            $secondary .= " OR ( survey_group_sec1 = '$group2' AND survey_group_sec2 = '$group1' ) ";
970
                            $combi .= $group1.' - '.$group2." or ".$group2.' - '.$group1.'<br />';
971
                        } else {
972
                            if ($i != 0) {
973
                                $secondary .= " OR ( survey_group_sec1 = '$group1' AND  survey_group_sec2 = '$group2') ";
974
                                $secondary .= " OR ( survey_group_sec1 = '$group2' AND survey_group_sec2 = '$group1' ) ";
975
                                $combi .= $group1.' - '.$group2." or ".$group2.' - '.$group1.'<br />';
976
                            } else {
977
                                $secondary .= " ( survey_group_sec1 = '$group1' AND  survey_group_sec2 = '$group2') ";
978
                                $secondary .= " OR ( survey_group_sec1 = '$group2' AND survey_group_sec2 = '$group1' ) ";
979
                                $combi .= $group1.' - '.$group2." or ".$group2.' - '.$group1.'<br />';
980
                            }
981
                        }
982
                    }
983
                    // Create the new select with the questions from the secondary phase
984
                    if (empty($_SESSION['page_questions_sec']) &&
985
                        !is_array($_SESSION['page_questions_sec']) &&
986
                        count($_SESSION['page_questions_sec'] == 0)
987
                    ) {
988
                        $sql = "SELECT * FROM $table_survey_question
989
                                 WHERE
990
                                    c_id = $course_id AND
991
                                    survey_id = '".$my_survey_id."' AND
992
                                    ($secondary )
993
                                 ORDER BY sort ASC";
994
                        $result = Database::query($sql);
995
                        $counter = 0;
996
                        while ($row = Database::fetch_array($result, 'ASSOC')) {
997
                            if ($survey_data['one_question_per_page'] == 1) {
998
                                $paged_questions_sec[$counter][] = $row['question_id'];
999
                                $counter++;
1000
                            } elseif ($row['type'] == 'pagebreak') {
1001
                                $counter++;
1002
                            } else {
1003
                                // ids from question of the current survey
1004
                                $paged_questions_sec[$counter][] = $row['question_id'];
1005
                            }
1006
                        }
1007
                        Session::write('page_questions_sec', $paged_questions_sec);
1008
                    } else {
1009
                        $paged_questions_sec = Session::read('page_questions_sec');
1010
                    }
1011
                    $paged_questions = Session::read('paged_questions'); // For the sake of pages counting
1012
                    if ($shuffle == '') {
1013
                        $shuffle = ' BY survey_question.sort, survey_question_option.sort ASC ';
1014
                    }
1015
                    $val = (int) $_POST['personality'];
1016
                    if (is_array($paged_questions_sec)) {
1017
                        $sql = "SELECT
1018
                                    survey_question.survey_group_sec1,
1019
                                    survey_question.survey_group_sec2,
1020
                                    survey_question.survey_group_pri,
1021
                                    survey_question.question_id,
1022
                                    survey_question.survey_id,
1023
                                    survey_question.survey_question,
1024
                                    survey_question.display,
1025
                                    survey_question.sort,
1026
                                    survey_question.type,
1027
                                    survey_question.max_value,
1028
                                    survey_question_option.question_option_id,
1029
                                    survey_question_option.option_text,
1030
                                    survey_question_option.sort as option_sort
1031
                                FROM $table_survey_question survey_question
1032
                                LEFT JOIN $table_survey_question_option survey_question_option
1033
                                ON survey_question.question_id = survey_question_option.question_id AND
1034
                                survey_question_option.c_id = $course_id
1035
                                WHERE
1036
                                    survey_question NOT LIKE '%{{%' AND 
1037
                                    survey_question.survey_id = '".$my_survey_id."' AND
1038
                                    survey_question.c_id = $course_id AND
1039
                                    survey_question.question_id IN (".implode(',', $paged_questions_sec[$val]).")
1040
                                ORDER  $shuffle ";
1041
1042
                        $result = Database::query($sql);
1043
                        $question_counter_max = Database::num_rows($result);
1044
                        $counter = 0;
1045
                        $limit = 0;
1046
                        $questions = [];
1047
                        while ($row = Database::fetch_array($result, 'ASSOC')) {
1048
                            // If the type is not a pagebreak we store it in the $questions array
1049
                            if ($row['type'] != 'pagebreak') {
1050
                                $questions[$row['sort']]['question_id'] = $row['question_id'];
1051
                                $questions[$row['sort']]['survey_id'] = $row['survey_id'];
1052
                                $questions[$row['sort']]['survey_question'] = $row['survey_question'];
1053
                                $questions[$row['sort']]['display'] = $row['display'];
1054
                                $questions[$row['sort']]['type'] = $row['type'];
1055
                                $questions[$row['sort']]['options'][$row['question_option_id']] = $row['option_text'];
1056
                                $questions[$row['sort']]['maximum_score'] = $row['max_value'];
1057
                                // Personality params
1058
                                $questions[$row['sort']]['survey_group_sec1'] = $row['survey_group_sec1'];
1059
                                $questions[$row['sort']]['survey_group_sec2'] = $row['survey_group_sec2'];
1060
                                $questions[$row['sort']]['survey_group_pri'] = $row['survey_group_pri'];
1061
                                $questions[$row['sort']]['sort'] = $row['sort'];
1062
                            } else {
1063
                                // If the type is a pagebreak we are finished loading the questions for this page
1064
                                break;
1065
                            }
1066
                            $counter++;
1067
                        }
1068
                    } else {
1069
                        echo get_lang('SurveyUndetermined');
1070
                    }
1071
                } else {
1072
                    echo get_lang('SurveyUndetermined');
1073
                }
1074
            } else {
1075
                echo get_lang('SurveyUndetermined');
1076
            }
1077
        } else {
1078
            // We need this variable only in the 2nd set of questions when personality is set.
1079
            Session::erase('page_questions_sec');
1080
            $paged_questions_sec = [];
1081
1082
            // Only the questions from the basic group
1083
            // the 50 questions A B C D E F G
1084
            $order_sql = $shuffle;
1085
            if ($shuffle == '') {
1086
                $order_sql = ' BY question_id ';
1087
            }
1088
1089
            if (empty($_SESSION['paged_questions'])) {
1090
                $sql = "SELECT * FROM $table_survey_question
1091
                        WHERE
1092
                            c_id = $course_id AND
1093
                            survey_id = '".intval($survey_invitation['survey_id'])."' AND
1094
                            survey_group_sec1='0' AND
1095
                            survey_group_sec2='0'
1096
                        ORDER ".$order_sql." ";
1097
                $result = Database::query($sql);
1098
                $counter = 0;
1099
                while ($row = Database::fetch_array($result, 'ASSOC')) {
1100
                    if ($survey_data['one_question_per_page'] == 1) {
1101
                        $paged_questions[$counter][] = $row['question_id'];
1102
                        $counter++;
1103
                    } else {
1104
                        if ($row['type'] == 'pagebreak') {
1105
                            $counter++;
1106
                        } else {
1107
                            // ids from question of the current survey
1108
                            $paged_questions[$counter][] = $row['question_id'];
1109
                        }
1110
                    }
1111
                }
1112
                Session::write('paged_questions', $paged_questions);
1113
            } else {
1114
                $paged_questions = Session::read('paged_questions');
1115
            }
1116
            $order_sql = $shuffle;
1117
            if ($shuffle == '') {
1118
                $order_sql = ' BY survey_question.sort, survey_question_option.sort ASC ';
1119
            }
1120
            $val = $_GET['show'];
1121
            $result = null;
1122
            if ($val != '') {
1123
                $imploded = Database::escape_string(implode(',', $paged_questions[$val]));
1124
                if ($imploded != '') {
1125
                    // The answers are always in the same order NO shuffle
1126
                    $order_sql = ' BY survey_question.sort, survey_question_option.sort ASC ';
1127
                    $sql = "SELECT
1128
                                survey_question.survey_group_sec1,
1129
                                survey_question.survey_group_sec2,
1130
                                survey_question.survey_group_pri,
1131
                                survey_question.question_id,
1132
                                survey_question.survey_id,
1133
                                survey_question.survey_question,
1134
                                survey_question.display,
1135
                                survey_question.sort,
1136
                                survey_question.type,
1137
                                survey_question.max_value,
1138
                                survey_question_option.question_option_id,
1139
                                survey_question_option.option_text,
1140
                                survey_question_option.sort as option_sort
1141
                                ".($allowRequiredSurveyQuestions ? ', survey_question.is_required' : '')."
1142
                            FROM $table_survey_question survey_question
1143
                            LEFT JOIN $table_survey_question_option survey_question_option
1144
                            ON survey_question.question_id = survey_question_option.question_id AND
1145
                            survey_question_option.c_id = $course_id
1146
                            WHERE
1147
                                survey_question NOT LIKE '%{{%' AND 
1148
                                survey_question.survey_id = '".intval($survey_invitation['survey_id'])."' AND
1149
                                survey_question.c_id = $course_id  AND
1150
                                survey_question.question_id IN (".$imploded.")
1151
                            ORDER $order_sql ";
1152
                    $result = Database::query($sql);
1153
                    $question_counter_max = Database :: num_rows($result);
1154
                }
1155
            }
1156
1157
            if (!is_null($result)) {
1158
                $counter = 0;
1159
                $limit = 0;
1160
                $questions = [];
1161
                while ($row = Database :: fetch_array($result, 'ASSOC')) {
1162
                    // If the type is not a pagebreak we store it in the $questions array
1163
                    if ($row['type'] != 'pagebreak') {
1164
                        $questions[$row['sort']]['question_id'] = $row['question_id'];
1165
                        $questions[$row['sort']]['survey_id'] = $row['survey_id'];
1166
                        $questions[$row['sort']]['survey_question'] = $row['survey_question'];
1167
                        $questions[$row['sort']]['display'] = $row['display'];
1168
                        $questions[$row['sort']]['type'] = $row['type'];
1169
                        $questions[$row['sort']]['options'][$row['question_option_id']] = $row['option_text'];
1170
                        $questions[$row['sort']]['maximum_score'] = $row['max_value'];
1171
                        $questions[$row['sort']]['is_required'] = $allowRequiredSurveyQuestions && $row['is_required'];
1172
                        // Personality params
1173
                        $questions[$row['sort']]['survey_group_sec1'] = $row['survey_group_sec1'];
1174
                        $questions[$row['sort']]['survey_group_sec2'] = $row['survey_group_sec2'];
1175
                        $questions[$row['sort']]['survey_group_pri'] = $row['survey_group_pri'];
1176
                        $questions[$row['sort']]['sort'] = $row['sort'];
1177
                    } else {
1178
                        // If the type is a page break we are finished loading the questions for this page
1179
                        //break;
1180
                    }
1181
                    $counter++;
1182
                }
1183
            }
1184
        }
1185
    } else { // In case it's another type than 0 or 1
1186
        echo get_lang('ErrorSurveyTypeUnknown');
1187
    }
1188
}
1189
1190
$numberOfPages = SurveyManager::getCountPages($survey_data);
1191
// Selecting the maximum number of pages
1192
// Displaying the form with the questions
1193
$show = 0;
1194
if (isset($_GET['show']) && $_GET['show'] != '') {
1195
    $show = (int) $_GET['show'] + 1;
1196
}
1197
1198
$displayFinishButton = true;
1199
if (isset($_GET['show']) && $_GET['show'] != '') {
1200
    $pagesIndexes = array_keys($paged_questions);
1201
    $pagesIndexes[] = count($pagesIndexes);
1202
1203
    if (end($pagesIndexes) <= $show - 1 && empty($_POST)) {
1204
        $displayFinishButton = false;
1205
    }
1206
}
1207
1208
// Displaying the form with the questions
1209
$personality = 0;
1210
if (isset($_POST['personality'])) {
1211
    $personality = (int) $_POST['personality'] + 1;
1212
}
1213
1214
// Displaying the form with the questions
1215
$g_c = isset($_GET['course']) ? Security::remove_XSS($_GET['course']) : '';
1216
$g_ic = isset($_GET['invitationcode']) ? Security::remove_XSS($_GET['invitationcode']) : '';
1217
$g_cr = isset($_GET['cidReq']) ? Security::remove_XSS($_GET['cidReq']) : '';
1218
$p_l = isset($_POST['language']) ? Security::remove_XSS($_POST['language']) : '';
1219
$add_parameters = isset($_GET['user_id']) ? '&user_id='.intval($_GET['user_id']) : '';
1220
$url = api_get_self().'?cidReq='.$courseInfo['code'].
1221
    '&id_session='.$sessionId.
1222
    $add_parameters.
1223
    '&course='.$g_c.
1224
    '&invitationcode='.$g_ic.
1225
    '&show='.$show;
1226
$form = new FormValidator(
1227
    'question',
1228
    'post',
1229
    $url,
1230
    null,
1231
    null,
1232
    FormValidator::LAYOUT_INLINE
1233
);
1234
$form->addHidden('language', $p_l);
1235
1236
if (isset($questions) && is_array($questions)) {
1237
    $originalShow = isset($_GET['show']) ? (int) $_GET['show'] : 0;
1238
    $questionCounter = 1;
1239
    if (!empty($originalShow)) {
1240
        $before = 0;
1241
        foreach ($paged_questions as $keyQuestion => $list) {
1242
            if ($originalShow > $keyQuestion) {
1243
                $before += count($list);
1244
            }
1245
        }
1246
        $questionCounter = $before + 1;
1247
    }
1248
1249
    foreach ($questions as $key => &$question) {
1250
        $ch_type = 'ch_'.$question['type'];
1251
        $questionNumber = $questionCounter;
1252
        $display = new $ch_type();
1253
        // @todo move this in a function.
1254
        $form->addHtml('<div class="survey_question '.$ch_type.'">');
1255
        $form->addHtml('<div style="float:left; font-weight: bold; margin-right: 5px;"> '.$questionNumber.'. </div>');
1256
        $form->addHtml('<div>'.Security::remove_XSS($question['survey_question']).'</div> ');
1257
1258
        $userAnswerData = SurveyUtil::get_answers_of_question_by_user($question['survey_id'], $question['question_id']);
1259
        $finalAnswer = null;
1260
1261
        if (!empty($userAnswerData[$user_id])) {
1262
            $userAnswer = $userAnswerData[$user_id];
1263
            switch ($question['type']) {
1264
                case 'score':
1265
                    $finalAnswer = [];
1266
                    foreach ($userAnswer as $userChoice) {
1267
                        list($choiceId, $choiceValue) = explode('*', $userChoice);
1268
1269
                        $finalAnswer[$choiceId] = $choiceValue;
1270
                    }
1271
                    break;
1272
                case 'percentage':
1273
                    list($choiceId, $choiceValue) = explode('*', current($userAnswer));
1274
1275
                    $finalAnswer = $choiceId;
1276
                    break;
1277
                default:
1278
                    $finalAnswer = $userAnswer;
1279
                    break;
1280
            }
1281
        }
1282
        $display->render($form, $question, $finalAnswer);
1283
        $form->addHtml('</div>');
1284
        $questionCounter++;
1285
    }
1286
}
1287
1288
$form->addHtml('<div class="start-survey">');
1289
if ($survey_data['survey_type'] == '0') {
1290
    if ($survey_data['show_form_profile'] == 0) {
1291
        // The normal survey as always
1292
        if ($show < $numberOfPages) {
1293
            if ($show == 0) {
1294
                $form->addButton(
1295
                    'next_survey_page',
1296
                    get_lang('StartSurvey'),
1297
                    'arrow-right',
1298
                    'success'
1299
                );
1300
            } else {
1301
                $form->addButton(
1302
                    'next_survey_page',
1303
                    get_lang('Next'),
1304
                    'arrow-right',
1305
                    'success'
1306
                );
1307
            }
1308
        }
1309
        if ($show >= $numberOfPages && $displayFinishButton) {
1310
            $form->addButton(
1311
                'finish_survey',
1312
                get_lang('FinishSurvey'),
1313
                'arrow-right',
1314
                'success'
1315
            );
1316
        }
1317
    } else {
1318
        // The normal survey as always but with the form profile
1319
        if (isset($_GET['show'])) {
1320
            $numberOfPages = count($paged_questions);
1321
            if ($show < $numberOfPages) {
1322
                if ($show == 0) {
1323
                    $form->addButton(
1324
                        'next_survey_page',
1325
                        get_lang('StartSurvey'),
1326
                        'arrow-right',
1327
                        'success'
1328
                    );
1329
                } else {
1330
                    $form->addButton(
1331
                        'next_survey_page',
1332
                        get_lang('Next'),
1333
                        'arrow-right',
1334
                        'success'
1335
                    );
1336
                }
1337
            }
1338
1339
            if ($show >= $numberOfPages && $displayFinishButton) {
1340
                $form->addButton(
1341
                    'finish_survey',
1342
                    get_lang('FinishSurvey'),
1343
                    'arrow-right',
1344
                    'success'
1345
                );
1346
            }
1347
        }
1348
    }
1349
} elseif ($survey_data['survey_type'] == '1') {
1350
    //conditional/personality-test type survey
1351
    if (isset($_GET['show']) || isset($_POST['personality'])) {
1352
        $numberOfPages = count($paged_questions);
1353
        if (!empty($paged_questions_sec) && count($paged_questions_sec) > 0) {
1354
            // In case we're in the second phase, also sum the second group questions
1355
            $numberOfPages += count($paged_questions_sec);
1356
        } else {
1357
            // We need this variable only if personality == 1
1358
            Session::erase('page_questions_sec');
1359
            $paged_questions_sec = [];
1360
        }
1361
1362
        if ($personality == 0) {
1363
            if (($show <= $numberOfPages) || !$_GET['show']) {
1364
                $form->addButton('next_survey_page', get_lang('Next'), 'arrow-right', 'success');
1365
                if ($survey_data['one_question_per_page'] == 0) {
1366
                    if ($personality >= 0) {
1367
                        $form->addHidden('personality', $personality);
1368
                    }
1369
                } else {
1370
                    if ($personality > 0) {
1371
                        $form->addHidden('personality', $personality);
1372
                    }
1373
                }
1374
1375
                if ($numberOfPages == $show) {
1376
                    $form->addHidden('personality', $personality);
1377
                }
1378
            }
1379
        }
1380
1381
        if ($show > $numberOfPages && $_GET['show'] && $personality == 0) {
1382
            $form->addHidden('personality', $personality);
1383
        } elseif ($personality > 0) {
1384
            if ($survey_data['one_question_per_page'] == 1) {
1385
                if ($show >= $numberOfPages) {
1386
                    $form->addButton('finish_survey', get_lang('FinishSurvey'), 'arrow-right', 'success');
1387
                } else {
1388
                    $form->addHidden('personality', $personality);
1389
                    $form->addButton('next_survey_page', get_lang('Next'), 'arrow-right', 'success');
1390
                }
1391
            } else {
1392
                // if the personality test hidden input was set.
1393
                $form->addButton('finish_survey', get_lang('FinishSurvey'), 'arrow-right');
1394
            }
1395
        }
1396
    } elseif ($survey_data['form_fields'] == '') {
1397
        // This is the case when the show_profile_form is true but there are not form_fields
1398
        $form->addButton('next_survey_page', get_lang('Next'), 'arrow-right', 'success');
1399
    } elseif (!is_array($user_data)) {
1400
        // If the user is not registered in the platform we do not show the form to update his information
1401
        $form->addButton('next_survey_page', get_lang('Next'), 'arrow-right', 'success');
1402
    }
1403
}
1404
$form->addHtml('</div>');
1405
$form->display();
1406
Display::display_footer();
1407