-
Notifications
You must be signed in to change notification settings - Fork 0
/
reloadAnyResponse.php
1133 lines (1086 loc) · 45.5 KB
/
reloadAnyResponse.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
/**
* Plugin helper for limesurvey : new class and function allowing to reload any survey
*
* @author Denis Chenu <denis@sondages.pro>
* @copyright 2018-2020 Denis Chenu <http://www.sondages.pro>
* @license AGPL v3
* @version 2.1.4
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
class reloadAnyResponse extends PluginBase {
protected $storage = 'DbStorage';
static protected $description = 'New class and function allowing to reload any survey.';
static protected $name = 'reloadAnyResponse';
static protected $dbVersion = 3;
/**
* @var array[] the settings
*/
protected $settings = array(
'information' => array(
'type' => 'info',
'content' => 'The default settings for all surveys. Remind no system is set in this plugin to show or send link to user.',
),
'allowAdminUser' => array(
'type'=>'checkbox',
'htmlOptions'=>array(
'value'=>1,
'uncheckValue'=>0,
),
'label'=>"Allow admin user to reload any survey with response id.",
'default'=>1,
),
'replaceEditResponse' => array(
'type'=>'checkbox',
'htmlOptions'=>array(
'value'=>1,
'uncheckValue'=>0,
),
'label'=>"Replace edit response in browse response interface.",
'help'=>"When an admin user want to edit an existing response : he was redirected to editing the public survey.",
'default'=>0,
),
'allowTokenUser' => array(
'type'=>'checkbox',
'htmlOptions'=>array(
'value'=>1,
'uncheckValue'=>0,
),
'label'=>"Allow user with a valid token.",
'default'=>1,
),
'uniqueCodeCreate' => array(
'type'=>'checkbox',
'htmlOptions'=>array(
'value'=>1,
'uncheckValue'=>0,
),
'label'=>"Create automatically unique code for all surveys.",
'help'=>"If code exist, it can be always used.",
'default'=>0,
),
'uniqueCodeAccess' => array(
'type'=>'checkbox',
'htmlOptions'=>array(
'value'=>1,
'uncheckValue'=>0,
),
'label'=>"Allow entering unique code for all surveys if exist.",
'help'=>"If you set to no, this disable usage for other plugins.",
'default'=>1,
),
'deleteLinkWhenResponseDeleted' => array(
'type'=>'checkbox',
'htmlOptions'=>array(
'value'=>1,
'uncheckValue'=>0,
),
'label'=>"Delete the link of response when a response is deleted.",
'help'=>"This delete the response link when response is deleted. If you use VV import, don't activate this option.",
'default'=>0,
),
'deleteLinkWhenSurveyDeactivated' => array(
'type'=>'checkbox',
'htmlOptions'=>array(
'value'=>1,
'uncheckValue'=>0,
),
'label'=>"Delete the link of all responses of a survey when it's deactivated.",
'help'=>"Since response table keep the current auto increment value, leave this option can not broke response security.",
'default'=>0,
),
'deleteLinkWhenSurveyDeleted' => array(
'type'=>'checkbox',
'htmlOptions'=>array(
'value'=>1,
'uncheckValue'=>0,
),
'label'=>"Delete the link of all responses of a survey when it's deleted.",
'help'=>"To avoid a big table.",
'default'=>1,
),
'disableMultiAccess' => array(
'type'=>'info',
'content'=>"<div class='alert alert-info'>You need renderMessage for disabling multiple access.</div>",
'default'=>1,
),
'multiAccessTime'=>array(
'type'=>'int',
'label' => 'Time for disable multiple access (in minutes) (config.php settings replace it of not exist)',
'help' => 'Before save value or entering survey : test if someone else edit response in this last minutes. Disable save and show a message if yes. Set to empty disable system but then answer of user can be deleted by another user without any information…',
'htmlOptions'=>array(
'min'=>1,
'placeholder'=>'Disable',
),
'default' => '',
),
'throwErrorRight'=>array(
'type'=>'checkbox',
'htmlOptions'=>array(
'value'=>1,
'uncheckValue'=>0,
),
'label' => 'Throw error when try to edit a response without right (Default)',
'help' => 'Send an http 401 error when srid is in url, but user did ,not have right. Else create a new response (according to survey settings).',
'default' => 0,
),
'noHttpUserAgent'=>array(
'type'=>'select',
'options' => array(
'forbidden' => 'Disable access with a 403',
'action' => 'Allow access and block other access',
),
'htmlOptions'=>array(
'empty'=>'Allow access but don‘t block other access',
),
'label' => 'Action to do without HTTP_USER_AGENT',
'help' => 'By default : show the page but don\'t disable other access. You can choose to send a http 403 error (Forbidden).',
'default' => '',
),
'botRegexp'=>array(
'type'=>'string',
'htmlOptions'=>array(
'placeholder'=>'/bot|crawl|slurp|spider|mediapartners|lua-resty-http/i',
),
'label' => 'Bot regexp',
'help' => 'Usage of preg_match : you can add new bot or invalid request with “|newbot”.',
'default' => '',
),
'botHttpUserAgent'=>array(
'type'=>'select',
'options' => array(
'forbidden' => 'Disable access with a 403',
'action' => 'Allow access and block other access',
),
'htmlOptions'=>array(
'empty'=>'Allow access but don‘t block other access',
),
'label' => 'Action to do with bot',
'help' => 'By default : show the page but don\'t disable other access. You can choose to send a http 403 error (Forbidden).',
'default' => '',
),
//~ 'multiAccessTimeOptOut'=>array(
//~ 'type'=>'int',
//~ 'label' => 'Auto save and close current responses (with a javascript solution) in minutes.',
//~ 'help' => 'If user didn‘t do any action on his browser during access time, save and close the windows. Set to an empty disable this feature.',
//~ 'htmlOptions'=>array(
//~ 'min'=>1,
//~ ),
//~ 'default' => 20,
//~ ),
//~ 'multiAccessTimeAlert'=>array(
//~ 'type'=>'int',
//~ 'label' => 'Time for alert shown for optout of survey',
//~ 'help' => 'Set to empty to disable. This alert is shown after X minutes, where X is the number here.',
//~ 'htmlOptions'=>array(
//~ 'min'=>1,
//~ ),
//~ 'default' => 18,
//~ ),
//~ 'uniqueCodeCode' => array(
//~ 'type'=>'string',
//~ 'label'=>"Code in GET params to test.",
//~ 'default'=>'code',
//~ ),
);
/** @inheritdoc **/
public function init()
{
if (Yii::app() instanceof CConsoleApplication) {
return;
}
$this->subscribe('beforeActivate');
/* Register language string */
$this->subscribe('afterPluginLoad');
/* Managing unique code for Response and SurveyDynamic */
$this->subscribe('afterModelSave');
$this->subscribe('afterModelDelete');
/* Delete related link for Survey */
$this->subscribe('afterSurveySave');
$this->subscribe('afterSurveyDelete');
$this->subscribe('beforeSurveyDeleteMany');
/* Get the survey by srid and code */
/* Save current session */
$this->subscribe('beforeSurveyPage');
/* Replace existing system if srid = new */
$this->subscribe('beforeLoadResponse');
/* Survey settings */
$this->subscribe('beforeSurveySettings');
$this->subscribe('newSurveySettings');
/* delete current session*/
$this->subscribe("afterSurveyComplete",'deleteSurveySession');
$this->subscribe("afterSurveyQuota",'deleteSurveySession');
/* delete current session when unload */
$this->subscribe("newDirectRequest",'newDirectRequest');
/* redirect to editing survey */
$this->subscribe("beforeControllerAction",'beforeControllerAction');
/* Logout remove all session, survey too, then must delete current related surveySessionId */
$this->subscribe("beforeLogout","deleteAllBySessionId");
}
/**
* Delete all related current survey session from this user
* @return @void
*/
public function deleteAllBySessionId()
{
if($this->getEvent()->getEventName() != "beforeLogout") {
return;
}
\reloadAnyResponse\models\surveySession::deleteAllBySessionId();
}
/** @inheritdoc **/
public function getPluginSettings($getValues=true)
{
/* @todo translation of label and help */
return parent::getPluginSettings($getValues);
}
/** @inheritdoc **/
public function beforeSurveySettings()
{
$oEvent = $this->event;
/* currentDefault translation */
$allowAdminUserDefault = $this->get('allowAdminUser',null,null,$this->settings['allowAdminUser']['default']) ? gT('Yes') : gT('No');
$allowTokenDefault = $this->get('allowTokenUser',null,null,$this->settings['allowTokenUser']['default']) ? gT('Yes') : gT('No');
$uniqueCodeCreateDefault = $this->get('uniqueCodeCreate',null,null,$this->settings['uniqueCodeCreate']['default']) ? gT('Yes') : gT('No');
$uniqueCodeAccessDefault = $this->get('uniqueCodeAccess',null,null,$this->settings['uniqueCodeAccess']['default']) ? gT('Yes') : gT('No');
$throwErrorRightDefault = $this->get('throwErrorRight',null,null,$this->settings['throwErrorRight']['default']) ? gT('Yes') : gT('No');
$multiAccessTimeDefault = $this->get('multiAccessTime',null,null,$this->settings['multiAccessTime']['default']) ? $this->get('multiAccessTime',null,null,$this->settings['multiAccessTime']['default']) : gT('Disable');
$oEvent->set("surveysettings.{$this->id}", array(
'name' => get_class($this),
'settings' => array(
'allowAdminUser'=>array(
'type'=>'select',
'label'=>$this->_translate("Allow admin user to reload any response with response id."),
'options'=>array(
1 =>gT("Yes"),
0 =>gT("No"),
),
'htmlOptions'=>array(
'empty' => CHtml::encode(sprintf($this->_translate("Use default (%s)"),$allowAdminUserDefault)),
),
'current'=>$this->get('allowAdminUser','Survey',$oEvent->get('survey'),"")
),
'allowTokenUser'=>array(
'type' => 'select',
'label' => $this->_translate("Allow participant with token to create or reload responses."),
'help' => $this->_translate("Related to “Enable token-based response persistence” and “Allow multiple responses or update responses” survey settings."),
'options'=>array(
1 =>gT("Yes"),
0 =>gT("No"),
),
'htmlOptions'=>array(
'empty' => CHtml::encode(sprintf($this->_translate("Use default (%s)"),$allowTokenDefault)),
),
'current'=>$this->get('allowTokenUser','Survey',$oEvent->get('survey'),"")
),
'uniqueCodeCreate'=>array(
'type'=>'select',
'label'=>$this->_translate("Create unique code automatically."),
'options'=>array(
1 =>gT("Yes"),
0 =>gT("No"),
),
'htmlOptions'=>array(
'empty' => CHtml::encode(sprintf($this->_translate("Use default (%s)"),$uniqueCodeCreateDefault)),
),
'current'=>$this->get('uniqueCodeCreate','Survey',$oEvent->get('survey'),"")
),
'uniqueCodeAccess'=>array(
'type'=>'select',
'label'=>$this->_translate("Allow using unique code if exist."),
'options'=>array(
1 =>gT("Yes"),
0 =>gT("No"),
),
'htmlOptions'=>array(
'empty' => CHtml::encode(sprintf($this->_translate("Use default (%s)"),$uniqueCodeAccessDefault)),
),
'current'=>$this->get('uniqueCodeAccess','Survey',$oEvent->get('survey'),"")
),
'multiAccessTime'=>array(
'type'=>'int',
'label'=>$this->_translate("Time for disable multiple access (in minutes)."),
'help' => $this->_translate("Set to 0 to disable, leave empty for default. If disable : same response can be open at same time; last saved response overwrites the previous one."),
'htmlOptions'=>array(
'min'=>0,
'placeholder' => CHtml::encode(sprintf($this->_translate("Use default (%s)"),$multiAccessTimeDefault)),
),
'current'=>$this->get('multiAccessTime','Survey',$oEvent->get('survey'),"")
),
'throwErrorRight' => array(
'type'=>'select',
'options'=>array(
1 =>gT("Yes"),
0 =>gT("No"),
),
'htmlOptions'=>array(
'empty' => CHtml::encode(sprintf($this->_translate("Use default (%s)"),$throwErrorRightDefault)),
),
'label' => $this->_translate("Throw a 401 error if try to reload without rights."),
'help' => $this->_translate("Send an http 401 error when srid is in url, but user did ,not have right. Else create a new response (according to survey settings)"),
'current'=>$this->get('throwErrorRight','Survey',$oEvent->get('survey'),"")
),
/* Reset to not submitted when open */
'reloadResetSubmitted' => array(
'type'=>'boolean',
'label' => $this->_translate("Reset submitdate when load previous reponse."),
'help' => $this->_translate("Related to “Allow multiple responses or update responses with one token” survey setting."),
'htmlOptions'=>array(
'disabled'=>1
),
'current'=> intval(Survey::model()->findByPk($oEvent->get('survey'))->alloweditaftercompletion != 'Y'),
),
),
));
}
public function beforeControllerAction()
{
if(!$this->get('replaceEditResponse') || !$this->get('allowAdminUser')) {
return;
}
if($this->getEvent()->get("controller") != "admin") {
return;
}
if($this->getEvent()->get("action") != "dataentry") {
return;
}
if($this->getEvent()->get("subaction") != "editdata") {
return;
}
$surveyid = App()->getRequest()->getParam('surveyid');
$srid = App()->getRequest()->getParam('id');
if(!Permission::model()->hasSurveyPermission($surveyid,'response','update')) {
return;
}
$oResponse = Response::model($surveyid)->findByPk($srid);
if(empty($oResponse)) {
return;
}
$surveyLink = Yii::app()->createUrl("survey/index", array('sid' => $surveyid,'srid'=>$srid,'newtest'=>'Y'));
$this->getEvent()->set('run',false);
App()->getController()->redirect($surveyLink);
}
/** @inheritdoc **/
public function newSurveySettings()
{
$event = $this->event;
foreach ($event->get('settings') as $name => $value) {
$this->set($name, $value, 'Survey', $event->get('survey'));
}
}
/** @inheritdoc **/
public function beforeActivate()
{
$this->_createDb();
}
/** @inheritdoc
* Delete all response link when survey is set to active != Y
**/
public function afterSurveySave()
{
if($this->_getCurrentSetting('deleteLinkWhenSurveyDeactivated')) {
$oSurvey = $this->getEvent()->get('model');
if($oSurvey->sid && $oSurvey->active != 'Y') {
$deleted = \reloadAnyResponse\models\responseLink::model()->deleteAll("sid = :sid",array(':sid'=>$oSurvey->sid));
if($deleted>0) { // Don't log each time, can be saved for something other …
$this->log(sprintf("%d responseLink deleted for %d",$deleted,$oSurvey->sid),CLogger::LEVEL_INFO);
}
}
}
}
/** @inheritdoc
* Delete all response link when survey is deleted
**/
public function afterSurveyDelete()
{
if($this->_getCurrentSetting('deleteLinkWhenSurveyDeleted')) {
$oSurvey = $this->getEvent()->get('model');
if($oSurvey->sid) {
$deleted = \reloadAnyResponse\models\responseLink::model()->deleteAll("sid = :sid",array(':sid'=>$oSurvey->sid));
if($deleted>0) { // Don't log each time, can be saved for something other …
$this->log(sprintf("%d responseLink deleted for %d",$deleted,$oSurvey->sid),CLogger::LEVEL_INFO);
}
}
}
}
/** @inheritdoc
* Delete all response link when surveys is deleted
* @todo
**/
public function beforeSurveyDeleteMany()
{
if($this->_getCurrentSetting('deleteLinkWhenSurveyDeleted')) {
$criteria = $this->getEvent()->get('filterCriteria');
}
}
/** @inheritdoc
* Create the response link when survey is started
* Remind : it's better if your plugin create this link directly `$responseLink = \reloadAnyResponse\models\responseLink::setResponseLink($iSurvey,$iResponse,$token);`
* Before 3.15.0 : afterResponseSave event didn't exist
**/
public function afterModelSave()
{
$oModel = $this->getEvent()->get('model');
$className = get_class($oModel);
/* Create responlink for survey and srid (work when start a survey) */
if($className == 'SurveyDynamic' || $className == 'Response') {
$sid = str_replace(array('{{survey_','}}'),array('',''),$oModel->tableName());
/* Test for sid activation */
if(!$this->_getIsActivated('uniqueCodeCreate',$sid)) {
return;
}
$srid = isset($oModel->id) ? $oModel->id : null;
if($sid && $srid) {
$responseLink = \reloadAnyResponse\models\responseLink::model()->findByPk(array('sid'=>$sid,'srid'=>$srid));
/* @todo : add a way to reset potential token ?
* @see https://gitlab.com/SondagesPro/managament/responseListAndManage/blob/80fb8571d394eedda6abfbfd1757c5322f699608/responseListAndManage.php#L2336
**/
if(!$responseLink) {
$token = isset($oModel->token) ? $oModel->token : null;
$responseLink = \reloadAnyResponse\models\responseLink::setResponseLink($sid,$srid,$token);
if(!$responseLink) {
$this->log("Unable to save responseLink with following errors.",CLogger::LEVEL_ERROR);
$this->log(CVarDumper::dumpAsString($responseLink->getErrors()),CLogger::LEVEL_ERROR);
}
}
}
}
}
/**
* @inheritdoc
* Delete related responseLink when a response is deleted
* Before 3.15.0 : afterResponseSave event didn't exist
* This function is in testing currently
**/
public function afterModelDelete()
{
if($this->_getCurrentSetting('deleteLinkWhenResponseDeleted')) {
$oModel = $this->getEvent()->get('model');
$className = get_class($oModel);
if($className == 'SurveyDynamic' || $className == 'Response') {
$sid = str_replace(array('{{survey_','}}'),array('',''),$oModel->tableName());
$srid = isset($oModel->id) ? $oModel->id : null;
if($srid) {
\reloadAnyResponse\models\responseLink::model()->deleteByPk(array('sid'=>$sid,'srid'=>$srid));
}
}
}
}
/** @See event */
public function beforeLoadResponse()
{
$srid = App()->getRequest()->getQuery('srid');
$surveyId = $this->getEvent()->get('surveyId');
$token = App()->getRequest()->getParam('token');
if($srid=='new' && $token && $this->_getIsActivated('allowTokenUser',$surveyId)) {
$this->getEvent()->set('response',false);
return;
}
/* control multi access to token with token and allow edit reponse */
$oSurvey = Survey::model()->findByPk($surveyId);
if($oSurvey && $oSurvey->tokenanswerspersistence == "Y") {
/* Get like limesurvey (in this situation) : get the last srid with this token (without plugin …) */
$oResponse = Response::model($surveyId)->find(array(
'select' => 'id',
'condition' => 'token=:token',
'order' => 'id DESC',
'params' => array('token' => $token)
));
if($oSurvey->alloweditaftercompletion == "Y" || empty($oResponse->submitdate)) {
if($this->_getCurrentSetting('multiAccessTime',$surveyId)
&& $oResponse
&& ($since = \reloadAnyResponse\models\surveySession::getIsUsed($surveyId,$oResponse->id, !$this->noactionByUserAgent()))) {
$this->_endWithEditionMessage($since);
}
if(!$this->noactionByUserAgent()) {
\reloadAnyResponse\models\surveySession::saveSessionTime($surveyId,$oResponse->id);
}
}
}
/* @todo : control what happen with useleft > 1 and tokenanswerspersistence != "Y" */
}
/** @inheritdoc **/
public function beforeSurveyPage()
{
/* Save current session Id to allow same user to reload survey in same browser */
/* resetAllSessionVariables regenerate session id */
/* Keep previous session id, if user reload start url it reset the sessionId, need to leav access */
$surveyid = $this->getEvent()->get('surveyId');
$multiAccessTime = $this->_getCurrentSetting('multiAccessTime',$surveyid);
if($multiAccessTime !== '') {
Yii::app()->setConfig('surveysessiontime_limit',$multiAccessTime);
}
$disableMultiAccess = true;
if($multiAccessTime === '0' /* disable by survey */|| $multiAccessTime === ''/* disable globally */) {
$disableMultiAccess = false;
}
if($disableMultiAccess) {
$this->checkAccessByUserAgent();
}
$this->_fixLanguage($surveyid);
/* For token : @todo in beforeReloadReponse */
/* @todo : delete surveySession is save or clearall action */
if($disableMultiAccess && ($since = \reloadAnyResponse\models\surveySession::getIsUsed($surveyid, null, !$this->noactionByUserAgent()))) {
/* This one is done with current session : maybe allow to keep srid in session and reload it ? */
$this->saveCurrentSrid($surveyid);
killSurveySession($surveyid);
$this->_endWithEditionMessage($since,array(
'comment' => $this->_translate('We save your current session, you can try to reload the survey in some minutes.'),
'class'=>'alert alert-info',
));
}
$srid = App()->getRequest()->getQuery('srid');
if(!$srid && $disableMultiAccess && !$this->noactionByUserAgent()) {
/* Always save current srid if needed , only reload can disable this */
\reloadAnyResponse\models\surveySession::saveSessionTime($surveyid);
if(isset($_SESSION['survey_'.$surveyid]['srid'])) {
$this->_addUnloadScript($surveyid,$_SESSION['survey_'.$surveyid]['srid']);
}
return;
}
$oSurvey = Survey::model()->findByPk($surveyid);
$token = App()->getRequest()->getParam('token');
if($srid == "new") {
// Done in beforeLoadResponse
return;
}
if(!$srid) {
$srid = $this->getCurrentSrid($surveyid);
}
if(!$srid) {
return;
}
//~ $accesscode = App()->getRequest()->getQuery($this->get('uniqueCodeCode'),null,null,$this->settings['uniqueCodeCode']['default']);
$accesscode = App()->getRequest()->getQuery('code');
$editAllowed = false;
if($accesscode && $this->_getIsActivated('uniqueCodeAccess',$surveyid)) {
$responseLink = \reloadAnyResponse\models\responseLink::model()->findByPk(array('sid'=>$surveyid,'srid'=>$srid));
if($responseLink && $responseLink->accesscode == $accesscode) {
$editAllowed = true;
}
if(!$responseLink) {
$this->_HttpException(404,$this->_translate("Sorry, this response didn‘t exist."),$surveyid);
}
if($responseLink && $responseLink->accesscode != $accesscode) {
$this->_HttpException(401,$this->_translate("Sorry, this access code is invalid."),$surveyid);
}
}
if(!$editAllowed && $this->_getIsActivated('allowTokenUser',$surveyid) && $this->_accessibleWithToken($oSurvey)) {
$editAllowed = true;
}
if(!$editAllowed && $this->_getIsActivated('allowAdminUser',$surveyid) && Permission::model()->hasSurveyPermission($surveyid,'responses','update')) {
$editAllowed = true;
}
if(!$editAllowed) {
if($this->_getIsActivated('throwErrorRight',$surveyid)) {
$this->_HttpException(401,$this->_translate("No right on this response"),$surveyid);
}
$this->log("srid used in url without right to reload");
return;
}
if($disableMultiAccess && $since = \reloadAnyResponse\models\surveySession::getIsUsed($surveyid, $srid, !$this->noactionByUserAgent())) {
$this->_endWithEditionMessage($since);
}
$this->_loadReponse($surveyid,$srid,App()->getRequest()->getParam('token'));
$this->_addUnloadScript($surveyid,$srid);
}
/**
* Delete SurveySession for this event srid
*/
public function deleteSurveySession()
{
$surveyId = $this->getEvent()->get('surveyId');
$responseId = $this->getEvent()->get('responseId');
if(!empty($surveyId) && !empty($responseId)) {
\reloadAnyResponse\models\surveySession::model()->deleteByPk(array('sid'=>$surveyId,'srid'=>$responseId));
}
}
/** @inheritdoc **/
public function newDirectRequest()
{
if($this->getEvent()->get('target') != get_class($this)) {
return;
}
$surveyId = Yii::app()->getRequest()->getParam('sid');
$responseId = Yii::app()->getRequest()->getParam('srid');
if($surveyId && $responseId) {
\reloadAnyResponse\models\surveySession::model()->deleteByPk(array('sid'=>$surveyId,'srid'=>$responseId));
}
}
/**
* Add beforeUnload script to delete session
* @param $surveyid
* @param $responseId
* @return @void
*/
private function _addUnloadScript($surveyId,$responseId)
{
$ajaxUrl = Yii::app()->getController()->createUrl('plugins/direct', array('plugin' => get_class($this), 'function' => 'close','sid'=>$surveyId,'srid'=>$responseId));
$onBeforeUnload = "window.onbeforeunload = function(e) {\n";
$onBeforeUnload .= " jQuery.ajax({ url:'{$ajaxUrl}' });\n";
$onBeforeUnload .= "}\n";
Yii::app()->getClientScript()->registerScript("reloadAnyResponseBeforeUnload",$onBeforeUnload,CClientScript::POS_HEAD);
}
/**
* Get boolean value for setting activation
* @param string existing $setting
* @param integer $surveyid
* @return boolean
*/
private function _getIsActivated($setting,$surveyid)
{
$activation = $this->get($setting,'Survey',$surveyid,"");
if($activation === '') {
$activation = $this->get($setting,null,null,$this->settings[$setting]['default']);
}
return (bool) $activation;
}
/**
* Create needed DB
* @return void
*/
private function _createDb()
{
if($this->get("dbVersion") == self::$dbVersion) {
return;
}
/* dbVersion not needed */
if(!$this->api->tableExists($this, 'responseLink') && !$this->api->tableExists($this, 'surveySession')) {
$this->api->createTable($this, 'responseLink', array(
'sid'=>'int not NULL',
'srid'=>'int not NULL',
'token'=>'text',
'accesscode'=>'text',
));
$this->api->createTable($this, 'surveySession', array(
'sid' => 'int not NULL',
'srid' => 'int not NULL',
'token' => 'string(55)',
'session' => 'text',
'lastaction' => 'datetime'
));
$this->set("dbVersion",self::$dbVersion);
return;
}
if(!$this->get("dbVersion")) {
$tableName = $this->api->getTable($this,'surveySession')->tableName();
Yii::app()->getDb()->createCommand()->alterColumn($tableName,'sid','int not NULL');
Yii::app()->getDb()->createCommand()->alterColumn($tableName,'srid','int not NULL');
$tableSchema = App()->getDb()->getSchema()->getTable($tableName);
if(empty($tableSchema->primaryKey)) {
Yii::app()->getDb()->createCommand()->addPrimaryKey('surveysession_sidsrid',$tableName,'sid,srid');
}
$tableName = $this->api->getTable($this,'responseLink')->tableName();
Yii::app()->getDb()->createCommand()->alterColumn($tableName,'sid','int not NULL');
Yii::app()->getDb()->createCommand()->alterColumn($tableName,'srid','int not NULL');
$tableSchema = App()->getDb()->getSchema()->getTable($tableName);
if(empty($tableSchema->primaryKey)) {
Yii::app()->getDb()->createCommand()->addPrimaryKey('responselink_sidsrid',$tableName,'sid,srid');
}
$this->set("dbVersion",self::$dbVersion);
}
if($this->get("dbVersion") < 2 ) {
$tableName = $this->api->getTable($this,'surveySession')->tableName();
Yii::app()->getDb()->createCommand()->alterColumn($tableName,'sid','int not NULL');
Yii::app()->getDb()->createCommand()->alterColumn($tableName,'srid','int not NULL');
$tableName = $this->api->getTable($this,'responseLink')->tableName();
Yii::app()->getDb()->createCommand()->alterColumn($tableName,'sid','int not NULL');
Yii::app()->getDb()->createCommand()->alterColumn($tableName,'srid','int not NULL');
$this->set("dbVersion",2);
}
if($this->get("dbVersion") < 3 ) {
$tableName = $this->api->getTable($this,'surveySession')->tableName();
if(empty(App()->getDb()->getSchema()->getTable($tableName)->primaryKey)) {
Yii::app()->getDb()->createCommand()->addPrimaryKey('surveysession_sidsrid',$tableName,'sid,srid');
}
$tableName = $this->api->getTable($this,'responseLink')->tableName();
if(empty(App()->getDb()->getSchema()->getTable($tableName)->primaryKey)) {
Yii::app()->getDb()->createCommand()->addPrimaryKey('responselink_sidsrid',$tableName,'sid,srid');
}
}
/* all done */
$this->set("dbVersion",self::$dbVersion);
}
/**
* Add this translation just after loaded all plugins
* @see event afterPluginLoad
*/
public function afterPluginLoad(){
$this->_setConfig();
}
/**
* Add needed alias and put it in autoloader,
* add surveysessiontime_limit to global config
* @return void
*/
private function _setConfig()
{
Yii::setPathOfAlias(get_class($this), dirname(__FILE__));
$this->_createDb();
if(!empty(Yii::app()->getConfig('surveysessiontime_limit')) ) {
/* Allow to force surveysessiontime_limit in config.php , to do : show it to admin */
Yii::app()->setConfig('surveysessiontimeDisable',true);
}
if(empty(Yii::app()->getConfig('surveysessiontime_limit')) ) {
Yii::app()->setConfig('surveysessiontime_limit',$this->get('multiAccessTime',null,null,$this->settings['multiAccessTime']['default']));
}
$messageSource=array(
'class' => 'CGettextMessageSource',
'cacheID' => get_class($this).'Lang',
'cachingDuration'=>0,
'forceTranslation' => true,
'useMoFile' => true,
'basePath' => __DIR__ . DIRECTORY_SEPARATOR.'locale',
'catalog'=>'messages',// default from Yii
);
Yii::app()->setComponent(get_class($this).'Messages',$messageSource);
}
/**
* Create Survey and add current response in $_SESSION
* @param integer $surveydi
* @param integer $srid
* @throws Error 404
* @todo : use the new helper
* @return void
*/
private function _loadReponse($surveyid,$srid,$token = null)
{
if(isset($_SESSION['survey_'.$surveyid]['srid']) && $_SESSION['survey_'.$surveyid]['srid'] == $srid) {
return;
}
$oResponse = SurveyDynamic::model($surveyid)->find("id = :srid",array(':srid'=>$srid));
$language = Yii::app()->getLanguage();
if(!$oResponse) {
$this->_HttpException(404, $this->_translate('Response not found.'),$surveyid);
}
$oSurvey = Survey::model()->findByPk($surveyid);
// Validate token : @todo review for admin user
if(!Permission::model()->hasSurveyPermission($surveyid,'response','update') && tableExists('tokens_'.$surveyid) && !empty($oResponse->token)) {
if($oResponse->token != $token) {
$this->_HttpException(401, $this->_translate('Access to this response need a valid token.'),$surveyid);
}
}
killSurveySession($surveyid); // Is this needed ?
LimeExpressionManager::SetDirtyFlag();
$_SESSION['survey_'.$surveyid]['srid'] = $oResponse->id;
if (!empty($oResponse->lastpage)) {
$_SESSION['survey_'.$surveyid]['LEMtokenResume'] = true;
// If the response was completed start at the beginning and not at the last page - just makes more sense
if (empty($oResponse->submitdate)) {
$_SESSION['survey_'.$surveyid]['step'] = $oResponse->lastpage;
}
if(!empty($oResponse->submitdate) && $oSurvey->alloweditaftercompletion != 'Y') {
$oResponse->submitdate = null;
$oResponse->save();
// Better to set Survey to alloweditaftercompletion == 'Y', but unable at this time on afterFindSurvey event
}
}
$_SESSION['survey_'.$surveyid]['s_lang'] = $language; /* buildsurveysession use session lang … , send a notic if not set */
buildsurveysession($surveyid);
if (!empty($oResponse->submitdate)) {
$_SESSION['survey_'.$surveyid]['maxstep'] = $_SESSION['survey_'.$surveyid]['totalsteps'];
}
if (tableExists('tokens_'.$surveyid) && !empty($oResponse->token)) {
$_SESSION['survey_'.$surveyid]['token'] = $oResponse->token;
}
if(version_compare(Yii::app()->getConfig('versionnumber'),"3",">=")) {
randomizationGroupsAndQuestions($surveyid);
initFieldArray($surveyid, $_SESSION['survey_'.$surveyid]['fieldmap']);
}
loadanswers();
$_SESSION['survey_'.$surveyid]['reloadAnyResponse'] = $oResponse->id;
\reloadAnyResponse\models\surveySession::saveSessionTime($surveyid,$oResponse->id);
}
/**
* Create a new response for token
* @todo : validate if we need it or if it's a bug in LS version tested
* @param int $surveyid
* @param string $token
* @return null|\Response
*/
private function _createNewResponse($surveyid,$token) {
$oSurvey = Survey::model()->findByPk($surveyid);
if($this->_accessibleWithToken($oSurvey)) {
return;
}
if($oSurvey->tokenanswerspersistence != "Y") {
return;
}
//~ if($oSurvey->alloweditaftercompletion != "Y") {
//~ return;
//~ }
/* some control */
if(!(
($this->_getIsActivated('allowAdminUser',$surveyid) && Permission::model()->hasSurveyPermission($surveyid,'response','create'))
||
($this->_getIsActivated('allowTokenUser',$surveyid))
)) {
// Disable here
$this->log("Try to create a new reponse with token but without valid rights",'warning');
return;
}
$oToken = Token::model($surveyid)->findByAttributes(array('token' => $token));
if(empty($oToken)) {
return;
}
$oResponse = Response::create($surveyid);
$oResponse->token = $oToken->token;
$oResponse->startlanguage = Yii::app()->getLanguage();
/* @todo generate if not set */
if(version_compare(Yii::app()->getConfig('versionnumber'),"3",">=") ) {
$oResponse->seed = isset($_SESSION['survey_'.$surveyid]['startingValues']['seed']) ? $_SESSION['survey_'.$surveyid]['startingValues']['seed'] : null;
}
$oResponse->lastpage=-1;
if($oSurvey->datestamp == 'Y') {
$date = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig('timeadjust'));
$oResponse->datestamp = $date;
$oResponse->startdate = $date;
}
$oResponse->save();
return $oResponse;
}
/**
* @inheritdoc adding string, by default current event
* @param string
*/
public function log($message, $level = \CLogger::LEVEL_TRACE,$logDetail = null)
{
if(!$logDetail && $this->getEvent()) {
$logDetail = $this->getEvent()->getEventName();
} // What to put if no event ?
parent::log($message, $level);
Yii::log($message, $level,'application.plugins.reloadAnyResponse.'.$logDetail);
}
/**
* Save current srid if exist in specific session
* @return void
*/
public function saveCurrentSrid($surveyId)
{
$currentSrid = isset($_SESSION['survey_'.$surveyId]['srid']) ? $_SESSION['survey_'.$surveyId]['srid'] : null;
if(!$currentSrid) {
return;
}
$sessionCurrentSrid = Yii::app()->session['reloadAnyResponsecurrentSrid'];
if(empty($sessionCurrentSrid)) {
$sessionCurrentSrid = array();
}
$sessionCurrentSrid[$surveyId] = $currentSrid;
Yii::app()->session['reloadAnyResponsecurrentSrid'] = $sessionCurrentSrid[$surveyId];
}
/**
* Get current srid if exist in specific session
* @return integer|null
*/
public function getCurrentSrid($surveyId)
{
$sessionCurrentSrid = Yii::app()->session['reloadAnyResponsecurrentSrid'];
if(empty($sessionCurrentSrid) || empty($sessionCurrentSrid[$surveyId])) {
return;
}
return $sessionCurrentSrid[$surveyId];
}
/**
* Did this survey have token with reload available
* @var \Survey
* @return boolean
*/
private function _accessibleWithToken($oSurvey)
{
Yii::import('application.helpers.common_helper', true);
return $oSurvey->anonymized != "Y" && tableExists("{{tokens_".$oSurvey->sid."}}");
}
/**
* Ending with the delay if renderMessage is available (if not : log as error …)
* @param float $since last edit
* @param string|string[] $comment array with 'comment' and 'class'
* @return void
*/
private function _endWithEditionMessage($since,$comment=null)
{
$messageString = sprintf($this->_translate("Sorry, someone update this response to the questionnaire a short time ago. The last action was made less than %s minutes ago."),ceil($since));
if(!Yii::getPathOfAlias('renderMessage')) {
/* plugin log */
$this->log("You need to download and activate renderMessage plugin for disableMultiAccess",'warning');
/* Yii log as vardump if debug>0 to be shown to user (with red part) */
Yii::log("reloadAnyReponse plugin : You need to download and activate renderMessage plugin for disableMultiAccess", 'warning', 'vardump');
$this->_HttpException("409",$messageString);
return;
}
$message = CHtml::tag("h1",array("class"=>'text-danger'),"409 Conflict");
$message .= CHtml::tag("div",array("class"=>'alert alert-danger'),$messageString);
if($comment) {
if(is_string($comment)) {
$comment = array(
'comment'=> $comment,
'class'=>'alert alert-info',
);
}
$message .= CHtml::tag("div",array("class"=>$comment['class']),$comment['comment']);
}
header($_SERVER["SERVER_PROTOCOL"]." 409 Conflict",true,409);
\renderMessage\messageHelper::renderContent($message);
}
/**
* Check access according to HTTP_USER_AGENT
* @throw Exception
* @return void
*/
private function checkAccessByUserAgent()
{
$noHttpUserAgent = $this->get('noHttpUserAgent',null,null,$this->settings['noHttpUserAgent']['default']);
if(empty($_SERVER['HTTP_USER_AGENT'])) {
if ($noHttpUserAgent == 'forbidden') {
header($_SERVER["SERVER_PROTOCOL"]." 403 No User Agent",true,403);
\renderMessage\messageHelper::renderContent($message);
}
// No action to do : can return
return;
}
$noBotHttpUserAgent = $this->get('botHttpUserAgent',null,null,$this->settings['botHttpUserAgent']['default']);
if ($noBotHttpUserAgent == 'forbidden' && $this->isBotByRegexp($_SERVER['HTTP_USER_AGENT'])) {
header($_SERVER["SERVER_PROTOCOL"]." 403 Bot",true,403);
\renderMessage\messageHelper::renderContent($message);
}
}
/**
* Check if need action (disable access time) by user aganet
* @return boolean
*/
private function noactionByUserAgent()