/
QuestionAdministrationController.php
3087 lines (2805 loc) · 119 KB
/
QuestionAdministrationController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Class QuestionAdministrationController
*/
class QuestionAdministrationController extends LSBaseController
{
/**
* It's import to have the accessRules set (security issue).
* Only logged in users should have access to actions. All other permissions
* should be checked in the action itself.
*
* @return array
*/
public function accessRules()
{
return [
[
'allow',
'actions' => [],
'users' => ['*'], //everybody
],
[
'allow',
'actions' => ['view'],
'users' => ['@'], //only login users
],
['deny'], //always deny all actions not mentioned above
];
}
/**
* This part comes from renderWrappedTemplate
*
* @param string $view View
*
* @return bool
*/
protected function beforeRender($view)
{
if (isset($this->aData['surveyid'])) {
$this->aData['oSurvey'] = $this->aData['oSurvey'] ?? Survey::model()->findByPk($this->aData['surveyid']);
// Needed to evaluate EM expressions in question summary
// See bug #11845
LimeExpressionManager::SetSurveyId($this->aData['surveyid']);
LimeExpressionManager::StartProcessingPage(false, true);
$this->layout = 'layout_questioneditor';
}
return parent::beforeRender($view);
}
/**
* Renders the main view for question editor.
* Main view function prepares the necessary global js parts and renders the HTML for the question editor
*
* @param integer $surveyid Survey ID
* @param integer $gid Group ID
* @param integer $qid Question ID
* @param string $landOnSideMenuTab Name of the side menu tab. Default behavior is to land on structure tab.
*
* @return void
*
* @throws CException
*/
public function actionView($surveyid, $gid = null, $qid = null, $landOnSideMenuTab = 'structure')
{
$this->actionEdit($qid);
}
/**
* Show form to create new question.
*
* @param int $surveyid
* @return void
*/
public function actionCreate($surveyid)
{
$surveyid = (int) $surveyid;
if (!Permission::model()->hasSurveyPermission($surveyid, 'surveycontent', 'create')) {
App()->user->setFlash('error', gT("Access denied"));
$this->redirect(App()->request->urlReferrer);
}
$oSurvey = Survey::model()->findByPk($surveyid);
if (empty($oSurvey)) {
throw new Exception('Internal error: Found no survey with id ' . $surveyid);
}
$oQuestion = $this->getQuestionObject();
$oQuestion->sid = $surveyid;
$this->aData['showSaveAndNewGroupButton'] = true;
$this->aData['showSaveAndNewQuestionButton'] = true;
$this->aData['closeUrl'] = Yii::app()->createUrl(
'questionAdministration/listquestions',
[
'surveyid' => $surveyid
]
);
$this->aData['tabOverviewEditor'] = 'overview';
$this->renderFormAux($oQuestion);
}
/**
* Show question edit form.
*
* @param int $questionId Question ID
* @param string $tabOverviewEditor which tab should be used this can be 'overview' or 'editor'
* @return void
* @throws CHttpException
*/
public function actionEdit(int $questionId, string $tabOverviewEditor = null)
{
$questionId = (int) $questionId;
if (!in_array($tabOverviewEditor, ['overview', 'editor'], true)) {
$tabOverviewEditor = null;
}
/** @var $question Question|null */
$question = Question::model()->findByPk($questionId);
if (empty($question)) {
throw new CHttpException(404, gT("Invalid question id"));
}
if (!Permission::model()->hasSurveyPermission($question->sid, 'surveycontent', 'update')) {
Yii::app()->user->setFlash('error', gT("Access denied"));
$this->redirect(Yii::app()->request->urlReferrer);
}
// "Directly show edit mode" personal setting
if (is_null($tabOverviewEditor)) {
$tabOverviewEditor = SettingsUser::getUserSettingValue('noViewMode', App()->user->id) ? 'editor' : 'overview';
}
$this->aData['closeUrl'] = Yii::app()->createUrl(
'questionAdministration/view/',
[
'surveyid' => $question->sid,
'gid' => $question->gid,
'qid' => $question->qid,
'landOnSideMenuTab' => 'structure'
]
);
$this->aData['tabOverviewEditor'] = $tabOverviewEditor;
$this->renderFormAux($question);
}
/**
* Helper function to render form.
* Used by create and edit actions.
*
* @param Question $question Question
* @return void
* @throws CException
* @todo Move to service class
*/
public function renderFormAux(Question $question)
{
Yii::app()->loadHelper("admin.htmleditor");
Yii::app()->getClientScript()->registerPackage('ace');
Yii::app()->getClientScript()->registerPackage('jquery-ace');
Yii::app()->getClientScript()->registerScript(
'editorfiletype',
"editorfiletype ='javascript';",
CClientScript::POS_HEAD
);
App()->getClientScript()->registerScriptFile(
App()->getConfig('adminscripts') . 'questionEditor.js',
CClientScript::POS_END
);
// TODO: No difference between true and false?
PrepareEditorScript(false, $this);
App()->session['FileManagerContext'] = "edit:survey:{$question->sid}";
initKcfinder();
$this->aData['surveyid'] = $question->sid;
$this->aData['sid'] = $question->sid;
$this->aData['display']['menu_bars']['gid_action'] = 'viewquestion';
$this->aData['questionbar']['buttons']['view'] = true;
$this->aData['sidemenu']['landOnSideMenuTab'] = 'structure';
$this->aData['title_bar']['title'] =
$question->survey->currentLanguageSettings->surveyls_title
. " (" . gT("ID") . ":" . $question->sid . ")";
$this->aData['aQuestionTypeList'] = QuestionTheme::findAllQuestionMetaDataForSelector();
$advancedSettings = $this->getAdvancedOptions($question->qid, $question->type, $question->question_theme_name);
// Remove general settings from this array.
unset($advancedSettings['Attribute']);
// Add <input> with JSON as value, used by JavaScript.
$jsVariablesHtml = $this->renderPartial(
'/admin/survey/Question/_subQuestionsAndAnwsersJsVariables',
[
'anslangs' => $question->survey->allLanguages,
// TODO
'assessmentvisible' => false,
'scalecount' => $question->questionType->answerscales
],
true
);
$showScriptField = Permission::model()->hasSurveyPermission($question->sid, 'surveycontent', 'update') &&
SettingsUser::getUserSettingValue('showScriptEdit', App()->user->id);
// TODO: Problem with CSRF cookie when entering directly after login.
$modalsHtml = Yii::app()->twigRenderer->renderViewFromFile(
'/application/views/questionAdministration/modals.twig',
[],
true
);
// Top Bar
$this->aData['topBar']['name'] = 'questionTopbar_view';
// Save Button
$this->aData['showSaveButton'] = true;
// Save and Close Button
$this->aData['showSaveAndCloseButton'] = true;
// Close Button
$this->aData['showCloseButton'] = true;
// Delete Button
$this->aData['showDeleteButton'] = true;
$this->aData['sid'] = $question->sid;
$this->aData['gid'] = $question->gid;
$this->aData['qid'] = $question->qid;
$this->aData['hasdefaultvalues'] = (QuestionTheme::findQuestionMetaData($question->type)['settings'])->hasdefaultvalues;
$generalSettings = $this->getGeneralOptions(
$question->qid,
$question->type,
$question->gid,
$question->question_theme_name
);
if (App()->session['questionselectormode'] !== 'default') {
$selectormodeclass = App()->session['questionselectormode'];
} else {
$selectormodeclass = App()->getConfig('defaultquestionselectormode');
}
$viewData = [
'oSurvey' => $question->survey,
'oQuestion' => $question,
'aQuestionTypeGroups' => $this->getQuestionTypeGroups($this->aData['aQuestionTypeList']),
'advancedSettings' => $advancedSettings,
'generalSettings' => $generalSettings,
'showScriptField' => $showScriptField,
'jsVariablesHtml' => $jsVariablesHtml,
'modalsHtml' => $modalsHtml,
'selectormodeclass' => $selectormodeclass,
];
$this->aData = array_merge($this->aData, $viewData);
$this->render(
'create',
$viewData
);
}
/**
* Load list questions view for a specified survey by $surveyid
*
* @param int $surveyid Goven Survey ID
* @param string $landOnSideMenuTab Name of the side menu tab (settings or structure). Default behavior is to land on settings tab.
*
* @return string
* @access public
* @todo php warning (Missing return statement)
*/
public function actionListQuestions($surveyid, $landOnSideMenuTab = 'settings')
{
if (!Permission::model()->hasSurveyPermission($surveyid, 'surveycontent', 'read')) {
throw new CHttpException(403, gT("No permission"));
}
$iSurveyID = sanitize_int($surveyid);
if (!in_array($landOnSideMenuTab, ['settings', 'structure', ''])) {
$landOnSideMenuTab = 'settings';
}
// Reinit LEMlang and LEMsid: ensure LEMlang are set to default lang, surveyid are set to this survey id
// Ensure Last GetLastPrettyPrintExpression get info from this sid and default lang
LimeExpressionManager::SetEMLanguage(Survey::model()->findByPk($iSurveyID)->language);
LimeExpressionManager::SetSurveyId($iSurveyID);
LimeExpressionManager::StartProcessingPage(false, true);
// Set number of page
$pageSize = App()->request->getParam('pageSize', null);
if ($pageSize != null) {
App()->user->setState('pageSize', (int) $pageSize);
}
$oSurvey = Survey::model()->findByPk($iSurveyID);
$aData = array();
$aData['oSurvey'] = $oSurvey;
$aData['surveyid'] = $iSurveyID;
$aData['sid'] = $iSurveyID;
$aData['display']['menu_bars']['listquestions'] = true;
$aData['sidemenu']['listquestions'] = true;
$aData['sidemenu']['landOnSideMenuTab'] = $landOnSideMenuTab;
$aData['surveybar']['returnbutton']['url'] = "/surveyAdministration/listsurveys";
$aData["surveyHasGroup"] = $oSurvey->groups;
$aData['subaction'] = gT("Questions in this survey");
$aData['title_bar']['title'] = $oSurvey->currentLanguageSettings->surveyls_title .
" (" . gT("ID") . ":" . $iSurveyID . ")";
// The DataProvider will be build from the Question model, search method
$model = new Question('search');
// Global filter
if (isset($_GET['Question'])) {
$model->setAttributes($_GET['Question'], false);
}
// Filter group
if (isset($_GET['gid'])) {
$model->gid = $_GET['gid'];
}
// Set number of page
if (isset($_GET['pageSize'])) {
App()->user->setState('pageSize', (int) $_GET['pageSize']);
}
$aData['pageSize'] = App()->user->getState('pageSize', App()->params['defaultPageSize']);
// We filter the current survey id
$model->sid = $oSurvey->sid;
$aData['model'] = $model;
$aData['topBar']['name'] = 'baseTopbar_view';
$aData['topBar']['leftSideView'] = 'listquestionsTopbarLeft_view';
$this->aData = $aData;
$this->render("listquestions", $aData);
}
/****
* *** A lot of getter function regarding functionalities and views.
* *** All called via ajax
****/
/**
* Returns all languages in a specific survey as a JSON document
*
* todo: is this action still in use?? where in the frontend?
*
* @param int $iSurveyId
*
* @return void
*/
public function actionGetPossibleLanguages($iSurveyId)
{
$iSurveyId = (int)$iSurveyId;
$aLanguages = Survey::model()->findByPk($iSurveyId)->allLanguages;
$this->renderJSON($aLanguages);
}
/**
* Action called by the FE editor when a save is triggered.
* This is called for both new question and update.
*
* @return void
* @throws CException
*/
public function actionSaveQuestionData()
{
$request = App()->request;
$iSurveyId = (int) $request->getPost('sid');
$sScenario = App()->request->getPost('scenario', '');
$questionData = [];
$questionData['question'] = (array) $request->getPost('question');
// TODO: It's l10n, not i10n.
$questionData['questionI10N'] = (array) $request->getPost('questionI10N');
$questionData['advancedSettings'] = (array) $request->getPost('advancedSettings');
$questionData['question']['sid'] = $iSurveyId;
$calledWithAjax = (int) $request->getPost('ajax');
$question = Question::model()->findByPk((int) $questionData['question']['qid']);
// Different permission check when sid vs qid is given.
// This double permission check is needed if user manipulates the post data.
if (empty($question)) {
if (!Permission::model()->hasSurveyPermission($iSurveyId, 'surveycontent', 'update')) {
Yii::app()->user->setFlash('error', gT("Access denied"));
$this->redirect(Yii::app()->request->urlReferrer);
}
} else {
if (!Permission::model()->hasSurveyPermission($question->sid, 'surveycontent', 'update')) {
Yii::app()->user->setFlash('error', gT("Access denied"));
$this->redirect(Yii::app()->request->urlReferrer);
}
}
// Check the POST data is not truncated
if (!$request->getPost('bFullPOST')) {
$message = gT("The data received seems incomplete. This usually happens due to server limitations ( PHP setting max_input_vars) - please contact your system administrator.");
if ($calledWithAjax) {
echo json_encode(['message' => $message]);
Yii::app()->end();
} else {
$sRedirectUrl = $this->createUrl('questionAdministration/listQuestions', ['surveyid' => $iSurveyId]);
Yii::app()->setFlashMessage($message, 'error');
$this->redirect($sRedirectUrl);
}
}
// Rollback at failure.
$transaction = Yii::app()->db->beginTransaction();
try {
if ($questionData['question']['qid'] == 0) {
$questionData['question']['qid'] = null;
$question = $this->storeNewQuestionData($questionData['question']);
} else {
// Store changes to the actual question data, by either storing it, or updating an old one
$question = $this->updateQuestionData($question, $questionData['question']);
}
// Apply the changes to general settings, advanced settings and translations
$setApplied = [];
$setApplied['questionI10N'] = $this->applyL10n($question, $questionData['questionI10N']);
$setApplied['advancedSettings'] = $this->unparseAndSetAdvancedOptions(
$question,
$questionData['advancedSettings']
);
$setApplied['question'] = $this->unparseAndSetGeneralOptions(
$question,
$questionData['question']
);
// save advanced attributes default values for given question type
if (
array_key_exists('save_as_default', $questionData['question'])
&& $questionData['question']['save_as_default'] == 'Y'
) {
SettingsUser::setUserSetting(
'question_default_values_' . $questionData['question']['type'],
ls_json_encode($questionData['advancedSettings'])
);
} elseif (
array_key_exists('clear_default', $questionData['question'])
&& $questionData['question']['clear_default'] == 'Y'
) {
SettingsUser::deleteUserSetting('question_default_values_' . $questionData['question']['type']);
}
// Clean answer options before save.
// NB: Still inside a database transaction.
$question->deleteAllAnswers();
// If question type has answeroptions, save them.
if ($question->questionType->answerscales > 0) {
$this->storeAnswerOptions(
$question,
$request->getPost('answeroptions')
);
}
if ($question->survey->active == 'N') {
// Clean subquestions before save.
$question->deleteAllSubquestions();
// If question type has subquestions, save them.
if ($question->questionType->subquestions > 0) {
$this->storeSubquestions(
$question,
$request->getPost('subquestions')
);
}
} else {
if ($question->questionType->subquestions > 0) {
$this->updateSubquestions(
$question,
$request->getPost('subquestions')
);
}
}
$transaction->commit();
// All done, redirect to edit form.
$question->refresh();
LimeExpressionManager::SetDirtyFlag();
$tabOverviewEditorValue = $request->getPost('tabOverviewEditor');
//only those two values are valid
if (!($tabOverviewEditorValue === 'overview' || $tabOverviewEditorValue === 'editor')) {
$tabOverviewEditorValue = 'overview';
}
if ($calledWithAjax) {
echo json_encode(['message' => gT('Question saved')]);
Yii::app()->end();
} else {
App()->setFlashMessage(gT('Question saved'), 'success');
$landOnSideMenuTab = 'structure';
if (empty($sScenario)) {
if (App()->request->getPost('save-and-close', '')) {
$sScenario = 'save-and-close';
} elseif (App()->request->getPost('saveandnew', '')) {
$sScenario = 'save-and-new';
} elseif (App()->request->getPost('saveandnewquestion', '')) {
$sScenario = 'save-and-new-question';
}
}
switch ($sScenario) {
case 'save-and-new-question':
$sRedirectUrl = $this->createUrl(
// TODO: Double check
'questionAdministration/create/',
[
'surveyid' => $iSurveyId,
'gid' => $question->gid,
]
);
break;
case 'save-and-new':
$sRedirectUrl = $this->createUrl(
'questionGroupsAdministration/add/',
[
'surveyid' => $iSurveyId,
]
);
break;
case 'save-and-close':
$sRedirectUrl = $this->createUrl(
'questionGroupsAdministration/view/',
[
'surveyid' => $iSurveyId,
'gid' => $question->gid,
'landOnSideMenuTab' => $landOnSideMenuTab,
'mode' => 'overview',
]
);
break;
default:
$sRedirectUrl = $this->createUrl(
'questionAdministration/edit/',
[
'questionId' => $question->qid,
'landOnSideMenuTab' => $landOnSideMenuTab,
'tabOverviewEditor' => $tabOverviewEditorValue,
]
);
}
$this->redirect($sRedirectUrl);
}
} catch (CException $ex) {
$transaction->rollback();
// Determine the proper redirect URL
if (empty($question)) {
$redirectUrl = $this->createUrl('surveyAdministration/view/', ["surveyid" => $iSurveyId]);
} else {
$tabOverviewEditorValue = $request->getPost('tabOverviewEditor');
if ($tabOverviewEditorValue !== 'overview' && $tabOverviewEditorValue !== 'editor') {
$tabOverviewEditorValue = 'overview';
}
$redirectUrl = $this->createUrl(
'questionAdministration/edit/',
[
'questionId' => $question->qid,
'landOnSideMenuTab' => 'structure',
'tabOverviewEditor' => $tabOverviewEditorValue,
]
);
}
// If we are already dealing with a friendly exception (may include detailed errors),
// just set the redirect URL and rethrow.
if ($ex instanceof LSUserException) {
throw $ex->setRedirectUrl($redirectUrl);
}
throw new LSUserException(
500,
$ex->getMessage(),
0,
$redirectUrl
);
}
}
/**
* @todo document me
*
* @param int $iQuestionId
* @param string $sQuestionType
* @param int $gid
* @param boolean $returnArray
* @param string $questionThemeName
*
* @return void|array
* @throws CException
*/
public function actionGetGeneralOptions(
$iQuestionId = null,
$sQuestionType = null,
$gid = null,
$returnArray = false, //todo see were this ajaxrequest is done and take out the parameter there and here
$questionThemeName = null
) {
$aGeneralOptionsArray = $this->getGeneralOptions($iQuestionId, $sQuestionType, $gid, $questionThemeName);
$this->renderJSON($aGeneralOptionsArray);
}
/**
* Collect initial question data
* This either creates a temporary question object, or calls a question object from the database
*
* @param int $iQuestionId
* @param int $gid
* @param string $type
*
* @return void
* @throws CException
*/
public function actionGetQuestionData($iQuestionId = null, $gid = null, $type = null)
{
$iQuestionId = (int)$iQuestionId;
$oQuestion = $this->getQuestionObject($iQuestionId, $type, $gid);
$aQuestionInformationObject = $this->getCompiledQuestionData($oQuestion);
$surveyInfo = $this->getCompiledSurveyInfo($oQuestion);
$aLanguages = [];
$aAllLanguages = getLanguageData(false, App()->session['adminlang']);
$aSurveyLanguages = $oQuestion->survey->getAllLanguages();
array_walk(
$aSurveyLanguages,
function ($lngString) use (&$aLanguages, $aAllLanguages) {
$aLanguages[$lngString] = $aAllLanguages[$lngString]['description'];
}
);
$this->renderJSON(
array_merge(
$aQuestionInformationObject,
[
'surveyInfo' => $surveyInfo,
'languages' => $aLanguages,
'mainLanguage' => $oQuestion->survey->language,
]
)
);
}
/**
* Called via Ajax.
*
* @param int $surveyid
* @param int $gid
* @param string $codes
* @param int $scale_id
* @param int $position
* @param string $assessmentvisible
* @return void
* @todo Permission check hard when both sid and gid are given.
*/
public function actionGetSubquestionRowForAllLanguages($surveyid, $gid, $codes, $scale_id, $position = 0, $assessmentvisible = '')
{
$oSurvey = Survey::model()->findByPk($surveyid);
if (empty($oSurvey)) {
throw new CHttpException(404, gT("Invalid survey id"));
}
if (!Permission::model()->hasSurveyPermission($oSurvey->sid, 'surveycontent', 'update')) {
throw new CHttpException(403, gT("No permission"));
}
$html = [];
$first = true;
$qid = 'new' . rand(0, 99999);
foreach ($oSurvey->allLanguages as $language) {
$html[$language] = $this->getSubquestionRow(
$oSurvey->sid,
$gid,
$qid,
$codes,
$language,
$first,
$scale_id,
$position,
$assessmentvisible
);
$first = false;
}
header('Content-Type: application/json');
echo json_encode($html);
}
/**
* AJAX Method to QuickAdd multiple Rows AJAX-based
* @todo Permission
* @todo Should be GET, not POST
* @return void
*/
public function actionGetSubquestionRowQuickAdd($surveyid, $gid)
{
$qid = '{{quid_placeholder}}';
$request = Yii::app()->request;
$codes = $request->getPost('codes');
$language = $request->getPost('language');
$first = $request->getPost('first');
$scale_id = $request->getPost('scale_id');
$type = $request->getPost('type');
$position = $request->getPost('position');
$assessmentvisible = $request->getPost('assessmentvisible');
echo $this->getSubquestionRow($surveyid, $gid, $qid, $codes, $language, $first, $scale_id, $position, $assessmentvisible);
}
/**
* @todo Permission
* @todo Should be GET, not POST
* @return void
*/
public function actionGetAnswerOptionRowQuickAdd($surveyid, $gid)
{
$qid = '{{quid_placeholder}}';
$request = Yii::app()->request;
$codes = $request->getPost('codes');
$language = $request->getPost('language');
$first = $request->getPost('first');
$scale_id = $request->getPost('scale_id');
$type = $request->getPost('type');
$position = $request->getPost('position');
$assessmentvisible = $request->getPost('assessmentvisible');
echo $this->getAnswerOptionRow($surveyid, $gid, $qid, $codes, $language, $first, $scale_id, $position, $assessmentvisible);
}
/**
* @return void
*/
public function actionGetAnswerOptionRowForAllLanguages($surveyid, $gid, $codes, $scale_id, $position = 0, $assessmentvisible = '')
{
$oSurvey = Survey::model()->findByPk($surveyid);
if (empty($oSurvey)) {
throw new CHttpException(404, gT("Invalid survey id"));
}
if (!Permission::model()->hasSurveyPermission($oSurvey->sid, 'surveycontent', 'update')) {
throw new CHttpException(403, gT("No permission"));
}
$html = [];
$first = true;
$qid = 'new' . rand(0, 99999);
foreach ($oSurvey->allLanguages as $language) {
$html[$language] = $this->getAnswerOptionRow(
$oSurvey->sid,
$gid,
$qid,
$codes,
$language,
$first,
$scale_id,
$position,
$assessmentvisible
);
$first = false;
}
header('Content-Type: application/json');
echo json_encode($html);
}
/**
* It returns a empty subquestion row.
* Used when user clicks "Add new row" in question editor.
*
* @todo Document.
* @todo Too many arguments.
* @param string $codes All previous codes (used to calculate the next code)
* @return string
*/
private function getSubquestionRow($surveyid, $gid, $qid, $codes, $language, $first, $scale_id, $position, $assessmentvisible = '')
{
// index.php/admin/questions/sa/getSubquestionRow/position/1/scale_id/1/surveyid/691948/gid/76/qid/1611/language/en/first/true
// TODO: calcul correct value
$oldCode = false;
// TODO: Fix question type 'A'. Needed?
$oQuestion = $this->getQuestionObject($qid, 'A', $gid);
$oSubquestion = $oQuestion->getEmptySubquestion();
$oSubquestion->qid = $qid; // Set qid as new12345 random id.
//Capture "true" and "false" as strings
if (is_string($first)) {
$first = $first == "false" ? false : true;
}
$stringCodes = json_decode($codes, true);
list($oSubquestion->title, $newPosition) = $this->calculateNextCode($stringCodes);
$activated = false; // You can't add ne subquestion when survey is active
Yii::app()->loadHelper('admin/htmleditor'); // Prepare the editor helper for the view
$view = 'subquestionRow.twig';
$aData = array(
'position' => $position,
'scale_id' => $scale_id,
'activated' => $activated,
'first' => $first,
'surveyid' => $surveyid,
'gid' => $gid,
'qid' => $qid,
'language' => $language,
'question' => '',
'relevance' => '1',
'oldCode' => $oldCode,
'subquestion' => $oSubquestion
);
$html = '<!-- Inserted Row -->';
$html .= App()->twigRenderer->renderPartial('/questionAdministration/' . $view, $aData);
$html .= '<!-- end of Inserted Row -->';
return $html;
}
/**
* @todo docs
* @return string
*/
private function getAnswerOptionRow($surveyid, $gid, $qid, $codes, $language, $first, $scale_id, $position, $assessmentvisible = '')
{
$oldCode = false;
// TODO: Fix question type 'A'. Needed?
$oQuestion = $this->getQuestionObject($qid, 'A', $gid);
$answerOption = $oQuestion->getEmptyAnswerOption();
$answerOption->aid = $qid;
//Capture "true" and "false" as strings
if (is_string($first)) {
$first = $first == "false" ? false : true;
}
$oSurvey = Survey::model()->findByPk($surveyid);
$stringCodes = json_decode($codes, true);
list($answerOption->code, $newPosition) = $this->calculateNextCode($stringCodes);
$activated = false; // You can't add ne subquestion when survey is active
Yii::app()->loadHelper('admin/htmleditor'); // Prepare the editor helper for the view
$view = 'answerOptionRow.twig';
$aData = array(
'assessmentvisible' => Assessment::isAssessmentActive($surveyid),
'assessment_value' => '',
'answerOption' => $answerOption,
'answerOptionl10n' => $answerOption->answerl10ns[$language],
'sortorder' => $newPosition,
'position' => $newPosition,
'scale_id' => $scale_id,
'activated' => $activated,
'first' => $first,
'surveyid' => $surveyid,
'sid' => $surveyid,
'gid' => $gid,
'qid' => $qid,
'language' => $language,
'question' => $oQuestion,
'relevance' => '1',
'oldCode' => $oldCode,
);
$html = '<!-- Inserted Row -->';
$html .= App()->twigRenderer->renderPartial('/questionAdministration/' . $view, $aData);
$html .= '<!-- end of Inserted Row -->';
return $html;
}
/**
* Calculate the next subquestion code based on previous codes.
*
* @param array $stringCodes
* @return array
*/
private function calculateNextCode(array $stringCodes)
{
if (empty($stringCodes)) {
return ['A1', 0];
}
// We get the numerical part of each code and we store them in Arrays
// One array is to store the pure numerical values (so we can search in it for the greates value, and increment it)
// Another array is to store the string values (so we keep all the prefixed "0")
$numCodes = array();
foreach ($stringCodes as $key => $stringCode) {
// This will loop into the code, from the last character to the first letter
$numericSuffix = '';
$n = 1;
$numeric = true;
while ($numeric === true && $n <= strlen($stringCode)) {
$currentCharacter = (string) substr($stringCode, -$n, 1); // get the current character
if (ctype_digit($currentCharacter)) {
// check if it's numerical
$numericSuffix = $currentCharacter . $numericSuffix; // store it in a string
$n = $n + 1;
} else {
$numeric = false; // At first non numeric character found, the loop is stoped
}
}
$numCodesWithZero[$key] = (string) $numericSuffix; // In string type, we can have : "0001"
$numCodes[$key] = (int) $numericSuffix; // In int type, we can only have : "1"
}
// Let's get the greatest code
$greatestNumCode = max($numCodes); // greatest code
$key = array_keys($numCodes, max($numCodes)); // its key (same key in all tables)
$greatesNumCodeWithZeros = (isset($numCodesWithZero)) ? $numCodesWithZero[$key[0]] : ''; // its value with prefixed 0 (like : 001)
$stringCodeOfGreatestCode = $stringCodes[$key[0]]; // its original submitted string (like: SQ001)
// We get the string part of it: it's the original string code, without the greates code with its 0 :
// like substr ("SQ001", (strlen(SQ001)) - strlen(001) ) ==> "SQ"
$stringPartOfNewCode = (string) substr($stringCodeOfGreatestCode, 0, (strlen($stringCodeOfGreatestCode) - strlen($greatesNumCodeWithZeros)));
// We increment by one the greatest code
$numericalPartOfNewCode = $greatestNumCode + 1;
// We get the list of 0 : (using $numericalPartOfNewCode will remove the excedent 0 ; SQ009 will be followed by SQ010 )
$listOfZero = (string) substr($greatesNumCodeWithZeros, 0, (strlen($greatesNumCodeWithZeros) - strlen($numericalPartOfNewCode)));
// When no more zero are available we want to be sure that the last 9 unit will not left
// (like in SQ01 => SQ99 ; should become SQ100, not SQ9100)
$listOfZero = $listOfZero == "9" ? '' : $listOfZero;
// We finaly build the new code
return [$stringPartOfNewCode . $listOfZero . $numericalPartOfNewCode, $numericalPartOfNewCode];
}
/**
* Collect the permissions available for a specific question
*
* @param $iQuestionId
*
* @return void
* @throws CException
*/
public function actionGetQuestionPermissions($iQuestionId = null)
{
$iQuestionId = (int)$iQuestionId;
$oQuestion = $this->getQuestionObject($iQuestionId);
$aPermissions = [
"read" => Permission::model()->hasSurveyPermission($oQuestion->sid, 'surveycontent', 'read'),
"update" => Permission::model()->hasSurveyPermission($oQuestion->sid, 'surveycontent', 'update'),
"editorpreset" => App()->session['htmleditormode'],
"script" =>
Permission::model()->hasSurveyPermission($oQuestion->sid, 'surveycontent', 'update')
&& SettingsUser::getUserSetting('showScriptEdit', App()->user->id),
];
$this->renderJSON($aPermissions);
}
/**
* Returns a json document containing the question types
*
* @return void
*/
public function actionGetQuestionTypeList()
{
$this->renderJSON(QuestionType::modelsAttributes());
}
/**
* @todo document me.
* @todo is this used in frontend somewherer? can't find it
*
* @param string $sQuestionType
* @return void
*/
public function actionGetQuestionTypeInformation($sQuestionType)
{
$aTypeInformations = QuestionType::modelsAttributes();
$aQuestionTypeInformation = $aTypeInformations[$sQuestionType];
$this->renderJSON($aQuestionTypeInformation);
}
/**
* Renders the top bar definition for questions as JSON document
*
* @param int $qid
* @return false|null|string|string[]
* @throws CException
*/
public function actionGetQuestionTopbar($qid = null)
{
$oQuestion = $this->getQuestionObject($qid);
$sid = $oQuestion->sid;
$gid = $oQuestion->gid;
$qid = $oQuestion->qid;
$questionTypes = QuestionType::modelsAttributes();
// TODO: Rename Variable for better readability.