Issues (1796)

public/main/survey/fillsurvey.php (2 issues)

Labels
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Framework\Container;
6
use Chamilo\CourseBundle\Entity\CSurvey;
7
use ChamiloSession as Session;
8
9
$lastQuestion = 0;
10
11
/**
12
 * @author unknown, the initial survey that did not make it in 1.8 because of bad code
13
 * @author Patrick Cool <[email protected]>, Ghent University: cleanup,
14
 * refactoring and rewriting large parts of the code
15
 * @author Julio Montoya <[email protected]>, Chamilo: Personality Test
16
 * modification and rewriting large parts of the code as well
17
 *
18
 * @todo check if the user already filled the survey and if this
19
 * is the case then the answers have to be updated and not stored again.
20
 * @todo performance could be improved if not the survey_id was
21
 * stored with the invitation but the survey_code
22
 */
23
24
// Unsetting the course id (because it is in the URL)
25
if (!isset($_GET['cidReq'])) {
26
    $cidReset = true;
27
} else {
28
    $_cid = $_GET['cidReq'];
29
}
30
31
require_once __DIR__.'/../inc/global.inc.php';
32
33
// Database table definitions
34
$table_survey = Database::get_course_table(TABLE_SURVEY);
35
$table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
36
$table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
37
$table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
38
$table_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
39
$table_user = Database::get_main_table(TABLE_MAIN_USER);
40
41
$allowRequiredSurveyQuestions = true;
42
43
// Check if user is anonymous or not
44
$isAnonymous = false;
45
if (api_is_anonymous(api_get_user_id(), true)) {
46
    $isAnonymous = true;
47
}
48
49
// getting all the course information
50
if (isset($_GET['course'])) {
51
    $courseInfo = api_get_course_info($_GET['course']);
52
} else {
53
    $courseInfo = api_get_course_info();
54
}
55
56
if (empty($courseInfo)) {
57
    api_not_allowed(true);
58
}
59
60
$courseId = $courseInfo['real_id'];
61
$userInfo = api_get_user_info();
62
$sessionId = isset($_GET['sid']) ? (int) $_GET['sid'] : api_get_session_id();
63
$lpItemId = isset($_GET['lp_item_id']) ? (int) $_GET['lp_item_id'] : 0;
64
$allowSurveyInLp = true;
65
66
if (!empty($userInfo)) {
67
    $interbreadcrumb[] = [
68
        'url' => api_get_path(WEB_CODE_PATH).'survey/survey_list.php?cid='.$courseId.'&sid='.$sessionId,
69
        'name' => get_lang('Survey list'),
70
    ];
71
}
72
73
// First we check if the needed parameters are present
74
if ((!isset($_GET['course']) || !isset($_GET['invitationcode'])) && !isset($_GET['user_id'])) {
75
    api_not_allowed(true, get_lang('There is a parameter missing in the link. Please use copy and past'));
76
}
77
78
$repo = Container::getSurveyRepository();
79
$surveyId = isset($_GET['iid']) ? (int) $_GET['iid'] : 0;
80
81
if (empty($surveyId) && (isset($_POST['language']) && is_numeric($_POST['language']))) {
82
    $surveyId = (int) $_POST['language'];
83
}
84
85
/** @var CSurvey $survey */
86
$survey = $repo->find($surveyId);
87
if (null === $survey) {
88
    api_not_allowed(true);
89
}
90
91
$surveyId = $survey->getIid();
92
$invitationCode = $_GET['invitationcode'] ?? null;
93
94
$lpItemCondition = '';
95
if ($allowSurveyInLp && !empty($lpItemId)) {
96
    $lpItemCondition = " AND c_lp_item_id = $lpItemId";
97
}
98
99
$sessionCondition = '';
100
if (true === api_get_setting('survey.show_surveys_base_in_sessions')) {
101
    $sessionCondition = api_get_session_condition($sessionId);
102
}
103
104
/*$surveyCode = isset($_GET['scode']) ? Database::escape_string($_GET['scode']) : '';
105
if ('' != $surveyCode) {
106
    // Firstly we check if this survey is ready for anonymous use:
107
    $sql = "SELECT anonymous FROM $table_survey
108
            WHERE c_id = $courseId AND code ='".$surveyCode."'";
109
    $resultAnonymous = Database::query($sql);
110
    $rowAnonymous = Database::fetch_assoc($resultAnonymous);
111
    // If is anonymous and is not allowed to take the survey to anonymous users, forbid access:
112
    if (!isset($rowAnonymous['anonymous']) ||
113
        (0 == $rowAnonymous['anonymous'] && api_is_anonymous()) ||
114
        0 == count($rowAnonymous)
115
    ) {
116
        api_not_allowed(true);
117
    }
118
    // If is anonymous and it is allowed to take the survey as anonymous, mark survey as anonymous.
119
}*/
120
121
if ((0 == $survey->getAnonymous() && api_is_anonymous())) {
122
    api_not_allowed(true);
123
}
124
125
// Start auto-invitation feature FS#3403 (all-users-can-do-the-survey-URL handling)
126
if ('auto' === $invitationCode) {
127
    $userid = api_get_user_id();
128
    // Survey_code of the survey
129
    $surveyCode = $survey->getCode();
130
    if ($isAnonymous) {
131
        $autoInvitationCode = 'auto-ANONY_'.md5(time())."-$surveyCode";
132
    } else {
133
        $invitations = SurveyManager::getUserInvitationsForSurveyInCourse(
134
            $userid,
135
            $surveyCode,
136
            $courseId,
137
            $sessionId,
138
            0,
139
            $lpItemId
140
        );
141
        $lastInvitation = current($invitations);
142
143
        if (!$lastInvitation) {
144
            // New invitation code from userid
145
            $autoInvitationCode = "auto-$userid-$surveyCode";
146
        } else {
147
            $autoInvitationCode = $lastInvitation->getInvitationCode();
148
        }
149
    }
150
151
    // Check availability.
152
    SurveyManager::checkTimeAvailability($survey);
153
154
    // Check for double invitation records (insert should be done once)
155
    $sql = "SELECT user_id
156
            FROM $table_survey_invitation
157
            WHERE
158
                c_id = $courseId AND
159
                invitation_code = '".Database::escape_string($autoInvitationCode)."'
160
                $sessionCondition
161
                $lpItemCondition";
162
    $result = Database::query($sql);
163
    $now = api_get_utc_datetime();
164
    if (0 == Database::num_rows($result)) {
165
        $params = [
166
            'c_id' => $courseId,
167
            'survey_id' => $surveyId,
168
            'user_id' => $userid,
169
            'invitation_code' => $autoInvitationCode,
170
            'invitation_date' => $now,
171
            'answered' => 0,
172
            'c_lp_item_id' => $lpItemId,
173
        ];
174
        Database::insert($table_survey_invitation, $params);
175
    }
176
    // From here we use the new invitationcode auto-userid-surveycode string
177
    $_GET['invitationcode'] = $autoInvitationCode;
178
    Session::write('auto_invitation_code_'.$surveyCode, $autoInvitationCode);
179
    $invitationCode = $autoInvitationCode;
180
}
181
182
// Now we check if the invitation code is valid
183
$sql = "SELECT * FROM $table_survey_invitation
184
        WHERE
185
            c_id = $courseId AND
186
            invitation_code = '".Database::escape_string($invitationCode)."'
187
            $sessionCondition
188
            $lpItemCondition";
189
$result = Database::query($sql);
190
if (Database::num_rows($result) < 1) {
191
    api_not_allowed(true, get_lang('Wrong invitation code'));
192
}
193
194
$survey_invitation = Database::fetch_assoc($result);
195
$surveyUserFromSession = Session::read('surveyuser');
196
// Now we check if the user already filled the survey
197
if (!isset($_POST['finish_survey']) &&
0 ignored issues
show
Consider adding parentheses for clarity. Current Interpretation: (! IssetNode && $isAnony...swered'] && ! IssetNode, Probably Intended Meaning: ! IssetNode && ($isAnony...wered'] && ! IssetNode)
Loading history...
198
    (
199
        $isAnonymous &&
200
        !empty($surveyUserFromSession) &&
201
        SurveyUtil::isSurveyAnsweredFlagged($survey->getCode(), $survey_invitation['c_id'])
202
    ) ||
203
    (1 == $survey_invitation['answered'] && !isset($_GET['user_id']))
204
) {
205
    api_not_allowed(true, Display::return_message(get_lang('You already filled this survey')));
206
}
207
208
$logInfo = [
209
    'tool' => TOOL_SURVEY,
210
    'tool_id' => $survey_invitation['iid'],
211
    'action' => 'invitationcode',
212
    'action_details' => $invitationCode,
213
];
214
Event::registerLog($logInfo);
0 ignored issues
show
The method registerLog() does not exist on Event. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

214
Event::/** @scrutinizer ignore-call */ 
215
       registerLog($logInfo);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
215
216
$survey_invitation['survey_id'] = $surveyId;
217
218
// Checking time availability
219
SurveyManager::checkTimeAvailability($survey);
220
$surveyType = $survey->getSurveyType();
221
if (3 === $surveyType) {
222
    header('Location: '.
223
        api_get_path(WEB_CODE_PATH).
224
        'survey/meeting.php?cid='.$courseId.'&sid='.$sessionId.'&invitationcode='.Security::remove_XSS($invitationCode)
225
    );
226
    exit;
227
}
228
229
if (!empty($survey->getAnonymous())) {
230
    define('USER_IN_ANON_SURVEY', true);
231
}
232
233
// Storing the answers
234
if (count($_POST) > 0) {
235
    if (0 === $surveyType) {
236
        $types = [];
237
        $required = [];
238
        $questions = $survey->getQuestions();
239
        $questionList = [];
240
        foreach ($questions as $question) {
241
            $id = $question->getIid();
242
            $questionList[$id] = $question;
243
            $types[$id] = $question->getType();
244
            $required[$id] = $allowRequiredSurveyQuestions && $question->isMandatory();
245
        }
246
247
        // Looping through all the post values
248
        foreach ($_POST as $key => &$value) {
249
            // If the post value key contains the string 'question' then it is an answer on a question
250
            if (false === strpos($key, 'other_question') &&
251
                false !== strpos($key, 'question') && '_qf__question' !== $key
252
            ) {
253
                // Finding the question id by removing 'question'
254
                $survey_question_id = str_replace('question', '', $key);
255
                // If not question ID was defined, we're on the start
256
                // screen or something else that doesn't require
257
                // saving an answer
258
                if (empty($survey_question_id)) {
259
                    continue;
260
                }
261
262
                $other = isset($_POST['other_question'.$survey_question_id]) ? $_POST['other_question'.$survey_question_id] : '';
263
                $question = $questionList[$survey_question_id] ?? null;
264
265
                if (null === $question) {
266
                    continue;
267
                }
268
269
                /* If the post value is an array then we have a multiple response question or a scoring question type
270
                remark: when it is a multiple response then the value of the array is the option_id
271
                when it is a scoring question then the key of the array is the option_id and the value is the value
272
                */
273
                if (is_array($value)) {
274
                    SurveyUtil::remove_answer(
275
                        $survey_invitation['user_id'],
276
                        $surveyId,
277
                        $survey_question_id,
278
                        $lpItemId
279
                    );
280
281
                    foreach ($value as $answer_key => &$answer_value) {
282
                        if ('score' === $types[$survey_question_id]) {
283
                            $option_id = $answer_key;
284
                            $option_value = $answer_value;
285
                        } else {
286
                            $option_id = $answer_value;
287
                            $option_value = '';
288
                        }
289
290
                        SurveyUtil::saveAnswer(
291
                            $survey_invitation['user_id'],
292
                            $survey,
293
                            $question,
294
                            $option_id,
295
                            $option_value,
296
                            '',
297
                            $lpItemId
298
                        );
299
                    }
300
                } else {
301
                    // All the other question types (open question, multiple choice, percentage, ...)
302
                    $option_value = 0;
303
                    if (isset($types[$survey_question_id]) && 'percentage' === $types[$survey_question_id]) {
304
                        $sql = "SELECT * FROM $table_survey_question_option
305
                                WHERE
306
                                    iid='".intval($value)."'";
307
                        $result = Database::query($sql);
308
                        $row = Database::fetch_assoc($result);
309
                        if ($row) {
310
                            $option_value = $row['option_text'];
311
                        }
312
                    } else {
313
                        if (isset($types[$survey_question_id]) && 'open' === $types[$survey_question_id]) {
314
                            $option_value = $value;
315
                        }
316
                    }
317
318
                    $survey_question_answer = $value;
319
                    SurveyUtil::remove_answer(
320
                        $survey_invitation['user_id'],
321
                        $surveyId,
322
                        $survey_question_id,
323
                        $lpItemId
324
                    );
325
326
                    SurveyUtil::saveAnswer(
327
                        $survey_invitation['user_id'],
328
                        $survey,
329
                        $question,
330
                        $value,
331
                        $option_value,
332
                        $other,
333
                        $lpItemId
334
                    );
335
                }
336
            }
337
        }
338
    } elseif (1 === $survey->getSurveyType()) {
339
        //conditional/personality-test type surveys
340
        // Getting all the types of the question (because of the special treatment of the score question type
341
        $shuffle = '';
342
        if (1 == $survey->getShuffle()) {
343
            $shuffle = ' ORDER BY RAND() ';
344
        }
345
        /*$sql = "SELECT * FROM $table_survey_question
346
                WHERE
347
                    survey_id = $surveyId AND
348
                    survey_group_pri = '0'
349
                    $shuffle";
350
        $result = Database::query($sql);*/
351
        // There is only one question type for conditional surveys
352
        $types = [];
353
        //while ($row = Database::fetch_assoc($result)) {
354
        $questions = $survey->getQuestions();
355
        $questionList = [];
356
        foreach ($questions as $question) {
357
            $questionList[$question->getIid()] = $question;
358
        }
359
360
        // Looping through all the post values
361
        foreach ($_POST as $key => &$value) {
362
            // If the post value key contains the string 'question' then it is an answer to a question
363
            if (false !== strpos($key, 'question')) {
364
                // Finding the question id by removing 'question'
365
                $survey_question_id = str_replace('question', '', $key);
366
                // If not question ID was defined, we're on the start
367
                // screen or something else that doesn't require
368
                // saving an answer
369
                if (empty($survey_question_id)) {
370
                    continue;
371
                }
372
                // We select the correct answer and the puntuacion
373
                $sql = "SELECT value FROM $table_survey_question_option
374
                        WHERE iid='".intval($value)."'";
375
                $result = Database::query($sql);
376
                $row = Database::fetch_assoc($result);
377
                $option_value = $row['value'];
378
                $survey_question_answer = $value;
379
380
                // We save the answer after making sure that a possible previous attempt is deleted
381
                SurveyUtil::remove_answer(
382
                    $survey_invitation['user_id'],
383
                    $survey_invitation['survey_id'],
384
                    $survey_question_id,
385
                    $lpItemId
386
                );
387
388
389
                $surveyId = (int) $survey_invitation['survey_id'];
390
                $repo = Container::getSurveyRepository();
391
                $survey = $repo->find($surveyId);
392
393
                SurveyUtil::saveAnswer(
394
                    api_get_user_entity($survey_invitation['user_id']),
395
                    $survey,
396
                    $questionList[$survey_question_id],
397
                    $value,
398
                    $option_value,
399
                    '',
400
                    $lpItemId
401
                );
402
            }
403
        }
404
    } else {
405
        // In case it's another type than 0 or 1
406
        api_not_allowed(true, get_lang('Survey type unknown'));
407
    }
408
}
409
410
$user_id = api_get_user_id();
411
if (0 == $user_id) {
412
    $user_id = $survey_invitation['user_id'];
413
}
414
$user_data = api_get_user_info($user_id);
415
416
if ('' != $survey->getFormFields() &&
417
    0 == $survey->getAnonymous() &&
418
    is_array($user_data)
419
) {
420
    $form_fields = explode('@', $survey->getFormFields());
421
    $list = [];
422
    foreach ($form_fields as $field) {
423
        $field_value = explode(':', $field);
424
        if (isset($field_value[1]) && 1 == $field_value[1]) {
425
            if ('' != $field_value[0]) {
426
                $val = api_substr($field_value[0], 8, api_strlen($field_value[0]));
427
                $list[$val] = 1;
428
            }
429
        }
430
    }
431
432
    $url = api_get_self().'?'.api_get_cidreq();
433
    $listQueryParams = explode('&', $_SERVER['QUERY_STRING']);
434
    foreach ($listQueryParams as $param) {
435
        $url .= '&'.Security::remove_XSS($param);
436
    }
437
438
    if (!empty($lpItemId)) {
439
        $url .= '&lp_item_id='.$lpItemId;
440
    }
441
442
    // We use the same form as in auth/profile.php
443
    $form = new FormValidator('profile', 'post', $url);
444
    if (api_is_western_name_order()) {
445
        if (isset($list['firstname']) && 1 == $list['firstname']) {
446
            //FIRST NAME
447
            $form->addElement('text', 'firstname', get_lang('First name'), ['size' => 40]);
448
            if ('true' !== api_get_setting('profile', 'name')) {
449
                $form->freeze(['firstname']);
450
            }
451
            $form->applyFilter(['firstname'], 'stripslashes');
452
            $form->applyFilter(['firstname'], 'trim');
453
            $form->addRule('firstname', get_lang('Required field'), 'required');
454
        }
455
        if (isset($list['lastname']) && 1 == $list['lastname']) {
456
            //    LAST NAME
457
            $form->addElement('text', 'lastname', get_lang('Last name'), ['size' => 40]);
458
            if ('true' !== api_get_setting('profile', 'name')) {
459
                $form->freeze(['lastname']);
460
            }
461
            $form->applyFilter(['lastname'], 'stripslashes');
462
            $form->applyFilter(['lastname'], 'trim');
463
            $form->addRule('lastname', get_lang('Required field'), 'required');
464
        }
465
    } else {
466
        if (isset($list['lastname']) && 1 == $list['lastname']) {
467
            //    LAST NAME
468
            $form->addElement('text', 'lastname', get_lang('Last name'), ['size' => 40]);
469
            if ('true' !== api_get_setting('profile', 'name')) {
470
                $form->freeze(['lastname']);
471
            }
472
            $form->applyFilter(['lastname'], 'stripslashes');
473
            $form->applyFilter(['lastname'], 'trim');
474
            $form->addRule('lastname', get_lang('Required field'), 'required');
475
        }
476
        if (isset($list['firstname']) && 1 == $list['firstname']) {
477
            //FIRST NAME
478
            $form->addElement('text', 'firstname', get_lang('First name'), ['size' => 40]);
479
            if ('true' !== api_get_setting('profile', 'name')) {
480
                $form->freeze(['firstname']);
481
            }
482
            $form->applyFilter(['firstname'], 'stripslashes');
483
            $form->applyFilter(['firstname'], 'trim');
484
            $form->addRule('firstname', get_lang('Required field'), 'required');
485
        }
486
    }
487
488
    if (isset($list['official_code']) && 1 == $list['official_code']) {
489
        //    OFFICIAL CODE
490
        $form->addElement('text', 'official_code', get_lang('Code'), ['size' => 40]);
491
        if ('true' !== api_get_setting('profile', 'officialcode')) {
492
            $form->freeze('official_code');
493
        }
494
        $form->applyFilter('official_code', 'stripslashes');
495
        $form->applyFilter('official_code', 'trim');
496
        if ('true' === api_get_setting('registration', 'officialcode') &&
497
            'true' === api_get_setting('profile', 'officialcode')
498
        ) {
499
            $form->addRule('official_code', get_lang('Required field'), 'required');
500
        }
501
    }
502
503
    if (isset($list['email']) && 1 == $list['email']) {
504
        //    EMAIL
505
        $form->addElement('text', 'email', get_lang('e-mail'), ['size' => 40]);
506
        if ('true' !== api_get_setting('profile', 'email')) {
507
            $form->freeze('email');
508
        }
509
        $form->applyFilter('email', 'stripslashes');
510
        $form->applyFilter('email', 'trim');
511
        if ('true' === api_get_setting('registration', 'email')) {
512
            $form->addRule('email', get_lang('Required field'), 'required');
513
        }
514
        $form->addEmailRule('email');
515
    }
516
517
    if (isset($list['phone']) && 1 == $list['phone']) {
518
        // PHONE
519
        $form->addElement('text', 'phone', get_lang('Phone'), ['size' => 20]);
520
        if ('true' !== api_get_setting('profile', 'phone')) {
521
            $form->freeze('phone');
522
        }
523
        $form->applyFilter('phone', 'stripslashes');
524
        $form->applyFilter('phone', 'trim');
525
        if ('true' == api_get_setting('profile', 'phone')) {
526
            $form->addRule('phone', get_lang('Required field'), 'required');
527
        }
528
    }
529
530
    if (isset($list['language']) && 1 == $list['language']) {
531
        // LANGUAGE
532
        $form->addSelectLanguage('language', get_lang('Language'));
533
        if ('true' !== api_get_setting('profile', 'language')) {
534
            $form->freeze('language');
535
        }
536
        if ('true' === api_get_setting('profile', 'language')) {
537
            $form->addRule('language', get_lang('Required field'), 'required');
538
        }
539
    }
540
541
    // EXTRA FIELDS
542
    $extraField = new ExtraField('user');
543
    $returnParams = $extraField->addElements($form, api_get_user_id());
544
    $jquery_ready_content = $returnParams['jquery_ready_content'];
545
546
    // the $jquery_ready_content variable collects all functions
547
    // that will be load in the $(document).ready javascript function
548
    $htmlHeadXtra[] = '<script>
549
    $(function() {
550
        '.$jquery_ready_content.'
551
    });
552
    </script>';
553
554
    $form->addButtonNext(get_lang('Next'));
555
    $form->setDefaults($user_data);
556
}
557
558
//$htmlHeadXtra[] = '<script>'.api_get_language_translate_html().'</script>';
559
$htmlHeadXtra[] = ch_selectivedisplay::getJs();
560
$htmlHeadXtra[] = survey_question::getJs();
561
562
Display::display_header(get_lang('Surveys'));
563
564
// Displaying the survey title and subtitle (appears on every page)
565
echo '<div class="survey-block">';
566
echo '<div class="page-header">';
567
echo '<h2>';
568
echo strip_tags($survey->getTitle(), '<span>').'</h2></div>';
569
if (!empty($survey->getSubtitle())) {
570
    echo '<div class="survey_subtitle"><p>'.strip_tags($survey->getSubtitle()).'</p></div>';
571
}
572
573
// Displaying the survey introduction
574
if (
575
    !isset($_GET['show']) ||
576
    (isset($_GET['show'])) && '' == $_GET['show']) {
577
    // The first thing we do is delete the session
578
    Session::erase('paged_questions');
579
    Session::erase('page_questions_sec');
580
    $paged_questions_sec = [];
581
    if (!empty($survey->getIntro())) {
582
        echo '<div class="survey_content">'.Security::remove_XSS($survey->getIntro()).'</div>';
583
    }
584
    $limit = 0;
585
}
586
587
if ($survey->getFormFields() &&
588
    0 == $survey->getAnonymous() &&
589
    is_array($user_data) &&
590
    !isset($_GET['show'])
591
) {
592
    if ($form->validate()) {
593
        $user_data = $form->exportValues();
594
        if (is_array($user_data)) {
595
            if (count($user_data) > 0) {
596
                $extras = [];
597
                // Build SQL query
598
                $sql = "UPDATE $table_user SET";
599
                $update = false;
600
                $allowedFields = [
601
                    'firstname',
602
                    'lastname',
603
                    'official_code',
604
                    'email',
605
                    'phone',
606
                    'language',
607
                ];
608
609
                foreach ($user_data as $key => $value) {
610
                    if (in_array($key, $allowedFields)) {
611
                        $sql .= " $key = '".Database :: escape_string($value)."',";
612
                        $update = true;
613
                    }
614
                }
615
                // Remove trailing , from the query we have so far
616
                $sql = rtrim($sql, ',');
617
                $sql .= " WHERE id  = $user_id";
618
619
                if ($update) {
620
                    Database::query($sql);
621
                }
622
623
                $extraFieldValue = new ExtraFieldValue('user');
624
                $extraFieldValue->saveFieldValues($user_data);
625
                echo '<div id="survey_content" class="survey_content">'.
626
                    get_lang('Information updated').' '.get_lang('Please fill survey').'</div>';
627
            }
628
        }
629
        $_GET['show'] = 0;
630
        $show = 0;
631
        // We unset the sessions
632
        Session::erase('paged_questions');
633
        Session::erase('page_questions_sec');
634
        $paged_questions_sec = [];
635
    } else {
636
        echo '<div id="survey_content" class="survey_content">'.get_lang('Update information').'</div>';
637
        // We unset the sessions
638
        Session::erase('paged_questions');
639
        Session::erase('page_questions_sec');
640
        $paged_questions_sec = [];
641
        $form->display();
642
    }
643
}
644
645
// Displaying the survey thanks message
646
if (isset($_POST['finish_survey'])) {
647
    echo Display::return_message(get_lang('You have finished this survey.'), 'confirm');
648
    echo Security::remove_XSS($survey->getSurveythanks());
649
    SurveyManager::updateSurveyAnswered($survey, $survey_invitation['user_id'], $lpItemId);
650
    SurveyUtil::flagSurveyAsAnswered($survey->getCode(), $survey_invitation['c_id']);
651
652
    if ($courseInfo && !api_is_anonymous() && 'learnpath' !== api_get_origin()) {
653
        echo '<br /><br />';
654
        echo Display::toolbarButton(
655
            get_lang('Return to Course Homepage'),
656
            api_get_course_url($courseInfo['real_id']),
657
            'home-outline'
658
        );
659
    }
660
661
    Session::erase('paged_questions');
662
    Session::erase('page_questions_sec');
663
    Display::display_footer();
664
    exit();
665
}
666
667
// Sets the random questions
668
$shuffle = '';
669
if (1 == $survey->getShuffle()) {
670
    $shuffle = ' BY RAND() ';
671
}
672
673
$pageBreakText = [];
674
if ((isset($_GET['show']) && '' != $_GET['show']) ||
675
    isset($_POST['personality'])
676
) {
677
    // Getting all the questions for this page and add them to a
678
    // multidimensional array where the first index is the page.
679
    // As long as there is no pagebreak fount we keep adding questions to the page
680
    $questions_displayed = [];
681
    $counter = 0;
682
    $paged_questions = [];
683
    // If non-conditional survey
684
    $select = '';
685
    $select = ' survey_question.parent_id, survey_question.parent_option_id, ';
686
687
    // If non-conditional survey
688
    if (0 === $survey->getSurveyType()) {
689
        if (empty($paged_questions)) {
690
            $sql = "SELECT * FROM $table_survey_question
691
                    WHERE
692
                        survey_question NOT LIKE '%{{%' AND
693
                        survey_id = '".$surveyId."'
694
                    ORDER BY sort ASC";
695
            $result = Database::query($sql);
696
            while ($row = Database::fetch_assoc($result)) {
697
                if (1 == $survey->getOneQuestionPerPage()) {
698
                    if ('pagebreak' !== $row['type']) {
699
                        $paged_questions[$counter][] = $row['iid'];
700
                        $counter++;
701
                        continue;
702
                    }
703
                } else {
704
                    if ('pagebreak' === $row['type']) {
705
                        $counter++;
706
                        $pageBreakText[$counter] = $row['survey_question'];
707
                    } else {
708
                        $paged_questions[$counter][] = $row['iid'];
709
                    }
710
                }
711
            }
712
            Session::write('paged_questions', $paged_questions);
713
        }
714
715
        // Redefinition of variables and session ids to fix issue of survey not
716
        //  showing questions - see support.chamilo.org #5529
717
        $courseId = $survey_invitation['c_id'];
718
        Session::write('_cid', $courseId);
719
        Session::write('_real_cid', $courseId);
720
721
        if (array_key_exists($_GET['show'], $paged_questions)) {
722
            if (isset($_GET['user_id'])) {
723
                // Get the user into survey answer table (user or anonymus)
724
                $my_user_id = 1 == $survey->getAnonymous() ? $surveyUserFromSession : api_get_user_id();
725
726
                $sql = "SELECT
727
                            survey_question.survey_group_sec1,
728
                            survey_question.survey_group_sec2,
729
                            survey_question.survey_group_pri,
730
                            survey_question.iid question_id,
731
                            survey_question.survey_id,
732
                            survey_question.survey_question,
733
                            survey_question.display,
734
                            survey_question.sort,
735
                            survey_question.type,
736
                            survey_question.max_value,
737
                            survey_question_option.iid question_option_id,
738
                            survey_question_option.option_text,
739
                            $select
740
                            survey_question_option.sort as option_sort
741
                        FROM $table_survey_question survey_question
742
                        LEFT JOIN $table_survey_question_option survey_question_option
743
                        ON survey_question.iid = survey_question_option.question_id AND
744
                        survey_question_option.c_id = $courseId
745
                        WHERE
746
                            survey_question.survey_id = '".$surveyId."' AND
747
                            survey_question.iid NOT IN (
748
                                SELECT sa.question_id
749
                                FROM ".$table_survey_answer." sa
750
                                WHERE
751
                                    sa.user='".$my_user_id."') AND
752
                                    survey_question.c_id =  $courseId
753
                                ORDER BY survey_question.sort, survey_question_option.sort ASC";
754
            } else {
755
                $sql = "SELECT
756
                            survey_question.survey_group_sec1,
757
                            survey_question.survey_group_sec2,
758
                            survey_question.survey_group_pri,
759
                            survey_question.iid question_id,
760
                            survey_question.survey_id,
761
                            survey_question.survey_question,
762
                            survey_question.display,
763
                            survey_question.sort,
764
                            survey_question.type,
765
                            survey_question.max_value,
766
                            survey_question_option.iid question_option_id,
767
                            survey_question_option.option_text,
768
                            $select
769
                            survey_question_option.sort as option_sort
770
                            ".($allowRequiredSurveyQuestions ? ', survey_question.is_required' : '')."
771
                        FROM $table_survey_question survey_question
772
                        LEFT JOIN $table_survey_question_option survey_question_option
773
                        ON survey_question.iid = survey_question_option.question_id
774
                        WHERE
775
                            survey_question NOT LIKE '%{{%' AND
776
                            survey_question.survey_id = '".$surveyId."' AND
777
                            survey_question.iid IN (".implode(',', $paged_questions[$_GET['show']]).")
778
                        ORDER BY survey_question.sort, survey_question_option.sort ASC";
779
            }
780
781
            $result = Database::query($sql);
782
            $question_counter_max = Database::num_rows($result);
783
            $counter = 0;
784
            $limit = 0;
785
            $questions = [];
786
            while ($row = Database::fetch_assoc($result)) {
787
                // If the type is not a pagebreak we store it in the $questions array
788
                if ('pagebreak' !== $row['type']) {
789
                    $sort = $row['sort'];
790
                    $questions[$sort]['question_id'] = $row['question_id'];
791
                    $questions[$sort]['survey_id'] = $row['survey_id'];
792
                    $questions[$sort]['survey_question'] = $row['survey_question'];
793
                    $questions[$sort]['display'] = $row['display'];
794
                    $questions[$sort]['type'] = $row['type'];
795
                    $questions[$sort]['options'][$row['question_option_id']] = $row['option_text'];
796
                    $questions[$sort]['maximum_score'] = $row['max_value'];
797
                    $questions[$sort]['sort'] = $sort;
798
                    $questions[$sort]['is_required'] = $allowRequiredSurveyQuestions && $row['is_required'];
799
                    $questions[$sort]['parent_id'] = $row['parent_id'] ?? 0;
800
                    $questions[$sort]['parent_option_id'] =
801
                        isset($row['parent_option_id']) ? $row['parent_option_id'] : 0;
802
                }
803
                $counter++;
804
                if (isset($_GET['show']) && (int) $_GET['show'] >= 0) {
805
                    $lastQuestion = (int) $_GET['show'] - 1;
806
                } else {
807
                    $lastQuestion = (int) $row['question_option_id'];
808
                }
809
            }
810
        }
811
    } elseif (1 === $survey->getSurveyType()) {
812
        $my_survey_id = (int) $survey_invitation['survey_id'];
813
        $current_user = Database::escape_string($survey_invitation['user_id']);
814
815
        if (isset($_POST['personality'])) {
816
            // Compute the results to get the 3 groups nearest to the user's personality
817
            if ('' == $shuffle) {
818
                $order = 'BY sort ASC ';
819
            } else {
820
                $order = $shuffle;
821
            }
822
            $answer_list = [];
823
            // Get current user results
824
            $results = [];
825
            $sql = "SELECT
826
                      survey_group_pri,
827
                      user,
828
                      SUM(value) as value
829
                    FROM $table_survey_answer as survey_answer
830
                    INNER JOIN $table_survey_question as survey_question
831
                    ON (survey_question.iid = survey_answer.question_id)
832
                    WHERE
833
                        survey_answer.survey_id='".$my_survey_id."' AND
834
                        survey_answer.user='".$current_user."'
835
                    GROUP BY survey_group_pri
836
                    ORDER BY survey_group_pri
837
                    ";
838
839
            $result = Database::query($sql);
840
            while ($row = Database :: fetch_array($result)) {
841
                $answer_list['value'] = $row['value'];
842
                $answer_list['group'] = $row['survey_group_pri'];
843
                $results[] = $answer_list;
844
            }
845
846
            // Get the total score for each group of questions
847
            $totals = [];
848
            $sql = "SELECT SUM(temp.value) as value, temp.survey_group_pri FROM
849
                    (
850
                        SELECT
851
                            MAX(value) as value,
852
                            survey_group_pri,
853
                            survey_question.iid question_id
854
                        FROM $table_survey_question as survey_question
855
                        INNER JOIN $table_survey_question_option as survey_question_option
856
                        ON (survey_question.iid = survey_question_option.question_id)
857
                        WHERE
858
                            survey_question.survey_id='".$my_survey_id."'  AND
859
                            survey_question.c_id = $courseId AND
860
                            survey_question_option.c_id = $courseId AND
861
                            survey_group_sec1='0' AND
862
                            survey_group_sec2='0'
863
                        GROUP BY survey_group_pri, survey_question.iid
864
                    ) as temp
865
                    GROUP BY temp.survey_group_pri
866
                    ORDER BY temp.survey_group_pri";
867
868
            $result = Database::query($sql);
869
            while ($row = Database::fetch_array($result)) {
870
                $list['value'] = $row['value'];
871
                $list['group'] = $row['survey_group_pri'];
872
                $totals[] = $list;
873
            }
874
            $final_results = [];
875
            // Get a percentage score for each group
876
            for ($i = 0; $i < count($totals); $i++) {
877
                for ($j = 0; $j < count($results); $j++) {
878
                    if ($totals[$i]['group'] == $results[$j]['group']) {
879
                        $group = $totals[$i]['group'];
880
                        $porcen = ($results[$j]['value'] / $totals[$i]['value']);
881
                        $final_results[$group] = $porcen;
882
                    }
883
                }
884
            }
885
886
            // Sort the results by score (getting a list of group IDs by score into $groups)
887
            arsort($final_results);
888
            $groups = array_keys($final_results);
889
            $result = [];
890
            $count_result = 0;
891
            foreach ($final_results as $key => &$sub_result) {
892
                $result[] = ['group' => $key, 'value' => $sub_result];
893
                $count_result++;
894
            }
895
896
            // i.e 70% - 70% -70% 70%  $equal_count =3
897
            $i = 0;
898
            $group_cant = 0;
899
            $equal_count = 0;
900
            // This is the case if the user does not select any question
901
            if ($count_result > 0) {
902
                // Count the number of scores equal to the first
903
                while (1) {
904
                    if ($result[$i]['value'] == $result[$i + 1]['value']) {
905
                        $equal_count++;
906
                    } else {
907
                        break;
908
                    }
909
                    $i++;
910
                }
911
            } else {
912
                // We force the exit of the survey undeterminated
913
                $equal_count = 10;
914
            }
915
916
            // If we have only 3 or less equal scores (i.e. 0,1 or 2 equalities), then we can use the three first groups
917
            if ($equal_count < 4) {
918
                // If there is one or less score equalities
919
                if (0 === $equal_count || 1 === $equal_count) {
920
                    // i.e 70% - 70% -60% - 60%  $equal_count = 1 we only get the first 2 options
921
                    if (($result[0]['value'] == $result[1]['value']) &&
922
                        ($result[2]['value'] == $result[3]['value'])
923
                    ) {
924
                        $group_cant = 1;
925
                    } elseif (($result[0]['value'] != $result[1]['value']) &&
926
                        ($result[1]['value'] == $result[2]['value']) && ($result[2]['value'] == $result[3]['value'])
927
                    ) {
928
                        // i.e 70% - 70% -0% - 0%     -    $equal_count = 0 we only get the first 2 options
929
                        /* elseif (($result[0]['value'] == $result[1]['value']) && ($result[1]['value'] != $result[2]['value'])) {
930
                          $group_cant = 0;
931
                          } */
932
                        /*
933
                          // i.e 70% - 70% -60% - 60%  $equal_count = 0 we only get the first 2 options
934
                          elseif (($result[0]['value'] == $result[1]['value'])  &&  ($result[2]['value'] == $result[3]['value'])) {
935
                          $group_cant = 0;
936
                          } */
937
                        // i.e. 80% - 70% - 70% - 70%
938
                        $group_cant = 0;
939
                    } else {
940
                        // i.e. 80% - 70% - 70% - 50
941
                        // i.e. 80% - 80% - 70% - 50
942
                        // By default we choose the highest 3
943
                        $group_cant = 2;
944
                    }
945
                } else {
946
                    // If there are two score equalities
947
                    $group_cant = $equal_count;
948
                }
949
950
                //@todo Translate these comments.
951
                // conditional_status
952
                // 0 no determinado
953
                // 1 determinado
954
                // 2 un solo valor
955
                // 3 valores iguales
956
                if ($group_cant > 0) {
957
                    //echo '$equal_count'.$group_cant;
958
                    // We only get highest 3
959
                    $secondary = '';
960
                    $combi = '';
961
                    for ($i = 0; $i <= $group_cant; $i++) {
962
                        $group1 = $groups[$i];
963
                        $group2 = $groups[$i + 1];
964
                        // Here we made all the posibilities with the 3 groups
965
                        if (2 == $group_cant && $i == $group_cant) {
966
                            $group2 = $groups[0];
967
                            $secondary .= " OR ( survey_group_sec1 = '$group1' AND  survey_group_sec2 = '$group2') ";
968
                            $secondary .= " OR ( survey_group_sec1 = '$group2' AND survey_group_sec2 = '$group1' ) ";
969
                            $combi .= $group1.' - '.$group2." or ".$group2.' - '.$group1.'<br />';
970
                        } else {
971
                            if (0 != $i) {
972
                                $secondary .= " OR ( survey_group_sec1 = '$group1' AND  survey_group_sec2 = '$group2') ";
973
                                $secondary .= " OR ( survey_group_sec1 = '$group2' AND survey_group_sec2 = '$group1' ) ";
974
                                $combi .= $group1.' - '.$group2." or ".$group2.' - '.$group1.'<br />';
975
                            } else {
976
                                $secondary .= " ( survey_group_sec1 = '$group1' AND  survey_group_sec2 = '$group2') ";
977
                                $secondary .= " OR ( survey_group_sec1 = '$group2' AND survey_group_sec2 = '$group1' ) ";
978
                                $combi .= $group1.' - '.$group2." or ".$group2.' - '.$group1.'<br />';
979
                            }
980
                        }
981
                    }
982
                    // Create the new select with the questions from the secondary phase
983
                    if (empty($_SESSION['page_questions_sec']) &&
984
                        !is_array($_SESSION['page_questions_sec']) &&
985
                        count(0 == $_SESSION['page_questions_sec'])
986
                    ) {
987
                        $sql = "SELECT * FROM $table_survey_question
988
                                 WHERE
989
                                    survey_id = '".$my_survey_id."' AND
990
                                    ($secondary )
991
                                 ORDER BY sort ASC";
992
                        $result = Database::query($sql);
993
                        $counter = 0;
994
                        while ($row = Database::fetch_assoc($result)) {
995
                            if (1 == $survey->getOneQuestionPerPage()) {
996
                                $paged_questions_sec[$counter][] = $row['question_id'];
997
                                $counter++;
998
                            } elseif ('pagebreak' === $row['type']) {
999
                                $counter++;
1000
                                $pageBreakText[$counter] = $row['survey_question'];
1001
                            } else {
1002
                                // ids from question of the current survey
1003
                                $paged_questions_sec[$counter][] = $row['question_id'];
1004
                            }
1005
                        }
1006
                        Session::write('page_questions_sec', $paged_questions_sec);
1007
                    } else {
1008
                        $paged_questions_sec = Session::read('page_questions_sec');
1009
                    }
1010
                    $paged_questions = Session::read('paged_questions'); // For the sake of pages counting
1011
                    if ('' == $shuffle) {
1012
                        $shuffle = ' BY survey_question.sort, survey_question_option.sort ASC ';
1013
                    }
1014
                    $val = (int) $_POST['personality'];
1015
                    if (is_array($paged_questions_sec)) {
1016
                        $sql = "SELECT
1017
                                    survey_question.survey_group_sec1,
1018
                                    survey_question.survey_group_sec2,
1019
                                    survey_question.survey_group_pri,
1020
                                    survey_question.iid question_id,
1021
                                    survey_question.survey_id,
1022
                                    survey_question.survey_question,
1023
                                    survey_question.display,
1024
                                    survey_question.sort,
1025
                                    survey_question.type,
1026
                                    survey_question.max_value,
1027
                                    survey_question_option.question_option_id,
1028
                                    survey_question_option.option_text,
1029
                                    survey_question_option.sort as option_sort
1030
                                FROM $table_survey_question survey_question
1031
                                LEFT JOIN $table_survey_question_option survey_question_option
1032
                                ON survey_question.iid = survey_question_option.question_id AND
1033
                                WHERE
1034
                                    survey_question NOT LIKE '%{{%' AND
1035
                                    survey_question.survey_id = '".$my_survey_id."'
1036
                                    survey_question.iid IN (".implode(',', $paged_questions_sec[$val]).")
1037
                                ORDER  $shuffle ";
1038
1039
                        $result = Database::query($sql);
1040
                        $question_counter_max = Database::num_rows($result);
1041
                        $counter = 0;
1042
                        $limit = 0;
1043
                        $questions = [];
1044
                        while ($row = Database::fetch_assoc($result)) {
1045
                            // If the type is not a pagebreak we store it in the $questions array
1046
                            if ('pagebreak' !== $row['type']) {
1047
                                $questions[$row['sort']]['question_id'] = $row['question_id'];
1048
                                $questions[$row['sort']]['survey_id'] = $row['survey_id'];
1049
                                $questions[$row['sort']]['survey_question'] = $row['survey_question'];
1050
                                $questions[$row['sort']]['display'] = $row['display'];
1051
                                $questions[$row['sort']]['type'] = $row['type'];
1052
                                $questions[$row['sort']]['options'][$row['question_option_id']] = $row['option_text'];
1053
                                $questions[$row['sort']]['maximum_score'] = $row['max_value'];
1054
                                // Personality params
1055
                                $questions[$row['sort']]['survey_group_sec1'] = $row['survey_group_sec1'];
1056
                                $questions[$row['sort']]['survey_group_sec2'] = $row['survey_group_sec2'];
1057
                                $questions[$row['sort']]['survey_group_pri'] = $row['survey_group_pri'];
1058
                                $questions[$row['sort']]['sort'] = $row['sort'];
1059
                            } else {
1060
                                // If the type is a pagebreak we are finished loading the questions for this page
1061
                                break;
1062
                            }
1063
                            $counter++;
1064
                        }
1065
                    } else {
1066
                        echo get_lang('Survey undefined');
1067
                    }
1068
                } else {
1069
                    echo get_lang('Survey undefined');
1070
                }
1071
            } else {
1072
                echo get_lang('Survey undefined');
1073
            }
1074
        } else {
1075
            // We need this variable only in the 2nd set of questions when personality is set.
1076
            Session::erase('page_questions_sec');
1077
            $paged_questions_sec = [];
1078
1079
            // Only the questions from the basic group
1080
            // the 50 questions A B C D E F G
1081
            $order_sql = $shuffle;
1082
            if ('' == $shuffle) {
1083
                $order_sql = ' BY question_id ';
1084
            }
1085
1086
            if (empty($_SESSION['paged_questions'])) {
1087
                $sql = "SELECT * FROM $table_survey_question
1088
                        WHERE
1089
                            survey_id = '".$surveyId."' AND
1090
                            survey_group_sec1='0' AND
1091
                            survey_group_sec2='0'
1092
                        ORDER ".$order_sql." ";
1093
                $result = Database::query($sql);
1094
                $counter = 0;
1095
                while ($row = Database::fetch_assoc($result)) {
1096
                    if (1 == $survey->getOneQuestionPerPage()) {
1097
                        $paged_questions[$counter][] = $row['question_id'];
1098
                        $counter++;
1099
                    } else {
1100
                        if ('pagebreak' === $row['type']) {
1101
                            $counter++;
1102
                            $pageBreakText[$counter] = $row['survey_question'];
1103
                        } else {
1104
                            // ids from question of the current survey
1105
                            $paged_questions[$counter][] = $row['question_id'];
1106
                        }
1107
                    }
1108
                }
1109
                Session::write('paged_questions', $paged_questions);
1110
            } else {
1111
                $paged_questions = Session::read('paged_questions');
1112
            }
1113
            $order_sql = $shuffle;
1114
            if ('' == $shuffle) {
1115
                $order_sql = ' BY survey_question.sort, survey_question_option.sort ASC ';
1116
            }
1117
            $val = $_GET['show'];
1118
            $result = null;
1119
            if ('' != $val) {
1120
                $imploded = Database::escape_string(implode(',', $paged_questions[$val]));
1121
                if ('' != $imploded) {
1122
                    // The answers are always in the same order NO shuffle
1123
                    $order_sql = ' BY survey_question.sort, survey_question_option.sort ASC ';
1124
                    $sql = "SELECT
1125
                                survey_question.survey_group_sec1,
1126
                                survey_question.survey_group_sec2,
1127
                                survey_question.survey_group_pri,
1128
                                survey_question.iid question_id,
1129
                                survey_question.survey_id,
1130
                                survey_question.survey_question,
1131
                                survey_question.display,
1132
                                survey_question.sort,
1133
                                survey_question.type,
1134
                                survey_question.max_value,
1135
                                survey_question_option.question_option_id,
1136
                                survey_question_option.option_text,
1137
                                survey_question_option.sort as option_sort
1138
                                ".($allowRequiredSurveyQuestions ? ', survey_question.is_required' : '')."
1139
                            FROM $table_survey_question survey_question
1140
                            LEFT JOIN $table_survey_question_option survey_question_option
1141
                            ON survey_question.iid = survey_question_option.question_id AND
1142
                            survey_question_option.c_id = $courseId
1143
                            WHERE
1144
                                survey_question NOT LIKE '%{{%' AND
1145
                                survey_question.survey_id = '".intval($survey_invitation['survey_id'])."' AND
1146
                                survey_question.c_id = $courseId  AND
1147
                                survey_question.iid IN (".$imploded.")
1148
                            ORDER $order_sql ";
1149
                    $result = Database::query($sql);
1150
                    $question_counter_max = Database :: num_rows($result);
1151
                }
1152
            }
1153
1154
            if (!is_null($result)) {
1155
                $counter = 0;
1156
                $limit = 0;
1157
                $questions = [];
1158
                while ($row = Database::fetch_assoc($result)) {
1159
                    // If the type is not a pagebreak we store it in the $questions array
1160
                    if ('pagebreak' !== $row['type']) {
1161
                        $questions[$row['sort']]['question_id'] = $row['question_id'];
1162
                        $questions[$row['sort']]['survey_id'] = $row['survey_id'];
1163
                        $questions[$row['sort']]['survey_question'] = $row['survey_question'];
1164
                        $questions[$row['sort']]['display'] = $row['display'];
1165
                        $questions[$row['sort']]['type'] = $row['type'];
1166
                        $questions[$row['sort']]['options'][$row['question_option_id']] = $row['option_text'];
1167
                        $questions[$row['sort']]['maximum_score'] = $row['max_value'];
1168
                        $questions[$row['sort']]['is_required'] = $allowRequiredSurveyQuestions && $row['is_required'];
1169
                        // Personality params
1170
                        $questions[$row['sort']]['survey_group_sec1'] = $row['survey_group_sec1'];
1171
                        $questions[$row['sort']]['survey_group_sec2'] = $row['survey_group_sec2'];
1172
                        $questions[$row['sort']]['survey_group_pri'] = $row['survey_group_pri'];
1173
                        $questions[$row['sort']]['sort'] = $row['sort'];
1174
                    } else {
1175
                        // If the type is a page break we are finished loading the questions for this page
1176
                        //break;
1177
                    }
1178
                    $counter++;
1179
                }
1180
            }
1181
        }
1182
    } else { // In case it's another type than 0 or 1
1183
        echo get_lang('Survey type unknown');
1184
    }
1185
}
1186
1187
$numberOfPages = SurveyManager::getCountPages($survey);
1188
1189
// Displaying the form with the questions
1190
$show = 0;
1191
if (isset($_GET['show']) && '' != $_GET['show']) {
1192
    $show = (int) $_GET['show'] + 1;
1193
}
1194
1195
$displayFinishButton = true;
1196
if (isset($_GET['show']) && '' != $_GET['show']) {
1197
    $pagesIndexes = array_keys($paged_questions);
1198
    $pagesIndexes[] = count($pagesIndexes);
1199
1200
    if (end($pagesIndexes) <= $show - 1 && empty($_POST)) {
1201
        $displayFinishButton = false;
1202
    }
1203
}
1204
1205
// Displaying the form with the questions
1206
$personality = 0;
1207
if (isset($_POST['personality'])) {
1208
    $personality = (int) $_POST['personality'] + 1;
1209
}
1210
1211
// Displaying the form with the questions
1212
$g_c = isset($_GET['course']) ? Security::remove_XSS($_GET['course']) : '';
1213
$g_ic = isset($_GET['invitationcode']) ? Security::remove_XSS($_GET['invitationcode']) : '';
1214
$g_cr = isset($_GET['cidReq']) ? Security::remove_XSS($_GET['cidReq']) : '';
1215
$p_l = isset($_POST['language']) ? Security::remove_XSS($_POST['language']) : '';
1216
$add_parameters = isset($_GET['user_id']) ? '&user_id='.intval($_GET['user_id']) : '';
1217
$url = api_get_self().'?'.api_get_cidreq().$add_parameters.
1218
    '&course='.$g_c.
1219
    '&invitationcode='.$g_ic.
1220
    '&show='.$show.
1221
    '&iid='.$surveyId
1222
;
1223
if (!empty($_GET['language'])) {
1224
    $lang = Security::remove_XSS($_GET['language']);
1225
    $url .= '&language='.$lang;
1226
}
1227
1228
if (!empty($lpItemId)) {
1229
    $url .= '&lp_item_id='.$lpItemId;
1230
}
1231
1232
$form = new FormValidator(
1233
    'question',
1234
    'post',
1235
    $url,
1236
    null,
1237
    null,
1238
    FormValidator::LAYOUT_INLINE
1239
);
1240
$form->addHidden('language', $p_l);
1241
1242
$showNumber = true;
1243
if (SurveyManager::hasDependency($survey)) {
1244
    $showNumber = false;
1245
}
1246
1247
if (isset($questions) && is_array($questions)) {
1248
    $originalShow = isset($_GET['show']) ? (int) $_GET['show'] : 0;
1249
    $questionCounter = 1;
1250
    if (!empty($originalShow)) {
1251
        $before = 0;
1252
        foreach ($paged_questions as $keyQuestion => $list) {
1253
            if ($originalShow > $keyQuestion) {
1254
                $before += count($list);
1255
            }
1256
        }
1257
        $questionCounter = $before + 1;
1258
    }
1259
1260
    $form->addHtml('<div class="start-survey">');
1261
    $js = '';
1262
    if (isset($pageBreakText[$originalShow]) && !empty(strip_tags($pageBreakText[$originalShow]))) {
1263
        // Only show page-break texts if there is something there, apart from
1264
        // HTML tags
1265
        $form->addHtml(
1266
            '<div>'.
1267
            Security::remove_XSS($pageBreakText[$originalShow]).
1268
            '</div>'
1269
        );
1270
        $form->addHtml('<br />');
1271
    }
1272
1273
    foreach ($questions as $key => &$question) {
1274
        $ch_type = 'ch_'.$question['type'];
1275
        $questionNumber = $questionCounter;
1276
        $display = new $ch_type();
1277
        $parent = $question['parent_id'];
1278
        $parentClass = '';
1279
        // @todo move this in a function.
1280
        if (!empty($parent)) {
1281
            $parentClass = ' with_parent with_parent_'.$question['question_id'];
1282
            $parents = survey_question::getParents($question['question_id']);
1283
            if (!empty($parents)) {
1284
                foreach ($parents as $parentId) {
1285
                    $parentClass .= ' with_parent_only_hide_'.$parentId;
1286
                }
1287
            }
1288
        }
1289
1290
        $js .= survey_question::getQuestionJs($question);
1291
1292
        // @todo move this in a function.
1293
        $form->addHtml('<div class="survey_question '.$ch_type.' '.$parentClass.'">');
1294
        if ($showNumber && $survey->isDisplayQuestionNumber()) {
1295
            $form->addHtml('<div style="float:left; font-weight: bold; margin-right: 5px;"> '.$questionNumber.'. </div>');
1296
        }
1297
        $form->addHtml('<div>'.Security::remove_XSS($question['survey_question']).'</div> ');
1298
1299
        $userAnswerData = SurveyUtil::get_answers_of_question_by_user($question['survey_id'], $question['question_id'], $lpItemId);
1300
        $finalAnswer = null;
1301
1302
        if (!empty($userAnswerData[$user_id])) {
1303
            $userAnswer = $userAnswerData[$user_id];
1304
            switch ($question['type']) {
1305
                case 'score':
1306
                    $finalAnswer = [];
1307
                    foreach ($userAnswer as $userChoice) {
1308
                        [$choiceId, $choiceValue] = explode('*', $userChoice);
1309
                        $finalAnswer[$choiceId] = $choiceValue;
1310
                    }
1311
                    break;
1312
                case 'percentage':
1313
                    [$choiceId, $choiceValue] = explode('*', current($userAnswer));
1314
                    $finalAnswer = $choiceId;
1315
                    break;
1316
                default:
1317
                    $finalAnswer = $userAnswer;
1318
                    break;
1319
            }
1320
        }
1321
        $display->render($form, $question, $finalAnswer);
1322
        $form->addHtml('</div>');
1323
        $questionCounter++;
1324
    }
1325
1326
    $form->addHtml($js);
1327
}
1328
1329
$form->addHtml('<div class="start-survey">');
1330
if ('0' == $survey->getSurveyType()) {
1331
    if (0 == $survey->getShowFormProfile()) {
1332
        // The normal survey as always
1333
        if ($show < $numberOfPages) {
1334
            if (0 == $show) {
1335
                $form->addButton(
1336
                    'next_survey_page',
1337
                    get_lang('Start the Survey'),
1338
                    'arrow-right',
1339
                    'success'
1340
                );
1341
            } else {
1342
                if (
1343
                'true' === api_get_setting('survey.survey_backwards_enable')
1344
                ) {
1345
                    if ($lastQuestion >= 0) {
1346
                        $form->addHtml(
1347
                            "<a class=\" btn btn--warning \" href=\"$url&show=$lastQuestion\">".
1348
                            "<em class=\"fa fa-arrow-left\"></em> "
1349
                            .get_lang('Back')." </a>"
1350
                        );
1351
                    }
1352
                }
1353
                $form->addButton(
1354
                    'next_survey_page',
1355
                    get_lang('Next'),
1356
                    'arrow-right',
1357
                    'success'
1358
                );
1359
            }
1360
        }
1361
        if ($show >= $numberOfPages && $displayFinishButton) {
1362
            $form->addButton(
1363
                'finish_survey',
1364
                get_lang('Finish survey'),
1365
                'arrow-right',
1366
                'success'
1367
            );
1368
        }
1369
    } else {
1370
        // The normal survey as always but with the form profile
1371
        if (isset($_GET['show'])) {
1372
            $numberOfPages = count($paged_questions);
1373
            if ($show < $numberOfPages) {
1374
                if (0 == $show) {
1375
                    $form->addButton(
1376
                        'next_survey_page',
1377
                        get_lang('Start the Survey'),
1378
                        'arrow-right',
1379
                        'success'
1380
                    );
1381
                } else {
1382
                    $form->addButton(
1383
                        'next_survey_page',
1384
                        get_lang('Next'),
1385
                        'arrow-right',
1386
                        'success'
1387
                    );
1388
                }
1389
            }
1390
1391
            if ($show >= $numberOfPages && $displayFinishButton) {
1392
                $form->addButton(
1393
                    'finish_survey',
1394
                    get_lang('Finish survey'),
1395
                    'arrow-right',
1396
                    'success'
1397
                );
1398
            }
1399
        }
1400
    }
1401
} elseif (1 === $survey->getSurveyType()) {
1402
    // Conditional/personality-test type survey
1403
    if (isset($_GET['show']) || isset($_POST['personality'])) {
1404
        $numberOfPages = count($paged_questions);
1405
        if (!empty($paged_questions_sec) && count($paged_questions_sec) > 0) {
1406
            // In case we're in the second phase, also sum the second group questions
1407
            $numberOfPages += count($paged_questions_sec);
1408
        } else {
1409
            // We need this variable only if personality == 1
1410
            Session::erase('page_questions_sec');
1411
            $paged_questions_sec = [];
1412
        }
1413
1414
        if (0 === $personality) {
1415
            if (($show <= $numberOfPages) || !$_GET['show']) {
1416
                $form->addButton('next_survey_page', get_lang('Next'), 'arrow-right', 'success');
1417
                if (0 == $survey->getOneQuestionPerPage()) {
1418
                    if ($personality >= 0) {
1419
                        $form->addHidden('personality', $personality);
1420
                    }
1421
                } else {
1422
                    if ($personality > 0) {
1423
                        $form->addHidden('personality', $personality);
1424
                    }
1425
                }
1426
1427
                if ($numberOfPages == $show) {
1428
                    $form->addHidden('personality', $personality);
1429
                }
1430
            }
1431
        }
1432
1433
        if ($show > $numberOfPages && $_GET['show'] && 0 === $personality) {
1434
            $form->addHidden('personality', $personality);
1435
        } elseif ($personality > 0) {
1436
            if (1 == $survey->getOneQuestionPerPage()) {
1437
                if ($show >= $numberOfPages) {
1438
                    $form->addButton('finish_survey', get_lang('Finish survey'), 'arrow-right', 'success');
1439
                } else {
1440
                    $form->addHidden('personality', $personality);
1441
                    $form->addButton('next_survey_page', get_lang('Next'), 'arrow-right', 'success');
1442
                }
1443
            } else {
1444
                // if the personality test hidden input was set.
1445
                $form->addButton('finish_survey', get_lang('Finish survey'), 'arrow-right');
1446
            }
1447
        }
1448
    } elseif ('' == $survey->getFormFields()) {
1449
        // This is the case when the show_profile_form is true but there are not form_fields
1450
        $form->addButton('next_survey_page', get_lang('Next'), 'arrow-right', 'success');
1451
    } elseif (!is_array($user_data)) {
1452
        // If the user is not registered in the platform we do not show the form to update his information
1453
        $form->addButton('next_survey_page', get_lang('Next'), 'arrow-right', 'success');
1454
    }
1455
}
1456
$form->addHtml('</div>');
1457
$form->display();
1458
Display::display_footer();
1459