-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathResponsePicker.php
More file actions
1398 lines (1246 loc) · 59 KB
/
Copy pathResponsePicker.php
File metadata and controls
1398 lines (1246 loc) · 59 KB
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
if (file_exists(__DIR__ . '/vendor/autoload.php')) {
require_once(__DIR__ . '/vendor/autoload.php');
}
/**
* Add conditional classloader.
*
*/
if (($_GET['test'] ?? '' === 'ResponsePicker') && file_exists(__DIR__ . '/test/ResponsePicker.php')) {
require_once __DIR__ . '/test/ResponsePicker.php';
} else {
class ResponsePicker extends \ls\pluginmanager\PluginBase
{
static protected $description = 'This plugins allows a user to pick which response to work on if multiple candidate responses exist.';
static protected $name = 'ResponsePicker';
protected $storage = 'DbStorage';
private function createEnabled(int $surveyId): bool
{
return (bool) $this->get('create', 'Survey', $surveyId);
}
private function deleteEnabled(int $surveyId): bool
{
return (bool) $this->get('delete', 'Survey', $surveyId);
}
private function viewEnabled(int $surveyId): bool
{
return (bool) $this->get('view', 'Survey', $surveyId);
}
private function updateEnabled(int $surveyId): bool
{
return (bool) $this->get('update', 'Survey', $surveyId);
}
private function repeatEnabled(int $surveyId): bool
{
return (bool) $this->get('repeat', 'Survey', $surveyId);
}
public function init()
{
$this->subscribe('beforeLoadResponse');
// Provides survey specific settings.
$this->subscribe('beforeSurveySettings');
// Saves survey specific settings.
$this->subscribe('newSurveySettings');
$this->subscribe('newDirectRequest');
$this->subscribe('newUnsecureRequest');
}
/**
* @throws CHttpException
* Unsecure means there is no CSRF.
*/
public function newUnsecureRequest() {
if ($this->event->get('target') == __CLASS__) {
/** @var CHttpRequest $request */
$request = $this->event->get('request');
$surveyId = $request->getParam('surveyId');
$responseId = $request->getParam('responseId');
$token = $request->getParam('token');
if (!isset($token, $surveyId, $responseId)) {
throw new \CHttpException(400, "Missing one or more mandatory parameters");
}
switch ($this->event->get("function")) {
case 'copy':
if (!$this->repeatEnabled($surveyId)) {
throw new \CHttpException(403, "Repeating not enabled for this survey");
}
if (!$request->isPostRequest) {
throw new \CHttpException(405, "This endpoint only supports POST");
}
$this->createCopy($surveyId, $responseId, $token);
break;
default:
throw new \CHttpException(404, "Unknown endpoint");
}
}
}
/**
* This function renders a response in a table.
* It uses LS internals which is not according to best practices.
* @param $response
* @param $surveyId
* @throws CException
* @throws Exception
*/
private function viewResponse($response, $surveyId, $language)
{
$aFields = array_keys(createFieldMap($surveyId, 'full', true, false, $language));
App()->loadHelper('admin.exportresults');
App()->loadHelper('export');
\Yii::import('application.helpers.viewHelper');
App()->controller->__set('action', App()->controller->getAction());
$oExport = new \ExportSurveyResultsService();
$oFormattingOptions = new FormattingOptions();
$oFormattingOptions->responseMinRecord = $response['id'];
$oFormattingOptions->responseMaxRecord = $response['id'];
$oFormattingOptions->selectedColumns = $aFields;
$oFormattingOptions->responseCompletionState = 'all';
$oFormattingOptions->headingFormat = 'full';
$oFormattingOptions->answerFormat = 'long';
$oFormattingOptions->output = 'file';
$sTempFile = $oExport->exportSurvey($surveyId, $language, 'json', $oFormattingOptions, '');
$data = array_values(json_decode(file_get_contents($sTempFile), true)['responses'][0])[0];
$out = '<html><head><meta charset="UTF-8"></head>
<title></title><body><table>';
foreach ($data as $key => $value) {
$row = "";
if (!empty($value)) {
$row .= "<tr>";
if (preg_match('/^\{.*\}$/', $key)) {
$row .= "<td style='width: 40%;'><span title='$key'>Computed</span></td>";
} else {
$row .= "<td style='width: 40%;'>$key</td>";
}
if (is_numeric($value)) {
if (abs(intval($value) - floatval($value)) < 0.001) {
$value = intval($value);
} else {
$value = floatval($value);
}
}
$row .= "<td>$value</td></tr>";
}
$out .= $row;
}
$out .= "</table>";
$out .= CHtml::link("Back to list", $this->api->createUrl('survey/index', ['sid' => $surveyId, 'token' => $response['token'], 'lang' => 'en', 'newtest' => 'Y']));
$out .= '</body><style>body { width: 1070px; margin-left: auto; margin-right: auto; } tr:nth-child(even) {background: #f1f1f1}</style></html>';
Yii::app()->getClientScript()->render($out);
echo $out;
}
public function newDirectRequest()
{
if ($this->event->get('target') == __CLASS__) {
/** @var CHttpRequest $request */
$request = $this->event->get('request');
$surveyId = $request->getParam('surveyId');
$responseId = $request->getParam('responseId');
$token = $request->getParam('token');
switch ($this->event->get("function")) {
case 'delete':
if (!$this->deleteEnabled($surveyId)) {
throw new \CHttpException(403, "Deleting not enabled for this survey");
}
if (!$request->isDeleteRequest) {
throw new \CHttpException(405, "This endpoint only supports DELETE");
}
/** @var \Response $response */
$response = Response::model($surveyId)->findByAttributes([
'id' => $responseId,
'token' => $token
]);
if (isset($response)) {
$response->delete();
}
http_response_code(202);
die();
break;
case 'read':
if (!$this->viewEnabled($surveyId)) {
throw new \CHttpException(403, "Viewing not enabled for this survey");
}
$response = $this->api->getResponse($surveyId, $responseId);
if (isset($response)) {
$this->viewResponse($response, $surveyId, $request->getParam('language', 'en'));
} else {
throw new \CHttpException(404, "Response not found.");
}
break;
case 'copy':
if (!$this->repeatEnabled($surveyId)) {
throw new \CHttpException(403, "Repeating not enabled for this survey");
}
if (!$request->isPostRequest) {
throw new \CHttpException(405, "This endpoint only supports POST");
}
$this->createCopy($surveyId, $responseId);
break;
default:
echo "Unknown action.";
}
}
}
/**
* Create a copy of the given response and direct the user to that response.
* @param $surveyId
* @param $responseId
*/
protected function createCopy($surveyId, $responseId, $token = null)
{
if (null === $response = \Response::model($surveyId)->findByPk($responseId)) {
throw new \CHttpException(404, "Response not found.");
}
if (isset($token) && !$response->token === $token) {
throw new \CHttpException(403, "Token not valid");
}
$response->id = null;
$response->isNewRecord = true;
$response->submitdate = null;
$response->lastpage = 1;
$skipColumns = explode("\r\n", $this->get('skipColumns', 'Survey', $surveyId, ""));
$questions = Question::model()->findAllByAttributes([
'sid' => $surveyId,
'parent_qid' => 0,
'title' => $skipColumns
]);
$attributePrefixes = array_map(function (Question $question) {
return "{$question->sid}X{$question->gid}X{$question->qid}";
}, $questions);
/** @var Question $question */
foreach ($attributePrefixes as $prefix) {
foreach ($response->attributeNames() as $attributeName) {
// Test prefix match
if (strpos($attributeName, $prefix) === 0) {
$response->{$attributeName} = null;
}
}
}
$response->save(false);
$location = $this->api->createUrl('survey/index', [
'ResponsePicker' => $response->id,
'sid' => $surveyId,
'token' => $response->token
]);
header('Location: ' . $location);
http_response_code(201);
die();
}
public function beforeLoadResponse()
{
$surveyId = $this->event->get('surveyId');
if ($this->get('enabled', 'Survey', $surveyId) == false) {
return;
}
// Responses to choose from.
$responses = $this->event->get('responses');
$this->defaultLang = 'en';
if (is_array($responses) && count($responses) > 0)
$this->defaultLang = $responses[0]->attributes['startlanguage'];
/**
* @var LSHttpRequest
*/
$request = $this->api->getRequest();
// Only handle get requests.
if ($request->requestType == 'GET') {
$choice = $request->getParam('ResponsePicker');
if (isset($choice)) {
if ($choice == 'new') {
if (!$this->createEnabled($surveyId)) {
throw new \CHttpException(403, "Creation not enabled for this survey");
}
$this->event->set('response', false);
} else {
foreach ($responses as $response) {
if ($response->id == $choice) {
$this->event->set('response', $response);
break;
}
}
}
/*
* Save the choice in the session; if the survey has a
* welcome page, it is displayed and the response is "chosen"
* in the next request (which is a post)
*/
$_SESSION['ResponsePicker'] = isset($response) ? $response->id : $choice;
} else {
$this->renderOptions($request, $responses);
}
} else {
if (isset($_SESSION['ResponsePicker'])) {
$choice = $_SESSION['ResponsePicker'];
unset($_SESSION['ResponsePicker']);
if ($choice == 'new') {
$this->event->set('response', false);
} else {
foreach ($responses as $response) {
if ($response->id == $choice) {
$this->event->set('response', $response);
break;
}
}
}
}
}
}
public function beforeSurveySettings()
{
$event = $this->event;
$settings = [
'name' => get_class($this),
'settings' => [
'enabled' => [
'type' => 'boolean',
'label' => 'Use ResponsePicker for this survey: ',
'current' => $this->get('enabled', 'Survey', $event->get('survey'), 0)
],
'update' => [
'type' => 'boolean',
'label' => 'Enable update button: ',
'current' => $this->get('update', 'Survey', $event->get('survey'), 0)
],
'repeat' => [
'type' => 'boolean',
'label' => 'Enable repeat button: ',
'current' => $this->get('repeat', 'Survey', $event->get('survey'), 0)
],
'view' => [
'type' => 'boolean',
'label' => 'Enable view button: ',
'current' => $this->get('view', 'Survey', $event->get('survey'), 0)
],
'delete' => [
'type' => 'boolean',
'label' => 'Enable delete button: ',
'current' => $this->get('delete', 'Survey', $event->get('survey'), 0)
],
'create' => [
'type' => 'boolean',
'label' => 'Enable create button: ',
'current' => $this->get('create', 'Survey', $event->get('survey'), 0)
],
'columns' => [
'type' => 'text',
'label' => 'Show these columns (One question code per line):',
'help' => 'Enable filtering by adding : and the type of filter (text,select,none), add a title override by appending another :',
'current' => $this->get('columns', 'Survey', $event->get('survey'), "")
],
'skipColumns' => [
'type' => 'text',
'label' => 'Skip these columns during the repeat action',
'current' => $this->get('skipColumns', 'Survey', $event->get('survey'), "")
],
'newheader' => [
'type' => 'string',
'label' => 'Header for new response button:',
'current' => $this->get('newheader', 'Survey', $event->get('survey'), "New response")
],
'updateConfirmation' => [
'type' => 'string',
'label' => 'Update confirmation message',
'current' => $this->get('updateConfirmation', 'Survey', $event->get('survey')),
'help' => 'Leave empty for no confirmation'
],
'repeatConfirmation' => [
'type' => 'string',
'label' => 'Default repeat confirmation message',
'current' => $this->get('repeatConfirmation', 'Survey', $event->get('survey')),
'help' => 'Leave empty for no confirmation'
],
'deleteConfirmation' => [
'type' => 'string',
'label' => 'Default delete confirmation message',
'current' => $this->get('deleteConfirmation', 'Survey', $event->get('survey')),
'help' => 'Leave empty for no confirmation'
]
],
];
$event->set("surveysettings.{$this->id}", $settings);
}
/** Adding double quote is forbidden
* @return void
*/
protected function setTranslations()
{
$this->translation['en']['No data found for'] = 'No data found for';
$this->translation['fr']['No data found for'] = 'Pas de donnée pour';
$this->translation['ar']['No data found for'] = 'لم يتم ايجاد نص ل';
$this->translation['pt']['No data found for'] = 'Sem dados para';
$this->translation['uk']['No data found for'] = 'Немає даних';
$this->translation['en']['Add an update'] = 'Add an update';
$this->translation['fr']['Add an update'] = 'Ajouter une mise à jour';
$this->translation['ar']['Add an update'] = 'إضافة تحديث جديد';
$this->translation['pt']['Add an update'] = 'Acrescentar uma nova resposta';
$this->translation['uk']['Add an update'] = 'Додати нову відповідь';
$this->translation['en']['Update ID'] = 'Update ID';
$this->translation['fr']['Update ID'] = 'Id de la réponse';
$this->translation['ar']['Update ID'] = 'رقم التحديث';
$this->translation['pt']['Update ID'] = 'Codigo de resposta';
$this->translation['uk']['Update ID'] = 'ID відповіді';
$this->translation['en']['Date of update'] = 'Date of update';
$this->translation['fr']['Date of update'] = 'Date de mise à jour';
$this->translation['ar']['Date of update'] = 'تاريخ التحديث';
$this->translation['pt']['Date of update'] = 'Data de actualização';
$this->translation['uk']['Date of update'] = 'Дата оновлення';
$this->translation['en']['Actions'] = 'Actions';
$this->translation['fr']['Actions'] = 'Actions';
$this->translation['ar']['Actions'] = 'إجراءات';
$this->translation['pt']['Actions'] = 'Acções';
$this->translation['uk']['Actions'] = 'Дії';
$this->translation['en']['New'] = 'New';
$this->translation['fr']['New'] = 'Nouveau';
$this->translation['ar']['New'] = 'جديد';
$this->translation['pt']['New'] = 'Novo';
$this->translation['uk']['New'] = 'Нова';
$this->translation['en']['# of updates'] = '# of updates';
$this->translation['fr']['# of updates'] = '# de mises à jour';
$this->translation['ar']['# of updates'] = 'عدد التحديثات';
$this->translation['pt']['# of updates'] = '# de resposta';
$this->translation['uk']['# of updates'] = '# оновлень';
}
/**
* @param string $lang
* @param string $key
* @return string
*/
protected function getTranslation($lang, $key)
{
if (!array_key_exists($lang, $this->translation))
$lang = 'en';
if (!array_key_exists($key, $this->translation[$lang]))
$lang = 'en';
return $this->translation[$lang][$key];
}
/**
* Renders the table containing responses to available for the current token.
* @param \CHttpRequest $request
* @param $responses
*/
protected function renderOptions($request, $responses)
{
$params['sid'] = $request->getParam('sid');
$params['token'] = $request->getParam('token');
$params['lang'] = $request->getParam('lang');
$params['newtest'] = $request->getParam('newtest');
$params['ResponsePicker'] = 'new';
$params = array_filter($params);
$result = [];
foreach ($responses as $response) {
$result[] = [
'data' => $this->api->getResponse($response->surveyId, $response->id),
'urls' => [
'delete' => $this->api->createUrl('plugins/direct', ['plugin' => __CLASS__, 'function' => 'delete', 'surveyId' => $response->surveyId, 'responseId' => $response->id, 'token' => $response->token]),
'read' => $this->api->createUrl('plugins/direct', ['plugin' => __CLASS__, 'function' => 'read', 'surveyId' => $response->surveyId, 'responseId' => $response->id, 'token' => $response->token, 'language' => $params['lang'] ?? 'en']),
'update' => $this->api->createUrl('survey/index', array_merge($params, ['ResponsePicker' => $response->id])),
'copy' => $this->api->createUrl('plugins/direct', ['plugin' => __CLASS__, 'function' => 'copy', 'surveyId' => $response->surveyId, 'responseId' => $response->id]),
],
];
}
$newResponse = $this->api->createUrl('survey/index', $params);
unset($params['ResponsePicker']);
unset($params['lang']);
$baseUrl = $this->api->createUrl('survey/index', $params);
$this->renderHtml($result, $newResponse, $baseUrl, $params['sid'], $request);
}
protected function renderJson($result)
{
header('Content-Type: application/json');
ob_end_clean();
echo json_encode($result, JSON_PRETTY_PRINT);
die();
}
/**
* Render an array of responses as an HTML table.
* @param $result
* @param $sid
* @throws CException
*/
protected function renderHtml($result, $newResponse, $baseUrl, $sid, \CHttpRequest $request)
{
Yii::app()->clientScript->reset();
/** @var CAssetManager $am */
$am = \Yii::app()->assetManager;
\Yii::app()->params['bower-asset'] = $am->publish(__DIR__ . '/vendor/bower-asset', false, -1);
//we set the default language to the survey base language
$baseLang = getSurveyInfo($sid)['language'];
//we get all available languages for the survey
$surveyLang = getSurveyInfo($sid)['additional_languages'];
//if there is a lang in the url we use it, or we use the browser lang
$lang = $request->getParam('lang') !== null ? $request->getParam('lang') : $this->get_browser_language();
$lang = strpos($lang, '-') !== false ? explode('-', $lang)[0] : $lang;
$lang = strtolower($lang);
$availableLanguages[] = $baseLang;
if (strpos($surveyLang, ' ') !== false)
$availableLanguages = array_merge($availableLanguages, explode(' ',$surveyLang));
else if (!empty($surveyLang)) $availableLanguages[] = $surveyLang;
$this->language = $baseLang;
//if the survey has the language then we choose it
if (strpos($surveyLang, $lang) !== false)
$this->language = $lang;
$this->setTranslations();
$columns = [];
if (isset($result[0]['data'])) {
foreach ($result[0]['data'] as $key => $value) {
$columns[$key] = true;
}
}
$template = [];
if ($this->viewEnabled($sid)) {
$template[] = '{view}';
}
if ($this->updateEnabled($sid) && $request->getQuery('editButton', 1)) {
$template[] = '{update}';
}
if ($this->repeatEnabled($sid) && $request->getQuery('copyButton', 1)) {
$template[] = '{repeat}';
}
if ($this->deleteEnabled($sid) && $request->getQuery('deleteButton', 1)) {
$template[] = '{delete}';
}
/*$gridColumns['control'] = [
'name' => '',
'header' => '',
'htmlOptions' => [
'class' => 'open',
'width' => '20px',
],
'filter' => false
];*/
$gridColumns['count'] = [
'name' => 'count',
'header' => $this->getTranslation($this->language, '# of updates'),
'htmlOptions' => [
'width' => '20px',
],
'filter' => false
];
if (!empty($template)) {
$gridColumns['actions'] = [
'header' => 'actions',
'visible' => false,
'htmlOptions' => [
'width' => '100px',
],
'class' => \CButtonColumn::class,
'template' => implode(' ', $template),
'buttons' => [
'view' => [
'label' => '<span class="oi oi-eye"></span>',
'options' => [
'title' => 'View response',
],
'imageUrl' => false,
'url' => function ($data) {
return $data['urls']['read'];
}
],
'update' => [
'label' => '<i class="oi oi-pencil"></i>',
'imageUrl' => false,
'options' => [
'title' => 'Edit response',
'data-confirm' => $this->get('updateConfirmation', 'Survey', $sid)
],
'url' => function ($data) {
return $data['urls']['update'];
}
],
'repeat' => [
'label' => '<i class="oi oi-plus"></i>',
'imageUrl' => false,
'options' => [
'title' => $this->getTranslation($this->language, 'Add an update'),
'data-method' => 'post',
'data-body' => json_encode([
$request->csrfTokenName => $request->csrfToken
]),
'data-confirm' => $this->get('repeatConfirmation', 'Survey', $sid)
],
'url' => function ($data) {
return $data['urls']['copy'];
}
],
'delete' => [
'click' => 'js:function() {}',
'label' => '<i class="oi oi-trash"></i>',
'imageUrl' => false,
'options' => [
'title' => 'Delete data',
'data-confirm' => $this->get('deleteConfirmation', 'Survey', $sid),
'data-method' => 'delete',
'data-body' => json_encode([
$request->csrfTokenName => $request->csrfToken
])
],
'url' => function ($data) {
return $data['urls']['delete'];
}
]
]
];
}
foreach ($result as $item) {
$uoid = $item['data']['UOID'];
$item['uoid'] = $uoid;
if (array_key_exists('Update', $item['data'])) {
$item['data']['Update'] = date('Y-m-d', strtotime($item['data']['Update']));
}
if (!isset($series[$uoid])) {
$series[$uoid] = $item;
}
else
{
if ($series[$uoid]['data']['Update'] < $item['data']['Update']) {
$item['child'] = $series[$uoid]['child'];
$item['child'][] = $item;
unset($series[$uoid]['child']);
$series[$uoid] = $item;
}
else
$series[$uoid]['child'][] = $item;
}
$series[$uoid . "_" . $item['data']['id']] = $item;
$series[$uoid]['count'] = count($series[$uoid]['child']) + 1;
}
$configuredColumns = explode("\r\n", $this->get('columns', 'Survey', $sid, ""));
foreach ($configuredColumns as $column) {
$parts = explode(':', $column);
if (is_array($parts) && $parts[0] == "d") {
$filteredKeys[$parts[1]] = true;
array_shift($parts);
}
list($name, $filter, $title) = array_pad($parts, 3, null);
$question = Question::model()->findByAttributes([
'sid' => $sid,
'title' => $name,
'language' => $this->language
]);
if (isset($question)) {
$answers = [];
foreach (Answer::model()->findAllByAttributes([
'qid' => $question->qid,
'language' => $this->language
]) as $answer) {
$answers[$answer->code] = $answer;
}
$header = $title ?? $question->question;
$header = strpos($header, ':') !== false ? explode(':', $header)[0] : $header;
$gridColumns[$name] = [
'name' => "data.$name",
'header' => $header,
'filter' => empty($filter) || array_key_exists($name,$filteredKeys) ? false : $filter,
];
$advSettings = Question::model()->getAdvancedSettingsWithValues($question->qid, $question->type, $sid, $this->language);
if($question->type == 'D' && isset($advSettings) && array_key_exists('date_format',$advSettings) && array_key_exists('value',$advSettings['date_format']) ) {
$dateFormat = $advSettings['date_format']['value'];
$gridColumns[$name]['value'] = function ($row) use ($dateFormat, $name) {
if(isset($dateFormat) && !empty($row['data'][$name])) {
$formatArr = explode('-',$dateFormat);
if(is_array($formatArr) && count($formatArr) > 0){
$dateFormat = "";
foreach($formatArr as $format) {
if(strpos($format, 'y') !== false)
$dateFormat .= strtoupper($format[0])."-";
else $dateFormat .= $format[0]."-";
}
$dateFormat = rtrim($dateFormat,'-');
}
$time = strtotime($row['data'][$name]);
$row['data'][$name] = date($dateFormat,$time);
}
return $row['data'][$name];
};
}
if (isset($answers) && !empty($answers)) {
$gridColumns[$name]['value'] = function ($row) use ($answers, $name) {
if (isset($answers[$row['data'][$name]])) {
return $answers[$row['data'][$name]]->answer;
} else {
return $this->getTranslation($this->language, 'No data found for') . " $name";
}
};
}
} elseif (isset($row['data'][$name])) {
// Direct property
$gridColumns[$name] = [
'name' => "data.$name",
'header' => $title ?? "Title not configured",
'filter' => empty($filter) ? false : $filter,
];
}
}
foreach($filteredKeys as $key => $value) {
$gridColumns += array_splice($gridColumns,array_search($key,array_keys($gridColumns)),1);
}
if (!array_key_exists('UOID', $gridColumns)) {
$gridColumns['UOID'] = [
'name' => 'data.UOID',
'header' => 'UOID',
'filter' => false
];
}
foreach ($columns as $column => $dummy) {
if (substr($column, 0, 4) == 'DISP') {
$gridColumns[$column] = [
'name' => "data.$column",
'header' => ucfirst($column),
'filter' => 'select-strict'
];
}
}
header('Content-Type: text/html; charset=utf-8');
echo '<html><title></title>';
echo CHtml::tag('body', ['class' => $request->getQuery('seamless', 0) ? 'seamless' : ''], false, false);
if (count($availableLanguages) > 1) {
echo "<select id='languagePicker' class='form-control' onChange='changeLanguage();'>";
foreach ($availableLanguages as $lang) {
$state = $lang == $this->language ? 'selected' : '';
echo "<option value='{$baseUrl}&lang={$lang}' {$state}>{$lang}</option>";
}
echo "</select>";
}
if ($request->getQuery('createButton', 1) && $this->get('create', 'Survey', $sid)) {
echo \CHtml::link(
$this->get('newheader', 'Survey', $sid, "New response"),
$newResponse,
['class' => 'btn btn-primary']
);
}
\Yii::import('zii.widgets.grid.CGridView');
echo Yii::app()->controller->widget(SamIT\Yii1\DataTables\DataTable::class, [
'dataProvider' => new CArrayDataProvider($series, [
'pagination' => [
'pageSize' => 10,
],
'keyField' => false,
'sort' => [
'defaultOrder' => [
'data.id' => CSort::SORT_DESC
]
],
]),
'itemsCssClass' => 'table-bordered table table-striped dataTable',
'pageSizeOptions' => [-1, 10, 25],
'filter' => true,
'columns' => $gridColumns
], true);
$this->registerClientScript(Yii::app()->clientScript);
$updateHeader = "Date of update";
if (array_key_exists('Update', $gridColumns)) {
$updateHeader = strpos($gridColumns['Update']['header'], ':') !== false ? explode(':', $gridColumns['Update']['header'])[0] : $gridColumns['Update']['header'];
} else {
$updateHeader = $this->getTranslation($this->language, 'Date of update');
}
if (array_key_exists('qid', $gridColumns)) {
$idHeader = strpos($gridColumns['qid']['header'], ':') !== false ? explode(':', $gridColumns['qid']['header'])[0] : $gridColumns['qid']['header'];
} else {
$idHeader = $this->getTranslation($this->language, 'Update ID');
}
$responsesColumns = [];
$responsesColumns['actions'] = ["name" => "actions", "header" => $this->getTranslation($this->language, 'Actions'), "filter" => false];
$responsesColumns['Update'] = ["name" => 'update', "header" => $updateHeader, "filter" => false];
$responsesColumns['id'] = ["name" => "responseId", "header" => $idHeader, "filter" => false];
if ($filteredKeys) $responsesColumns = array_merge($responsesColumns,array_intersect_key($gridColumns, $filteredKeys));
$actions = $gridColumns['actions']['buttons'];
$template = explode(' ', $gridColumns['actions']['template']);
foreach ($gridColumns['actions']['buttons'] as $key => $action) {
if (!in_array('{' . $key . '}', $template))
$actions[$key] = null;
}
echo '<script>';
echo "function changeLanguage() {
let lp = document.getElementById('languagePicker');
let url = lp.options[lp.selectedIndex].value;
document.location.href= url;
}";
echo 'let columns = ' . json_encode($responsesColumns) . ';';
echo 'let actions = ' . json_encode($actions) . ';';
echo '</script>';
echo '</body></html>';
die();
}
/**
* Get browser language, given an array of avalaible languages.
*
* @param [array] $availableLanguages Avalaible languages for the site
* @param [string] $default Default language for the site
* @return [string] Language code/prefix
*/
public function get_browser_language($available = [], $default = 'en')
{
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
if (empty($available)) {
return $lang = substr($langs[0], 0, 2);
}
foreach ($langs as $lang) {
$lang = substr($lang, 0, 2);
if (in_array($lang, $available)) {
return $lang;
}
}
}
return $default;
}
/**
* Updates survey settings
*/
public function newSurveySettings()
{
$surveyId = $this->event->get('survey');
foreach ($this->event->get('settings') as $name => $value) {
$this->set($name, $value, 'Survey', $surveyId);
}
}
protected function registerClientScript(\CClientScript $clientScript)
{
$bowerPath = \Yii::app()->params['bower-asset'];
// Bootstrap 4
$clientScript->registerScriptFile("$bowerPath/bootstrap/dist/js/bootstrap.min.js");
$clientScript->registerCssFile("$bowerPath/bootstrap/dist/css/bootstrap.min.css");
// Iconic
$clientScript->registerCssFile("$bowerPath/open-iconic/font/css/open-iconic-bootstrap.min.css");
// Bootbox
$clientScript->registerScriptFile("$bowerPath/bootbox/bootbox.js");
// Iframe resizer
$clientScript->registerScriptFile('https://unpkg.com/iframe-resizer@4.3.1/js/iframeResizer.contentWindow.min.js', CClientScript::POS_HEAD, [
'defer' => true
]);
$clientScript->registerCss('select', <<<CSS
.datatable-view {
padding-top: 16px;
}
table {
-webkit-border-horizontal-spacing: 0px;
-webkit-border-vertical-spacing: 0px;
}
html {
border: none;
}
body {
border: none;
--primary-button-background-color: #4177c1;
--primary-button-color: white;
--main-background-color: #e0e0e0;
background-color: var(--main-background-color);
padding: 20px;
}
a {
color: #5791e1;
}
select {
margin: 0 auto;
max-width: 150px;
}
.btn {
cursor: pointer;
padding: 8px 12px;
border-radius: 6px;
font-size: 14px;
box-shadow: none;
background-image: none;
border: none;
text-decoration: none;
outline: none;
text-align: center;
}
.btn-primary {
background-color: var(--primary-button-background-color);
color: var(--primary-button-color);
border: 1px solid var(--primary-button-background-color);
transition: color 0.2s, background 0.2s, border 0.2s;
text-shadow: none;
}
.btn.new-facility {
float: right;
margin-top: 20px;
}
table,
table.dataTable {
background-color: white;
padding: 0;
overflow: auto;
border-collapse: collapse;
}
.datatable-view {
background: white;
border-radius: 10px;
padding: 20px 25px;
margin-top: 20px;
}
.page-link {
color: var(--primary-button-background-color);
font-size: 13px;
}
.form-control {
font-size: 12px;
height: 38px;
}
div.dataTables_wrapper div.dataTables_length label,
div.dataTables_wrapper div.dataTables_info {
font-size: 12px;
}
.dataTables_wrapper.container-fluid {
margin: 0;
padding: 0;
}
table thead tr th,
.table thead tr th {
background: #f6f6f6;
color: #9d9d9d;
font-family: "Source Sans Pro";
font-weight: 400;
text-transform: uppercase;
font-size: 11px;
padding: 10px;
}
.table tbody tr {
cursor: pointer;
transition: color 0.2s;
}
.table tbody tr:hover td {