Issues (2089)

public/main/survey/fillsurvey.php (1 issue)

Labels
Severity
1
<?php
2
3
declare(strict_types=1);
4
5
/* For licensing terms, see /license.txt */
6
7
use Chamilo\CoreBundle\Framework\Container;
8
use Chamilo\CourseBundle\Entity\CSurvey;
9
use ChamiloSession as Session;
10
11
$lastQuestion = 0;
12
13
/*
14
 * @author unknown, the initial survey that did not make it in 1.8 because of bad code
15
 * @author Patrick Cool <[email protected]>, Ghent University: cleanup,
16
 * refactoring and rewriting large parts of the code
17
 * @author Julio Montoya <[email protected]>, Chamilo: Personality Test
18
 * modification and rewriting large parts of the code as well
19
 *
20
 * @todo check if the user already filled the survey and if this
21
 * is the case then the answers have to be updated and not stored again.
22
 * @todo performance could be improved if not the survey_id was
23
 * stored with the invitation but the survey_code
24
 */
25
26
// Unsetting the course id (because it is in the URL)
27
if (!isset($_GET['cidReq'])) {
28
    $cidReset = true;
29
} else {
30
    $_cid = $_GET['cidReq'];
31
}
32
33
require_once __DIR__.'/../inc/global.inc.php';
34
35
// -----------------------------------------------------------------------------
36
// DB tables
37
// -----------------------------------------------------------------------------
38
$table_survey = Database::get_course_table(TABLE_SURVEY);
39
$table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
40
$table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
41
$table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
42
$table_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
43
$table_user = Database::get_main_table(TABLE_MAIN_USER);
44
45
$allowRequiredSurveyQuestions = true;
46
47
// -----------------------------------------------------------------------------
48
// Auth / context
49
// -----------------------------------------------------------------------------
50
$isAnonymous = api_is_anonymous(api_get_user_id(), true);
51
52
$courseInfo = isset($_GET['course'])
53
    ? api_get_course_info($_GET['course'])
54
    : api_get_course_info();
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
// -----------------------------------------------------------------------------
74
// Required params
75
// -----------------------------------------------------------------------------
76
if ((!isset($_GET['course']) || !isset($_GET['invitationcode'])) && !isset($_GET['user_id'])) {
77
    api_not_allowed(true, get_lang('There is a parameter missing in the link. Please use copy and past'));
78
}
79
80
$repo = Container::getSurveyRepository();
81
$surveyId = isset($_GET['iid']) ? (int) $_GET['iid'] : 0;
82
83
if (empty($surveyId) && (isset($_POST['language']) && is_numeric($_POST['language']))) {
84
    $surveyId = (int) $_POST['language'];
85
}
86
87
/** @var CSurvey $survey */
88
$survey = $repo->find($surveyId);
89
if (null === $survey) {
90
    api_not_allowed(true);
91
}
92
93
$surveyId = $survey->getIid();
94
$invitationCode = $_GET['invitationcode'] ?? null;
95
96
$lpItemCondition = '';
97
if ($allowSurveyInLp && !empty($lpItemId)) {
98
    $lpItemCondition = " AND c_lp_item_id = $lpItemId";
99
}
100
101
$sessionCondition = '';
102
if (true === api_get_setting('survey.show_surveys_base_in_sessions')) {
103
    $sessionCondition = api_get_session_condition($sessionId);
104
}
105
106
// Anonymous restriction
107
if (0 == $survey->getAnonymous() && api_is_anonymous()) {
108
    api_not_allowed(true);
109
}
110
111
// -----------------------------------------------------------------------------
112
// Auto-invitation flow
113
// -----------------------------------------------------------------------------
114
if ('auto' === $invitationCode) {
115
    $userid = api_get_user_id();
116
    $surveyCode = $survey->getCode();
117
118
    if ($isAnonymous) {
119
        $autoInvitationCode = 'auto-ANONY_'.md5(time())."-$surveyCode";
120
    } else {
121
        $invitations = SurveyManager::getUserInvitationsForSurveyInCourse(
122
            $userid,
123
            $surveyCode,
124
            $courseId,
125
            $sessionId,
126
            0,
127
            $lpItemId
128
        );
129
        $lastInvitation = current($invitations);
130
        $autoInvitationCode = $lastInvitation
131
            ? $lastInvitation->getInvitationCode()
132
            : "auto-$userid-$surveyCode";
133
    }
134
135
    SurveyManager::checkTimeAvailability($survey);
136
137
    $sql = "SELECT user_id
138
            FROM $table_survey_invitation
139
            WHERE c_id = $courseId
140
              AND invitation_code = '".Database::escape_string($autoInvitationCode)."'
141
              $sessionCondition
142
              $lpItemCondition";
143
    $result = Database::query($sql);
144
    $now = api_get_utc_datetime();
145
146
    if (0 == Database::num_rows($result)) {
147
        $params = [
148
            'c_id' => $courseId,
149
            'survey_id' => $surveyId,
150
            'user_id' => $userid,
151
            'invitation_code' => $autoInvitationCode,
152
            'invitation_date' => $now,
153
            'answered' => 0,
154
            'c_lp_item_id' => $lpItemId,
155
        ];
156
        Database::insert($table_survey_invitation, $params);
157
    }
158
159
    $_GET['invitationcode'] = $autoInvitationCode;
160
    Session::write('auto_invitation_code_'.$surveyCode, $autoInvitationCode);
161
    $invitationCode = $autoInvitationCode;
162
}
163
164
// Validate invitation code
165
$sql = "SELECT *
166
        FROM $table_survey_invitation
167
        WHERE c_id = $courseId
168
          AND invitation_code = '".Database::escape_string($invitationCode)."'
169
          $sessionCondition
170
          $lpItemCondition";
171
$result = Database::query($sql);
172
if (Database::num_rows($result) < 1) {
173
    api_not_allowed(true, get_lang('Wrong invitation code'));
174
}
175
176
$survey_invitation = Database::fetch_assoc($result);
177
$surveyUserFromSession = Session::read('surveyuser');
178
179
// Block if already answered
180
if (
181
    !isset($_POST['finish_survey'])
182
    && (
183
        ($isAnonymous && !empty($surveyUserFromSession) && SurveyUtil::isSurveyAnsweredFlagged($survey->getCode(), $survey_invitation['c_id']))
184
        || (1 == $survey_invitation['answered'] && !isset($_GET['user_id']))
185
    )
186
) {
187
    api_not_allowed(true, Display::return_message(get_lang('You already filled this survey')));
188
}
189
190
Event::registerLog([
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

190
Event::/** @scrutinizer ignore-call */ 
191
       registerLog([

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...
191
    'tool' => TOOL_SURVEY,
192
    'tool_id' => $survey_invitation['iid'],
193
    'action' => 'invitationcode',
194
    'action_details' => $invitationCode,
195
]);
196
197
$survey_invitation['survey_id'] = $surveyId;
198
199
// Availability check
200
SurveyManager::checkTimeAvailability($survey);
201
202
// Redirect if meeting
203
$surveyType = $survey->getSurveyType();
204
if (3 === $surveyType) {
205
    header(
206
        'Location: '.
207
        api_get_path(WEB_CODE_PATH).
208
        'survey/meeting.php?cid='.$courseId.'&sid='.$sessionId.'&invitationcode='.Security::remove_XSS($invitationCode)
209
    );
210
211
    exit;
212
}
213
214
if (!empty($survey->getAnonymous())) {
215
    define('USER_IN_ANON_SURVEY', true);
216
}
217
218
// -----------------------------------------------------------------------------
219
// Answer saving
220
// -----------------------------------------------------------------------------
221
if (count($_POST) > 0) {
222
    if (0 === $surveyType) {
223
        // Standard survey flow
224
        $types = [];
225
        $required = [];
226
        $questionList = [];
227
228
        foreach ($survey->getQuestions() as $question) {
229
            $id = $question->getIid();
230
            $questionList[$id] = $question;
231
            $types[$id] = $question->getType();
232
            $required[$id] = $allowRequiredSurveyQuestions && $question->isMandatory();
233
        }
234
235
        foreach ($_POST as $key => &$value) {
236
            // Only question inputs
237
            if (!str_contains($key, 'other_question')
238
                  && str_contains($key, 'question') && '_qf__question' !== $key) {
239
                $survey_question_id = str_replace('question', '', $key);
240
                if (empty($survey_question_id)) {
241
                    continue;
242
                }
243
244
                $other = isset($_POST['other_question'.$survey_question_id]) ? $_POST['other_question'.$survey_question_id] : '';
245
                $question = $questionList[$survey_question_id] ?? null;
246
                if (null === $question) {
247
                    continue;
248
                }
249
250
                if (is_array($value)) {
251
                    // Score or multiple
252
                    SurveyUtil::remove_answer($survey_invitation['user_id'], $surveyId, $survey_question_id, $lpItemId);
253
254
                    foreach ($value as $answer_key => &$answer_value) {
255
                        if ('score' === $types[$survey_question_id]) {
256
                            $option_id = $answer_key;
257
                            $option_value = $answer_value;
258
                        } else {
259
                            $option_id = $answer_value;
260
                            $option_value = '';
261
                        }
262
263
                        SurveyUtil::saveAnswer(
264
                            $survey_invitation['user_id'],
265
                            $survey,
266
                            $question,
267
                            $option_id,
268
                            $option_value,
269
                            '',
270
                            $lpItemId
271
                        );
272
                    }
273
                } else {
274
                    // Open / single / percentage
275
                    $option_value = 0;
276
                    if (isset($types[$survey_question_id]) && 'percentage' === $types[$survey_question_id]) {
277
                        $sql = "SELECT * FROM $table_survey_question_option WHERE iid='".(int) $value."'";
278
                        $result = Database::query($sql);
279
                        $row = Database::fetch_assoc($result);
280
                        if ($row) {
281
                            $option_value = $row['option_text'];
282
                        }
283
                    } elseif (isset($types[$survey_question_id]) && 'open' === $types[$survey_question_id]) {
284
                        $option_value = $value;
285
                    }
286
287
                    SurveyUtil::remove_answer($survey_invitation['user_id'], $surveyId, $survey_question_id, $lpItemId);
288
289
                    SurveyUtil::saveAnswer(
290
                        $survey_invitation['user_id'],
291
                        $survey,
292
                        $question,
293
                        $value,
294
                        $option_value,
295
                        $other,
296
                        $lpItemId
297
                    );
298
                }
299
            }
300
        }
301
    } elseif (1 === $survey->getSurveyType()) {
302
        // Conditional / personality test
303
        $shuffle = '';
304
        if (1 == $survey->getShuffle()) {
305
            $shuffle = ' ORDER BY RAND() ';
306
        }
307
308
        $questionList = [];
309
        foreach ($survey->getQuestions() as $question) {
310
            $questionList[$question->getIid()] = $question;
311
        }
312
313
        foreach ($_POST as $key => &$value) {
314
            if (str_contains($key, 'question')) {
315
                $survey_question_id = str_replace('question', '', $key);
316
                if (empty($survey_question_id)) {
317
                    continue;
318
                }
319
320
                $sql = "SELECT value FROM $table_survey_question_option WHERE iid='".(int) $value."'";
321
                $result = Database::query($sql);
322
                $row = Database::fetch_assoc($result);
323
                $option_value = $row['value'];
324
325
                SurveyUtil::remove_answer(
326
                    $survey_invitation['user_id'],
327
                    $survey_invitation['survey_id'],
328
                    $survey_question_id,
329
                    $lpItemId
330
                );
331
332
                $surveyId = (int) $survey_invitation['survey_id'];
333
                $repo = Container::getSurveyRepository();
334
                $survey = $repo->find($surveyId);
335
336
                SurveyUtil::saveAnswer(
337
                    api_get_user_entity($survey_invitation['user_id']),
338
                    $survey,
339
                    $questionList[$survey_question_id],
340
                    $value,
341
                    $option_value,
342
                    '',
343
                    $lpItemId
344
                );
345
            }
346
        }
347
    } else {
348
        api_not_allowed(true, get_lang('Survey type unknown'));
349
    }
350
}
351
352
// -----------------------------------------------------------------------------
353
// Profile form (if requested by survey)
354
// -----------------------------------------------------------------------------
355
$user_id = api_get_user_id();
356
if (0 == $user_id) {
357
    $user_id = $survey_invitation['user_id'];
358
}
359
$user_data = api_get_user_info($user_id);
360
361
if ('' != $survey->getFormFields() && 0 == $survey->getAnonymous() && is_array($user_data)) {
362
    $form_fields = explode('@', $survey->getFormFields());
363
    $list = [];
364
    foreach ($form_fields as $field) {
365
        $field_value = explode(':', $field);
366
        if (isset($field_value[1]) && 1 == $field_value[1]) {
367
            if ('' != $field_value[0]) {
368
                $val = api_substr($field_value[0], 8, api_strlen($field_value[0]));
369
                $list[$val] = 1;
370
            }
371
        }
372
    }
373
374
    $url = api_get_self().'?'.api_get_cidreq();
375
    $listQueryParams = explode('&', $_SERVER['QUERY_STRING']);
376
    foreach ($listQueryParams as $param) {
377
        $url .= '&'.Security::remove_XSS($param);
378
    }
379
    if (!empty($lpItemId)) {
380
        $url .= '&lp_item_id='.$lpItemId;
381
    }
382
383
    // Same form as auth/profile.php
384
    $form = new FormValidator('profile', 'post', $url);
385
    if (api_is_western_name_order()) {
386
        if (isset($list['firstname']) && 1 == $list['firstname']) {
387
            $form->addElement('text', 'firstname', get_lang('First name'), ['size' => 40]);
388
            if ('true' !== api_get_setting('profile', 'name')) {
389
                $form->freeze(['firstname']);
390
            }
391
            $form->applyFilter(['firstname'], 'stripslashes');
392
            $form->applyFilter(['firstname'], 'trim');
393
            $form->addRule('firstname', get_lang('Required field'), 'required');
394
        }
395
        if (isset($list['lastname']) && 1 == $list['lastname']) {
396
            $form->addElement('text', 'lastname', get_lang('Last name'), ['size' => 40]);
397
            if ('true' !== api_get_setting('profile', 'name')) {
398
                $form->freeze(['lastname']);
399
            }
400
            $form->applyFilter(['lastname'], 'stripslashes');
401
            $form->applyFilter(['lastname'], 'trim');
402
            $form->addRule('lastname', get_lang('Required field'), 'required');
403
        }
404
    } else {
405
        if (isset($list['lastname']) && 1 == $list['lastname']) {
406
            $form->addElement('text', 'lastname', get_lang('Last name'), ['size' => 40]);
407
            if ('true' !== api_get_setting('profile', 'name')) {
408
                $form->freeze(['lastname']);
409
            }
410
            $form->applyFilter(['lastname'], 'stripslashes');
411
            $form->applyFilter(['lastname'], 'trim');
412
            $form->addRule('lastname', get_lang('Required field'), 'required');
413
        }
414
        if (isset($list['firstname']) && 1 == $list['firstname']) {
415
            $form->addElement('text', 'firstname', get_lang('First name'), ['size' => 40]);
416
            if ('true' !== api_get_setting('profile', 'name')) {
417
                $form->freeze(['firstname']);
418
            }
419
            $form->applyFilter(['firstname'], 'stripslashes');
420
            $form->applyFilter(['firstname'], 'trim');
421
            $form->addRule('firstname', get_lang('Required field'), 'required');
422
        }
423
    }
424
425
    if (isset($list['official_code']) && 1 == $list['official_code']) {
426
        $form->addElement('text', 'official_code', get_lang('Code'), ['size' => 40]);
427
        if ('true' !== api_get_setting('profile', 'officialcode')) {
428
            $form->freeze('official_code');
429
        }
430
        $form->applyFilter('official_code', 'stripslashes');
431
        $form->applyFilter('official_code', 'trim');
432
        if ('true' === api_get_setting('registration', 'officialcode')
433
            && 'true' === api_get_setting('profile', 'officialcode')) {
434
            $form->addRule('official_code', get_lang('Required field'), 'required');
435
        }
436
    }
437
438
    if (isset($list['email']) && 1 == $list['email']) {
439
        $form->addElement('text', 'email', get_lang('E-mail'), ['size' => 40]);
440
        if ('true' !== api_get_setting('profile', 'email')) {
441
            $form->freeze('email');
442
        }
443
        $form->applyFilter('email', 'stripslashes');
444
        $form->applyFilter('email', 'trim');
445
        if ('true' === api_get_setting('registration', 'email')) {
446
            $form->addRule('email', get_lang('Required field'), 'required');
447
        }
448
        $form->addEmailRule('email');
449
    }
450
451
    if (isset($list['phone']) && 1 == $list['phone']) {
452
        $form->addElement('text', 'phone', get_lang('Phone'), ['size' => 20]);
453
        if ('true' !== api_get_setting('profile', 'phone')) {
454
            $form->freeze('phone');
455
        }
456
        $form->applyFilter('phone', 'stripslashes');
457
        $form->applyFilter('phone', 'trim');
458
        if ('true' == api_get_setting('profile', 'phone')) {
459
            $form->addRule('phone', get_lang('Required field'), 'required');
460
        }
461
    }
462
463
    if (isset($list['language']) && 1 == $list['language']) {
464
        $form->addSelectLanguage('language', get_lang('Language'));
465
        if ('true' !== api_get_setting('profile', 'language')) {
466
            $form->freeze('language');
467
        }
468
        if ('true' === api_get_setting('profile', 'language')) {
469
            $form->addRule('language', get_lang('Required field'), 'required');
470
        }
471
    }
472
473
    $extraField = new ExtraField('user');
474
    $returnParams = $extraField->addElements($form, api_get_user_id());
475
    $jquery_ready_content = $returnParams['jquery_ready_content'];
476
477
    $htmlHeadXtra[] = '<script>$(function(){ '.$jquery_ready_content.' });</script>';
478
    $form->addButtonNext(get_lang('Next'));
479
    $form->setDefaults($user_data);
480
}
481
482
// -----------------------------------------------------------------------------
483
// JS assets for selective display and question widgets
484
// -----------------------------------------------------------------------------
485
$htmlHeadXtra[] = ch_selectivedisplay::getJs();
486
$htmlHeadXtra[] = survey_question::getJs();
487
488
// -----------------------------------------------------------------------------
489
// Header + page container
490
// -----------------------------------------------------------------------------
491
Display::display_header(get_lang('Surveys'));
492
493
echo '<div class="mx-auto mt-8 bg-white shadow rounded-2xl p-6 border border-gray-50">';
494
echo '<h2 class="text-2xl font-bold text-gray-800 mb-2">'.Security::remove_XSS(strip_tags($survey->getTitle(), '<span>')).'</h2>';
495
496
if (!empty($survey->getSubtitle())) {
497
    echo '<p class="text-gray-600 mb-4">'.Security::remove_XSS($survey->getSubtitle()).'</p>';
498
}
499
500
// Intro (first load)
501
if (!isset($_GET['show']) || (isset($_GET['show']) && '' == $_GET['show'])) {
502
    Session::erase('paged_questions');
503
    Session::erase('page_questions_sec');
504
    $paged_questions_sec = [];
505
    if (!empty($survey->getIntro())) {
506
        echo '<div class="prose prose-slate max-w-none mb-6">'.Security::remove_XSS($survey->getIntro()).'</div>';
507
    }
508
    $limit = 0;
509
}
510
511
// Profile form handling
512
if ($survey->getFormFields() && 0 == $survey->getAnonymous() && is_array($user_data) && !isset($_GET['show'])) {
513
    if ($form->validate()) {
514
        $user_data = $form->exportValues();
515
        if (is_array($user_data) && count($user_data) > 0) {
516
            $sql = "UPDATE $table_user SET";
517
            $update = false;
518
            $allowedFields = ['firstname', 'lastname', 'official_code', 'email', 'phone', 'language'];
519
520
            foreach ($user_data as $key => $value) {
521
                if (in_array($key, $allowedFields)) {
522
                    $sql .= " $key = '".Database::escape_string($value)."',";
523
                    $update = true;
524
                }
525
            }
526
            $sql = rtrim($sql, ',')." WHERE id = $user_id";
527
            if ($update) {
528
                Database::query($sql);
529
            }
530
531
            $extraFieldValue = new ExtraFieldValue('user');
532
            $extraFieldValue->saveFieldValues($user_data);
533
534
            echo Display::return_message(get_lang('Information updated').' '.get_lang('Please fill survey'), 'confirm', false);
535
        }
536
537
        $_GET['show'] = 0;
538
        $show = 0;
539
540
        Session::erase('paged_questions');
541
        Session::erase('page_questions_sec');
542
        $paged_questions_sec = [];
543
    } else {
544
        echo '<div class="mb-4 text-gray-700">'.get_lang('Update information').'</div>';
545
        Session::erase('paged_questions');
546
        Session::erase('page_questions_sec');
547
        $paged_questions_sec = [];
548
        $form->display();
549
    }
550
}
551
552
// -----------------------------------------------------------------------------
553
// Finish screen
554
// -----------------------------------------------------------------------------
555
if (isset($_POST['finish_survey'])) {
556
    echo Display::return_message(get_lang('You have finished this survey.'), 'confirm');
557
    echo '<div class="prose prose-slate">'.Security::remove_XSS($survey->getSurveythanks()).'</div>';
558
559
    SurveyManager::updateSurveyAnswered($survey, $survey_invitation['user_id'], $lpItemId);
560
    SurveyUtil::flagSurveyAsAnswered($survey->getCode(), $survey_invitation['c_id']);
561
562
    if ($courseInfo && !api_is_anonymous() && 'learnpath' !== api_get_origin()) {
563
        echo '<div class="mt-6">';
564
        echo Display::toolbarButton(
565
            get_lang('Return to Course Homepage'),
566
            api_get_course_url($courseInfo['real_id']),
567
            'home-outline'
568
        );
569
        echo '</div>';
570
    }
571
572
    // Close container + footer and exit early
573
    echo '</div>';
574
    Display::display_footer();
575
576
    exit;
577
}
578
579
// -----------------------------------------------------------------------------
580
// Page / question building
581
// -----------------------------------------------------------------------------
582
$shuffle = '';
583
if (1 == $survey->getShuffle()) {
584
    $shuffle = ' BY RAND() ';
585
}
586
587
$pageBreakText = [];
588
$paged_questions = []; // keep this defined for later usage
589
$questions_exists = true;
590
591
if ((isset($_GET['show']) && '' != $_GET['show']) || isset($_POST['personality'])) {
592
    $questions_displayed = [];
593
    $counter = 0;
594
    $select = ' survey_question.parent_id, survey_question.parent_option_id, ';
595
596
    if (0 === $survey->getSurveyType()) {
597
        if (empty($paged_questions)) {
598
            $sql = "SELECT *
599
                    FROM $table_survey_question
600
                    WHERE survey_question NOT LIKE '%{{%'
601
                      AND survey_id = '".$surveyId."'
602
                    ORDER BY sort ASC";
603
            $result = Database::query($sql);
604
            if (0 == Database::num_rows($result)) {
605
                $questions_exists = false;
606
            }
607
            while ($row = Database::fetch_assoc($result)) {
608
                if (1 == $survey->getOneQuestionPerPage()) {
609
                    if ('pagebreak' !== $row['type']) {
610
                        $paged_questions[$counter][] = $row['iid'];
611
                        $counter++;
612
613
                        continue;
614
                    }
615
                } else {
616
                    if ('pagebreak' === $row['type']) {
617
                        $counter++;
618
                        $pageBreakText[$counter] = $row['survey_question'];
619
                    } else {
620
                        $paged_questions[$counter][] = $row['iid'];
621
                    }
622
                }
623
            }
624
            Session::write('paged_questions', $paged_questions);
625
        }
626
627
        // Fix contexts (support ticket #5529)
628
        $courseId = $survey_invitation['c_id'];
629
        Session::write('_cid', $courseId);
630
        Session::write('_real_cid', $courseId);
631
632
        if (array_key_exists($_GET['show'], $paged_questions)) {
633
            if (isset($_GET['user_id'])) {
634
                $my_user_id = 1 == $survey->getAnonymous() ? $surveyUserFromSession : api_get_user_id();
635
636
                $sql = "SELECT
637
                            survey_question.survey_group_sec1,
638
                            survey_question.survey_group_sec2,
639
                            survey_question.survey_group_pri,
640
                            survey_question.iid question_id,
641
                            survey_question.survey_id,
642
                            survey_question.survey_question,
643
                            survey_question.display,
644
                            survey_question.sort,
645
                            survey_question.type,
646
                            survey_question.max_value,
647
                            survey_question_option.iid question_option_id,
648
                            survey_question_option.option_text,
649
                            $select
650
                            survey_question_option.sort as option_sort
651
                        FROM $table_survey_question survey_question
652
                        LEFT JOIN $table_survey_question_option survey_question_option
653
                          ON survey_question.iid = survey_question_option.question_id
654
                         AND survey_question_option.c_id = $courseId
655
                        WHERE survey_question.survey_id = '".$surveyId."'
656
                          AND survey_question.iid NOT IN (
657
                                SELECT sa.question_id
658
                                  FROM ".$table_survey_answer." sa
659
                                 WHERE sa.user='".$my_user_id."')
660
                          AND survey_question.c_id =  $courseId
661
                        ORDER BY survey_question.sort, survey_question_option.sort ASC";
662
            } else {
663
                $sql = "SELECT
664
                            survey_question.survey_group_sec1,
665
                            survey_question.survey_group_sec2,
666
                            survey_question.survey_group_pri,
667
                            survey_question.iid question_id,
668
                            survey_question.survey_id,
669
                            survey_question.survey_question,
670
                            survey_question.display,
671
                            survey_question.sort,
672
                            survey_question.type,
673
                            survey_question.max_value,
674
                            survey_question_option.iid question_option_id,
675
                            survey_question_option.option_text,
676
                            $select
677
                            survey_question_option.sort as option_sort
678
                            ".($allowRequiredSurveyQuestions ? ', survey_question.is_required' : '')."
679
                        FROM $table_survey_question survey_question
680
                        LEFT JOIN $table_survey_question_option survey_question_option
681
                          ON survey_question.iid = survey_question_option.question_id
682
                        WHERE survey_question NOT LIKE '%{{%'
683
                          AND survey_question.survey_id = '".$surveyId."'
684
                          AND survey_question.iid IN (".implode(',', $paged_questions[$_GET['show']]).')
685
                        ORDER BY survey_question.sort, survey_question_option.sort ASC';
686
            }
687
688
            $result = Database::query($sql);
689
            $question_counter_max = Database::num_rows($result);
690
            $counter = 0;
691
            $limit = 0;
692
            $questions = [];
693
            while ($row = Database::fetch_assoc($result)) {
694
                if ('pagebreak' !== $row['type']) {
695
                    $sort = $row['sort'];
696
                    $questions[$sort]['question_id'] = $row['question_id'];
697
                    $questions[$sort]['survey_id'] = $row['survey_id'];
698
                    $questions[$sort]['survey_question'] = $row['survey_question'];
699
                    $questions[$sort]['display'] = $row['display'];
700
                    $questions[$sort]['type'] = $row['type'];
701
                    $questions[$sort]['options'][$row['question_option_id']] = $row['option_text'];
702
                    $questions[$sort]['maximum_score'] = $row['max_value'];
703
                    $questions[$sort]['sort'] = $sort;
704
                    $questions[$sort]['is_required'] = $allowRequiredSurveyQuestions && ($row['is_required'] ?? 0);
705
                    $questions[$sort]['parent_id'] = $row['parent_id'] ?? 0;
706
                    $questions[$sort]['parent_option_id'] = $row['parent_option_id'] ?? 0;
707
                }
708
                $counter++;
709
                if (isset($_GET['show']) && (int) $_GET['show'] >= 0) {
710
                    $lastQuestion = (int) $_GET['show'] - 1;
711
                } else {
712
                    $lastQuestion = (int) $row['question_option_id'];
713
                }
714
            }
715
        }
716
    } elseif (1 === $survey->getSurveyType()) {
717
        $my_survey_id = (int) $survey_invitation['survey_id'];
718
        $current_user = Database::escape_string($survey_invitation['user_id']);
719
720
        if (isset($_POST['personality'])) {
721
            $order = '' == $shuffle ? 'BY sort ASC ' : $shuffle;
722
723
            // Current user results
724
            $results = [];
725
            $sql = "SELECT survey_group_pri, user, SUM(value) as value
726
                    FROM $table_survey_answer as survey_answer
727
                    INNER JOIN $table_survey_question as survey_question
728
                        ON (survey_question.iid = survey_answer.question_id)
729
                    WHERE survey_answer.survey_id='".$my_survey_id."'
730
                      AND survey_answer.user='".$current_user."'
731
                    GROUP BY survey_group_pri
732
                    ORDER BY survey_group_pri";
733
            $result = Database::query($sql);
734
            while ($row = Database::fetch_array($result)) {
735
                $results[] = ['value' => $row['value'], 'group' => $row['survey_group_pri']];
736
            }
737
738
            // Totals by group
739
            $totals = [];
740
            $sql = "SELECT SUM(temp.value) as value, temp.survey_group_pri FROM
741
                    (
742
                        SELECT MAX(value) as value, survey_group_pri, survey_question.iid question_id
743
                        FROM $table_survey_question as survey_question
744
                        INNER JOIN $table_survey_question_option as survey_question_option
745
                            ON (survey_question.iid = survey_question_option.question_id)
746
                        WHERE survey_question.survey_id='".$my_survey_id."'
747
                          AND survey_question.c_id = $courseId
748
                          AND survey_question_option.c_id = $courseId
749
                          AND survey_group_sec1='0' AND survey_group_sec2='0'
750
                        GROUP BY survey_group_pri, survey_question.iid
751
                    ) as temp
752
                    GROUP BY temp.survey_group_pri
753
                    ORDER BY temp.survey_group_pri";
754
            $result = Database::query($sql);
755
            while ($row = Database::fetch_array($result)) {
756
                $totals[] = ['value' => $row['value'], 'group' => $row['survey_group_pri']];
757
            }
758
759
            // Percentages
760
            $final_results = [];
761
            for ($i = 0; $i < count($totals); $i++) {
762
                for ($j = 0; $j < count($results); $j++) {
763
                    if ($totals[$i]['group'] == $results[$j]['group']) {
764
                        $group = $totals[$i]['group'];
765
                        $percent = ($results[$j]['value'] / $totals[$i]['value']);
766
                        $final_results[$group] = $percent;
767
                    }
768
                }
769
            }
770
771
            arsort($final_results);
772
            $groups = array_keys($final_results);
773
            $result = [];
774
            $count_result = 0;
775
            foreach ($final_results as $key => &$sub_result) {
776
                $result[] = ['group' => $key, 'value' => $sub_result];
777
                $count_result++;
778
            }
779
780
            $i = 0;
781
            $group_cant = 0;
782
            $equal_count = 0;
783
            if ($count_result > 0) {
784
                while (1) {
785
                    if (($result[$i]['value'] ?? null) == ($result[$i + 1]['value'] ?? null)) {
786
                        $equal_count++;
787
                    } else {
788
                        break;
789
                    }
790
                    $i++;
791
                }
792
            } else {
793
                $equal_count = 10; // force undefined
794
            }
795
796
            if ($equal_count < 4) {
797
                if (0 === $equal_count || 1 === $equal_count) {
798
                    if (($result[0]['value'] ?? 0) == ($result[1]['value'] ?? 0) && ($result[2]['value'] ?? 0) == ($result[3]['value'] ?? 0)) {
799
                        $group_cant = 1;
800
                    } elseif (($result[0]['value'] ?? 0) != ($result[1]['value'] ?? 0)
801
                        && ($result[1]['value'] ?? 0) == ($result[2]['value'] ?? 0)
802
                        && ($result[2]['value'] ?? 0) == ($result[3]['value'] ?? 0)) {
803
                        $group_cant = 0;
804
                    } else {
805
                        $group_cant = 2;
806
                    }
807
                } else {
808
                    $group_cant = $equal_count;
809
                }
810
811
                if ($group_cant > 0) {
812
                    $secondary = '';
813
                    for ($i = 0; $i <= $group_cant; $i++) {
814
                        $group1 = $groups[$i] ?? null;
815
                        $group2 = $groups[$i + 1] ?? null;
816
                        if (null === $group1 || null === $group2) {
817
                            continue;
818
                        }
819
                        if (2 == $group_cant && $i == $group_cant) {
820
                            $group2 = $groups[0];
821
                        }
822
                        $secondary .= (empty($secondary) ? '' : ' OR ')
823
                            ." ( survey_group_sec1 = '$group1' AND survey_group_sec2 = '$group2') "
824
                            ." OR ( survey_group_sec1 = '$group2' AND survey_group_sec2 = '$group1' ) ";
825
                    }
826
827
                    if (empty($_SESSION['page_questions_sec'])
828
                        && !is_array($_SESSION['page_questions_sec'])
829
                        && count(0 == $_SESSION['page_questions_sec'])) {
830
                        $sql = "SELECT * FROM $table_survey_question
831
                                WHERE survey_id = '".$my_survey_id."'
832
                                  AND ($secondary)
833
                                ORDER BY sort ASC";
834
                        $result = Database::query($sql);
835
                        $counter = 0;
836
                        while ($row = Database::fetch_assoc($result)) {
837
                            if (1 == $survey->getOneQuestionPerPage()) {
838
                                $paged_questions_sec[$counter][] = $row['question_id'];
839
                                $counter++;
840
                            } elseif ('pagebreak' === $row['type']) {
841
                                $counter++;
842
                                $pageBreakText[$counter] = $row['survey_question'];
843
                            } else {
844
                                $paged_questions_sec[$counter][] = $row['question_id'];
845
                            }
846
                        }
847
                        Session::write('page_questions_sec', $paged_questions_sec);
848
                    } else {
849
                        $paged_questions_sec = Session::read('page_questions_sec');
850
                    }
851
852
                    $paged_questions = Session::read('paged_questions');
853
                    if ('' == $shuffle) {
854
                        $shuffle = ' BY survey_question.sort, survey_question_option.sort ASC ';
855
                    }
856
                    $val = (int) $_POST['personality'];
857
                    if (is_array($paged_questions_sec)) {
858
                        $sql = "SELECT
859
                                    survey_question.survey_group_sec1,
860
                                    survey_question.survey_group_sec2,
861
                                    survey_question.survey_group_pri,
862
                                    survey_question.iid question_id,
863
                                    survey_question.survey_id,
864
                                    survey_question.survey_question,
865
                                    survey_question.display,
866
                                    survey_question.sort,
867
                                    survey_question.type,
868
                                    survey_question.max_value,
869
                                    survey_question_option.question_option_id,
870
                                    survey_question_option.option_text,
871
                                    survey_question_option.sort as option_sort
872
                                FROM $table_survey_question survey_question
873
                                LEFT JOIN $table_survey_question_option survey_question_option
874
                                   ON survey_question.iid = survey_question_option.question_id
875
                                WHERE survey_question NOT LIKE '%{{%'
876
                                  AND survey_question.survey_id = '".$my_survey_id."'
877
                                  AND survey_question.iid IN (".implode(',', $paged_questions_sec[$val]).")
878
                                ORDER $shuffle";
879
                        $result = Database::query($sql);
880
                        $question_counter_max = Database::num_rows($result);
881
                        $counter = 0;
882
                        $limit = 0;
883
                        $questions = [];
884
                        while ($row = Database::fetch_assoc($result)) {
885
                            if ('pagebreak' !== $row['type']) {
886
                                $questions[$row['sort']]['question_id'] = $row['question_id'];
887
                                $questions[$row['sort']]['survey_id'] = $row['survey_id'];
888
                                $questions[$row['sort']]['survey_question'] = $row['survey_question'];
889
                                $questions[$row['sort']]['display'] = $row['display'];
890
                                $questions[$row['sort']]['type'] = $row['type'];
891
                                $questions[$row['sort']]['options'][$row['question_option_id']] = $row['option_text'];
892
                                $questions[$row['sort']]['maximum_score'] = $row['max_value'];
893
                                $questions[$row['sort']]['survey_group_sec1'] = $row['survey_group_sec1'];
894
                                $questions[$row['sort']]['survey_group_sec2'] = $row['survey_group_sec2'];
895
                                $questions[$row['sort']]['survey_group_pri'] = $row['survey_group_pri'];
896
                                $questions[$row['sort']]['sort'] = $row['sort'];
897
                            } else {
898
                                break;
899
                            }
900
                            $counter++;
901
                        }
902
                    } else {
903
                        echo get_lang('Survey undefined');
904
                    }
905
                } else {
906
                    echo get_lang('Survey undefined');
907
                }
908
            } else {
909
                echo get_lang('Survey undefined');
910
            }
911
        } else {
912
            // First personality phase
913
            Session::erase('page_questions_sec');
914
            $paged_questions_sec = [];
915
916
            $order_sql = '' == $shuffle ? ' BY question_id ' : $shuffle;
917
918
            if (empty($_SESSION['paged_questions'])) {
919
                $sql = "SELECT * FROM $table_survey_question
920
                        WHERE survey_id = '".$surveyId."'
921
                          AND survey_group_sec1='0'
922
                          AND survey_group_sec2='0'
923
                        ORDER ".$order_sql.' ';
924
                $result = Database::query($sql);
925
                $counter = 0;
926
                while ($row = Database::fetch_assoc($result)) {
927
                    if (1 == $survey->getOneQuestionPerPage()) {
928
                        $paged_questions[$counter][] = $row['question_id'];
929
                        $counter++;
930
                    } else {
931
                        if ('pagebreak' === $row['type']) {
932
                            $counter++;
933
                            $pageBreakText[$counter] = $row['survey_question'];
934
                        } else {
935
                            $paged_questions[$counter][] = $row['question_id'];
936
                        }
937
                    }
938
                }
939
                Session::write('paged_questions', $paged_questions);
940
            } else {
941
                $paged_questions = Session::read('paged_questions');
942
            }
943
944
            $order_sql = '' == $shuffle ? ' BY survey_question.sort, survey_question_option.sort ASC ' : $shuffle;
945
            $val = $_GET['show'] ?? '';
946
            $result = null;
947
            if ('' != $val) {
948
                $imploded = Database::escape_string(implode(',', $paged_questions[$val]));
949
                if ('' != $imploded) {
950
                    $order_sql = ' BY survey_question.sort, survey_question_option.sort ASC ';
951
                    $sql = 'SELECT
952
                                survey_question.survey_group_sec1,
953
                                survey_question.survey_group_sec2,
954
                                survey_question.survey_group_pri,
955
                                survey_question.iid question_id,
956
                                survey_question.survey_id,
957
                                survey_question.survey_question,
958
                                survey_question.display,
959
                                survey_question.sort,
960
                                survey_question.type,
961
                                survey_question.max_value,
962
                                survey_question_option.question_option_id,
963
                                survey_question_option.option_text,
964
                                survey_question_option.sort as option_sort
965
                                '.($allowRequiredSurveyQuestions ? ', survey_question.is_required' : '')."
966
                            FROM $table_survey_question survey_question
967
                            LEFT JOIN $table_survey_question_option survey_question_option
968
                               ON survey_question.iid = survey_question_option.question_id
969
                              AND survey_question_option.c_id = $courseId
970
                            WHERE survey_question NOT LIKE '%{{%'
971
                              AND survey_question.survey_id = '".(int) $survey_invitation['survey_id']."'
972
                              AND survey_question.c_id = $courseId
973
                              AND survey_question.iid IN (".$imploded.")
974
                            ORDER $order_sql";
975
                    $result = Database::query($sql);
976
                    $question_counter_max = Database::num_rows($result);
977
                }
978
            }
979
980
            if (null !== $result) {
981
                $counter = 0;
982
                $limit = 0;
983
                $questions = [];
984
                while ($row = Database::fetch_assoc($result)) {
985
                    if ('pagebreak' !== $row['type']) {
986
                        $questions[$row['sort']]['question_id'] = $row['question_id'];
987
                        $questions[$row['sort']]['survey_id'] = $row['survey_id'];
988
                        $questions[$row['sort']]['survey_question'] = $row['survey_question'];
989
                        $questions[$row['sort']]['display'] = $row['display'];
990
                        $questions[$row['sort']]['type'] = $row['type'];
991
                        $questions[$row['sort']]['options'][$row['question_option_id']] = $row['option_text'];
992
                        $questions[$row['sort']]['maximum_score'] = $row['max_value'];
993
                        $questions[$row['sort']]['is_required'] = $allowRequiredSurveyQuestions && ($row['is_required'] ?? 0);
994
                        $questions[$row['sort']]['survey_group_sec1'] = $row['survey_group_sec1'];
995
                        $questions[$row['sort']]['survey_group_sec2'] = $row['survey_group_sec2'];
996
                        $questions[$row['sort']]['survey_group_pri'] = $row['survey_group_pri'];
997
                        $questions[$row['sort']]['sort'] = $row['sort'];
998
                    }
999
                    $counter++;
1000
                }
1001
            }
1002
        }
1003
    } else {
1004
        echo get_lang('Survey type unknown');
1005
    }
1006
}
1007
1008
// -----------------------------------------------------------------------------
1009
// Page counters / params
1010
// -----------------------------------------------------------------------------
1011
$numberOfPages = SurveyManager::getCountPages($survey);
1012
1013
$show = 0;
1014
if (isset($_GET['show']) && '' != $_GET['show']) {
1015
    $show = (int) $_GET['show'] + 1;
1016
}
1017
1018
$displayFinishButton = true;
1019
if (isset($_GET['show']) && '' != $_GET['show']) {
1020
    $pagesIndexes = array_keys($paged_questions);
1021
    $pagesIndexes[] = count($pagesIndexes);
1022
    if (end($pagesIndexes) <= $show - 1 && empty($_POST)) {
1023
        $displayFinishButton = false;
1024
    }
1025
}
1026
1027
$personality = isset($_POST['personality']) ? (int) $_POST['personality'] + 1 : 0;
1028
1029
$g_c = isset($_GET['course']) ? Security::remove_XSS($_GET['course']) : '';
1030
$g_ic = isset($_GET['invitationcode']) ? Security::remove_XSS($_GET['invitationcode']) : '';
1031
$g_cr = isset($_GET['cidReq']) ? Security::remove_XSS($_GET['cidReq']) : '';
1032
$p_l = isset($_POST['language']) ? Security::remove_XSS($_POST['language']) : '';
1033
1034
$add_parameters = isset($_GET['user_id']) ? '&user_id='.(int) $_GET['user_id'] : '';
1035
1036
$url = api_get_self().'?'.api_get_cidreq().$add_parameters.
1037
    '&course='.$g_c.
1038
    '&invitationcode='.$g_ic.
1039
    '&show='.$show.
1040
    '&iid='.$surveyId;
1041
1042
if (!empty($_GET['language'])) {
1043
    $lang = Security::remove_XSS($_GET['language']);
1044
    $url .= '&language='.$lang;
1045
}
1046
if (!empty($lpItemId)) {
1047
    $url .= '&lp_item_id='.$lpItemId;
1048
}
1049
1050
// -----------------------------------------------------------------------------
1051
// Form
1052
// -----------------------------------------------------------------------------
1053
$form = new FormValidator('question', 'post', $url, null, null, FormValidator::LAYOUT_HORIZONTAL);
1054
$form->addHidden('language', $p_l);
1055
1056
// Numbering control
1057
$showNumber = !SurveyManager::hasDependency($survey);
1058
1059
// -----------------------------------------------------------------------------
1060
// Render questions (cards)
1061
// -----------------------------------------------------------------------------
1062
if (isset($questions) && is_array($questions)) {
1063
    $originalShow = isset($_GET['show']) ? (int) $_GET['show'] : 0;
1064
    $questionCounter = 1;
1065
    if (!empty($originalShow)) {
1066
        $before = 0;
1067
        foreach ($paged_questions as $keyQuestion => $list) {
1068
            if ($originalShow > $keyQuestion) {
1069
                $before += count($list);
1070
            }
1071
        }
1072
        $questionCounter = $before + 1;
1073
    }
1074
1075
    // Page-break caption
1076
    $js = '';
1077
    if (isset($pageBreakText[$originalShow]) && !empty(strip_tags($pageBreakText[$originalShow]))) {
1078
        $form->addHtml('<div class="mb-4 p-3 bg-gray-30 rounded">'.Security::remove_XSS($pageBreakText[$originalShow]).'</div>');
1079
    }
1080
1081
    foreach ($questions as $key => &$question) {
1082
        $ch_type = 'ch_'.$question['type'];
1083
        $questionNumber = $questionCounter;
1084
1085
        // Use concrete question renderer; keep finalAnswer for prefill
1086
        $display = new $ch_type();
1087
        $parent = $question['parent_id'];
1088
        $parentClass = '';
1089
1090
        if (!empty($parent)) {
1091
            $parentClass = ' with_parent with_parent_'.$question['question_id'];
1092
            $parents = survey_question::getParents($question['question_id']);
1093
            if (!empty($parents)) {
1094
                foreach ($parents as $parentId) {
1095
                    $parentClass .= ' with_parent_only_hide_'.$parentId;
1096
                }
1097
            }
1098
        }
1099
1100
        $js .= survey_question::getQuestionJs($question);
1101
1102
        $form->addHtml('<div class="survey_question '.$ch_type.' '.$parentClass.' mb-6 p-4 bg-gray-10 rounded-lg border border-gray-50">');
1103
        if ($showNumber && $survey->isDisplayQuestionNumber()) {
1104
            $form->addHtml('<div class="font-semibold text-blue-700 mb-1"> '.$questionNumber.'. </div>');
1105
        }
1106
        $form->addHtml('<div class="text-gray-800 mb-2">'.Security::remove_XSS($question['survey_question']).'</div>');
1107
1108
        // Prefill user answer if exists
1109
        $userAnswerData = SurveyUtil::get_answers_of_question_by_user($question['survey_id'], $question['question_id'], $lpItemId);
1110
        $finalAnswer = null;
1111
        if (!empty($userAnswerData[$user_id])) {
1112
            $userAnswer = $userAnswerData[$user_id];
1113
1114
            switch ($question['type']) {
1115
                case 'score':
1116
                    $finalAnswer = [];
1117
                    foreach ($userAnswer as $userChoice) {
1118
                        [$choiceId, $choiceValue] = explode('*', $userChoice);
1119
                        $finalAnswer[$choiceId] = $choiceValue;
1120
                    }
1121
1122
                    break;
1123
1124
                case 'percentage':
1125
                    [$choiceId, $choiceValue] = explode('*', current($userAnswer));
1126
                    $finalAnswer = $choiceId;
1127
1128
                    break;
1129
1130
                default:
1131
                    $finalAnswer = $userAnswer;
1132
1133
                    break;
1134
            }
1135
        }
1136
1137
        $display->render($form, $question, $finalAnswer);
1138
        $form->addHtml('</div>');
1139
        $questionCounter++;
1140
    }
1141
1142
    $form->addHtml($js);
1143
}
1144
1145
// -----------------------------------------------------------------------------
1146
// Navigation buttons (Previous / Next / Finish)
1147
// -----------------------------------------------------------------------------
1148
$form->addHtml('<div class="flex justify-between mt-6 gap-3">');
1149
if (
1150
    isset($_GET['show'])
1151
    && $_GET['show'] > 0
1152
    && 'true' === api_get_setting('survey.survey_backwards_enable')
1153
    && 1 === (int) $survey->getOneQuestionPerPage()
1154
) {
1155
    $currentShow = (int) $_GET['show'];
1156
    $prevShow = max(0, $currentShow - 1);
1157
1158
    $prevUrl = api_get_self().'?'.api_get_cidreq().
1159
        '&course='.urlencode($g_c).
1160
        '&invitationcode='.urlencode($g_ic).
1161
        '&iid='.$surveyId.
1162
        '&show='.$prevShow;
1163
1164
    if (!empty($_GET['language'])) {
1165
        $prevUrl .= '&language='.urlencode($_GET['language']);
1166
    }
1167
    if (!empty($lpItemId)) {
1168
        $prevUrl .= '&lp_item_id='.$lpItemId;
1169
    }
1170
    if (isset($_GET['user_id'])) {
1171
        $prevUrl .= '&user_id='.(int) $_GET['user_id'];
1172
    }
1173
1174
    $form->addHtml(
1175
        '<a href="'.$prevUrl.'" class="btn btn--plain-outline">
1176
            <i class="mdi mdi-arrow-left mr-2"></i>'.get_lang('Previous question').'
1177
        </a>'
1178
    );
1179
}
1180
1181
// Next / Start
1182
if ('0' == (string) $survey->getSurveyType()) {
1183
    if (0 == $survey->getShowFormProfile()) {
1184
        if ($show < $numberOfPages) {
1185
            $label = 0 == $show ? get_lang('Start the Survey') : get_lang('Next question');
1186
            $form->addButton('next_survey_page', $label, 'arrow-right', 'success');
1187
        }
1188
        if ($show >= $numberOfPages && $displayFinishButton) {
1189
            $form->addButton('finish_survey', get_lang('Finish survey'), 'check', 'success');
1190
        }
1191
    } else {
1192
        if (isset($_GET['show'])) {
1193
            $pageCount = count($paged_questions);
1194
            if ($show < $pageCount) {
1195
                $label = 0 == $show ? get_lang('Start the Survey') : get_lang('Next question');
1196
                $form->addButton('next_survey_page', $label, 'arrow-right', 'success');
1197
            }
1198
            if ($show >= $pageCount && $displayFinishButton) {
1199
                $form->addButton('finish_survey', get_lang('Finish survey'), 'check', 'success');
1200
            }
1201
        }
1202
    }
1203
} elseif (1 === $survey->getSurveyType()) {
1204
    if (isset($_GET['show']) || isset($_POST['personality'])) {
1205
        $pageCount = count($paged_questions);
1206
        if (!empty($paged_questions_sec) && count($paged_questions_sec) > 0) {
1207
            $pageCount += count($paged_questions_sec);
1208
        } else {
1209
            Session::erase('page_questions_sec');
1210
            $paged_questions_sec = [];
1211
        }
1212
1213
        if (0 === $personality) {
1214
            if (($show <= $pageCount) || !$_GET['show']) {
1215
                $form->addButton('next_survey_page', get_lang('Next'), 'arrow-right', 'success');
1216
                if (0 == $survey->getOneQuestionPerPage()) {
1217
                    if ($personality >= 0) {
1218
                        $form->addHidden('personality', $personality);
1219
                    }
1220
                } else {
1221
                    if ($personality > 0) {
1222
                        $form->addHidden('personality', $personality);
1223
                    }
1224
                }
1225
                if ($pageCount == $show) {
1226
                    $form->addHidden('personality', $personality);
1227
                }
1228
            }
1229
        }
1230
1231
        if ($show > $pageCount && $_GET['show'] && 0 === $personality) {
1232
            $form->addHidden('personality', $personality);
1233
        } elseif ($personality > 0) {
1234
            if (1 == $survey->getOneQuestionPerPage()) {
1235
                if ($show >= $pageCount) {
1236
                    $form->addButton('finish_survey', get_lang('Finish survey'), 'check', 'success');
1237
                } else {
1238
                    $form->addHidden('personality', $personality);
1239
                    $form->addButton('next_survey_page', get_lang('Next'), 'arrow-right', 'success');
1240
                }
1241
            } else {
1242
                $form->addButton('finish_survey', get_lang('Finish survey'), 'check');
1243
            }
1244
        }
1245
    } elseif ('' == $survey->getFormFields() || !is_array($user_data)) {
1246
        $form->addButton('next_survey_page', get_lang('Next'), 'arrow-right', 'success');
1247
    }
1248
}
1249
1250
$form->addHtml('</div>');
1251
1252
// No-questions notice at end
1253
if (isset($_GET['show']) && ($show >= $numberOfPages || empty($questions))) {
1254
    if (false == $questions_exists) {
1255
        echo '<p class="text-gray-600">'.get_lang('There are no questions for this survey').'</p>';
1256
    }
1257
}
1258
1259
// -----------------------------------------------------------------------------
1260
// Render form + close container + footer
1261
// -----------------------------------------------------------------------------
1262
$form->display();
1263
echo '</div>';
1264
Display::display_footer();
1265