-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
surveyChaining.php
1381 lines (1330 loc) · 66.5 KB
/
surveyChaining.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
/**
* Chaining survey
*
* @author Denis Chenu <denis@sondages.pro>
* @copyright 2018-2024 Denis Chenu <http://www.sondages.pro>
* @copyright 2018 DRAAF Bourgogne-Franche-Comte <http://draaf.bourgogne-franche-comte.agriculture.gouv.fr/>
* @license GPL v3
* @version 1.4.2
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU AFFERO 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 surveyChaining extends PluginBase
{
protected $storage = 'DbStorage';
protected static $description = 'Chaining surveys';
protected static $name = 'surveyChaining';
public $allowedPublicMethods = [
'actionSettings',
];
/**
* @var integer dbversion
*/
private $dbversion = 1;
/**
* @var boolean did this done (see issue in limesurvey)
*/
private $done = false;
public function init()
{
/* Config must be set before all other */
Yii::setPathOfAlias('surveyChaining', dirname(__FILE__));
/* Add menu in tool menu */
$this->subscribe('beforeToolsMenuRender');
/* Add menu in tool menu */
$this->subscribe('afterSurveyComplete');
/* */
$this->subscribe('beforeControllerAction');
/* */
$this->subscribe('newDirectRequest');
/* when survey is deleted : must delete all related links */
$this->subscribe('afterSurveyDelete');
}
/** @inheritdoc
* Set the DB if needed
**/
public function beforeControllerAction()
{
$this->_setDb();
}
/** */
public function newDirectRequest()
{
if ($this->getEvent()->get('target') != get_class($this)) {
return;
}
if (!Permission::model()->getUserId()) {
throw new CHttpException(401);
}
$surveyId = App()->getRequest()->getParam('sid');
$destSurveyId = App()->getRequest()->getParam('destsid');
if (!$surveyId || !$destSurveyId) {
throw new CHttpException(500, $this->translate("This action need a survey and a destination survey id"));
}
if (!Permission::model()->hasSurveyPermission($surveyId, 'surveysettings', 'update')) {
throw new CHttpException(403);
}
if (!Permission::model()->hasSurveyPermission($surveyId, 'surveycontent', 'read')) {
throw new CHttpException(403, sprintf($this->translate("You don't have permission to read content on %s"), $surveyId));
}
if (!Permission::model()->hasSurveyPermission($destSurveyId, 'surveycontent', 'update')) {
throw new CHttpException(403, sprintf($this->translate("You don't have permission to set content on %s"), $destSurveyId));
}
$oAnswersAsReadonly = Plugin::model()->find("name = :name", array(":name" => 'answersAsReadonly'));
if (!$oAnswersAsReadonly || !$oAnswersAsReadonly->active) {
$this->_renderJson(array('error' => array('message' => $this->translate("answersAsReadonly plugin didn't exist or is not activated."))));
}
//~ $oSurvey = Survey::model()->findByPk($surveyId);
//~ $oDestSurvey = Survey::model()->findByPk($destSurveyId);
$aSameCode = $this->_getSameCodes($surveyId, $destSurveyId);
if (empty($aSameCode)) {
$this->_renderJson(array(
'error' => array('message' => $this->translate("Survey selected and current survey didn't have any correspondig question.")),
'success' => null,
));
}
$aSameCodeQuestion = array_unique(array_map(function ($emCode) {
$aEmCode = explode("_", $emCode);
return $aEmCode[0];
}, $aSameCode));
$aQidDones = array();
foreach ($aSameCodeQuestion as $qCode) {
$oQuestion = Question::model()->find(
"title = :title and sid = :sid",
array(
":title" => $qCode,
":sid" => $destSurveyId
)
);
if ($oQuestion) {
QuestionAttribute::model()->setQuestionAttribute($oQuestion->qid, 'readonly', 1);
$aQidDones[] = $oQuestion->qid;
}
}
if (empty($aQidDones)) {
$this->_renderJson(
array(
'error' => array('message' => $this->translate("No question set to readonly.")),
'success' => null,
)
);
}
$this->_renderJson(array(
'success' => sprintf($this->translate("Question(s) %s are set to readonly"), implode(',', $aQidDones)),
'error' => null
));
}
/** @inheritdoc **/
public function afterSurveyDelete()
{
/* Delete all link when set a survey is deleted */
$oSurvey = $this->getEvent()->get('model');
if ($oSurvey->sid) {
$deleted = \surveyChaining\models\chainingResponseLink::model()->deleteAll("prevsid = :prevsid OR nextsid =:nextsid", array(':prevsid' => $oSurvey->sid,':nextsid' => $oSurvey->sid));
if ($deleted > 0) { // Don't log each time, can be saved for something other …
$this->log(sprintf("%d chainingResponseLink deleted for %d", $deleted, $oSurvey->sid), CLogger::LEVEL_INFO);
}
}
}
/** @inheritdoc **/
public function beforeToolsMenuRender()
{
$event = $this->getEvent();
$surveyId = $event->get('surveyId');
$aMenuItem = array(
'label' => $this->translate('Survey chaining'),
'iconClass' => 'fa fa-recycle',
'href' => Yii::app()->createUrl(
'admin/pluginhelper',
array(
'sa' => 'sidebody',
'plugin' => get_class($this),
'method' => 'actionSettings',
'surveyId' => $surveyId
)
),
);
if (class_exists("\LimeSurvey\Menu\MenuItem")) {
$menuItem = new \LimeSurvey\Menu\MenuItem($aMenuItem);
} else {
$menuItem = new \ls\menu\MenuItem($aMenuItem);
}
$event->append('menuItems', array($menuItem));
}
/**
* Main function
* @param int $surveyId Survey id
*
* @return string
*/
public function actionSettings($surveyId)
{
if (intval(App()->getConfig('versionnumber')) < 4) {
return $this->actionSettingsLegacy3LTS($surveyId);
}
$oSurvey = Survey::model()->findByPk($surveyId);
if (!$oSurvey) {
throw new CHttpException(404, $this->translate("This survey does not seem to exist."));
}
if (!Permission::model()->hasSurveyPermission($surveyId, 'surveysettings', 'update')) {
throw new CHttpException(403);
}
$aData = array();
$aData['warningString'] = null;
$aData['pluginClass'] = get_class($this);
$aData['surveyId'] = $surveyId;
$aData['title'] = $this->translate("Survey chaining settings");
$aData['assetUrl'] = Yii::app()->assetManager->publish(dirname(__FILE__) . '/assets/');
$aSettings = array();
if (version_compare(App()->getConfig('getQuestionInformationAPI'), "1.13.0") < 0) {
$aNoSettings = array(
'getQuestionInformation' => array(
'type' => 'info',
'content' => "<p class='alert alert-danger'>" . $this->translate("You need getQuestionInformation version 1.13 or up for this plugin")
)
);
$aSettings[$this->translate("Unable to update settings")] = $aNoSettings;
$aData['aSettings'] = $aSettings;
$content = $this->renderPartial('settings', $aData, true);
return $content;
}
if (App()->getRequest()->getPost('save' . get_class($this))) {
PluginSetting::model()->deleteAll(
"plugin_id = :pluginid AND model = :model AND model_id = :sid",
array(":pluginid" => $this->id,":model" => 'Survey',':sid' => $surveyId)
);
$this->set('nextSurvey', App()->getRequest()->getPost('nextSurvey'), 'Survey', $surveyId);
$this->set('findExistingLink', App()->getRequest()->getPost('findExistingLink'), 'Survey', $surveyId);
$this->set('nextEmail', App()->getRequest()->getPost('nextEmail'), 'Survey', $surveyId);
$this->set('nextMessage', App()->getRequest()->getPost('nextMessage'), 'Survey', $surveyId);
$this->set('choiceQuestion', App()->getRequest()->getPost('choiceQuestion'), 'Survey', $surveyId);
if ($this->get('choiceQuestion', 'Survey', $surveyId, null)) {
$title = $this->get('choiceQuestion', 'Survey', $surveyId, null);
$oQuestion = Question::model()->find("sid=:sid and title=:title", array(":sid" => $surveyId, ":title" => $title));
$aoAnswers = Answer::model()->findAll(array(
'condition' => "qid=:qid",
'order' => 'sortorder ASC',
'params' => array(":qid" => $oQuestion->qid)
));
foreach ($aoAnswers as $oAnswers) {
$code = $oAnswers->code;
$this->set('nextSurvey_' . $code, App()->getRequest()->getPost('nextSurvey_' . $code), 'Survey', $surveyId);
$this->set('findExistingLink_' . $code, App()->getRequest()->getPost('findExistingLink_' . $code), 'Survey', $surveyId);
$this->set('nextEmail_' . $code, App()->getRequest()->getPost('nextEmail_' . $code), 'Survey', $surveyId);
$this->set('nextMessage_' . $code, App()->getRequest()->getPost('nextMessage_' . $code), 'Survey', $surveyId);
}
}
if (App()->getRequest()->getPost('save' . get_class($this)) == 'redirect') {
Yii::app()->getController()->redirect(
Yii::app()->getController()->createUrl(
'surveyAdministration/view',
array('surveyid' => $surveyId)
)
);
}
}
$aSettings = array();
/* Basic settings */
//$aWholeSurveys = Survey::model()->with('permission')
$aWholeSurveys = Survey::model()
->permission(Yii::app()->user->getId())
->with('defaultlanguage')
->findAll(array('order' => 'surveyls_title'));
$sHelpSurveyTable = null;
$iNextSurvey = $this->get('nextSurvey', 'Survey', $surveyId, null);
$aNextSettings = array(
'nextSurvey' => array(
'type' => 'select',
'htmlOptions' => array(
'empty' => $this->translate("None"),
),
'label' => $this->translate("Next survey (by default)."),
'options' => CHtml::listData($aWholeSurveys, 'sid', 'defaultlanguage.surveyls_title'),
'current' => $this->get('nextSurvey', 'Survey', $surveyId, null),
'help' => $this->_getHelpFoSurveySetting($surveyId, $this->get('nextSurvey', 'Survey', $surveyId, null)),
),
'findExistingLink' => array(
'type' => 'boolean',
'label' => $this->translate("Update existing response if exist."),
'help' => $this->translate("If you check this settings and a chain already exist with this respone, previous response was updated, else a new empty response was updated. If you want to keep history : disable this setting."),
'current' => $this->get('findExistingLink', 'Survey', $surveyId, 1),
),
'nextEmail' => array(
'type' => 'string',
'label' => $this->translate("Send email to"),
'help' => $this->translate("You can use Expression Manager with question code"),
'current' => $this->get('nextEmail', 'Survey', $surveyId, null),
),
'nextMessage' => array(
'type' => 'select',
'label' => $this->translate("Mail template to use"),
'help' => $this->translate("Mail template from the next survey. If a condition is defined: template depends on the condition. {SURVEYURL} will be replaced by the link to the next survey."),
'htmlOptions' => array(
'empty' => $this->translate("Invitation (Default)"),
),
'options' => array(
"invite" => $this->translate("Invitation"),
"remind" => $this->translate("Reminder"),
"register" => $this->translate("Register"),
"admin_notification" => $this->translate("Admin notification"),
"admin_responses" => $this->translate("Admin detailed response"),
),
'current' => $this->get('nextMessage', 'Survey', $surveyId, null),
),
);
$aSettings[$this->translate("Next survey")] = $aNextSettings;
$surveyColumnsInformation = new \getQuestionInformation\helpers\surveyColumnsInformation($surveyId, App()->getLanguage());
$surveyColumnsInformation->ByEmCode = true;
$surveyColumnsInformation->restrictToType = ['L','O','!'];
$singleChoicesQuestions = $surveyColumnsInformation->allQuestionListData();
$aNextQuestionSettings = array(
'choiceQuestion' => array(
'type' => 'select',
'htmlOptions' => array(
'empty' => $this->translate("None"),
'options' => $singleChoicesQuestions['options'],
),
'label' => $this->translate("Question determining the following survey"),
'options' => $singleChoicesQuestions['data'],
'current' => $this->get('choiceQuestion', 'Survey', $surveyId, null),
'help' => $this->translate("Only single choice question type can be used for survey selection. The list of available answer update after save this settings."),
),
);
$aSettings[$this->translate("Surveys determined by a question inside this survey")] = $aNextQuestionSettings;
/* Text for default */
$sDefaultText = $this->translate("None");
if (!empty($oNextSurvey)) {
$sDefaultText = $this->translate("Current default");
}
if ($this->get('choiceQuestion', 'Survey', $surveyId, null)) {
$title = $this->get('choiceQuestion', 'Survey', $surveyId, null);
$oQuestion = Question::model()->find("sid=:sid and title=:title", array(":sid" => $surveyId, ":title" => $title));
if ($oQuestion) {
if (intval(App()->getConfig('versionnumber') <= 3)) {
$answers = \getQuestionInformation\helpers\surveyAnswers::getAnswers($oQuestion);
} else {
$answers = \getQuestionInformation\helpers\surveyAnswers::getAnswers($oQuestion, App()->getLanguage());
}
foreach ($answers as $code => $answer) {
$aNextSettings = array(
'nextSurvey_' . $code => array(
'type' => 'select',
'htmlOptions' => array(
'empty' => $sDefaultText,
),
'label' => $this->translate("Next survey according to the choice"),
'options' => CHtml::listData($aWholeSurveys, 'sid', 'defaultlanguage.surveyls_title'),
'current' => intval($this->get('nextSurvey_' . $code, 'Survey', $surveyId, null)),
'help' => $this->_getHelpFoSurveySetting($surveyId, $this->get('nextSurvey_' . $code, 'Survey', $surveyId, null)),
),
'findExistingLink_' . $code => array(
'type' => 'boolean',
'label' => $this->translate("Update existing response if exist."),
'current' => $this->get('findExistingLink_' . $code, 'Survey', $surveyId, 1),
),
'nextEmail_' . $code => array(
'type' => 'string',
'label' => $this->translate("Send email to"),
'help' => $this->translate("You can use Expression Manager with question code"),
'current' => $this->get('nextEmail_' . $code, 'Survey', $surveyId, null),
),
'nextMessage_' . $code => array(
'type' => 'select',
'label' => $this->translate("Mail template to use"),
'htmlOptions' => array(
'empty' => $this->translate("Invitation (Default)"),
),
'options' => array(
"invite" => $this->translate("Invitation"),
"remind" => $this->translate("Reminder"),
"register" => $this->translate("Register"),
"admin_notification" => $this->translate("Admin notification"),
"admin_responses" => $this->translate("Admin detailed response"),
),
'current' => $this->get('nextMessage_' . $code, 'Survey', $surveyId, null),
),
);
$aSettings[sprintf($this->translate("Next survey for %s (%s)"), $code, viewHelper::flatEllipsizeText($answer, 1, 60, "…"))] = $aNextSettings;
}
}
}
$aData['aSettings'] = $aSettings;
$content = $this->renderPartial('settings', $aData, true);
return $content;
}
/**
* Main function for 3LST legacy
* @see actionSettings
* @param int $surveyId Survey id
*
* @return string
*/
private function actionSettingsLegacy3LTS($surveyId)
{
$oSurvey = Survey::model()->findByPk($surveyId);
if (!$oSurvey) {
throw new CHttpException(404, $this->translate("This survey does not seem to exist."));
}
if (!Permission::model()->hasSurveyPermission($surveyId, 'surveysettings', 'update')) {
throw new CHttpException(403);
}
if (App()->getRequest()->getPost('save' . get_class($this))) {
PluginSetting::model()->deleteAll("plugin_id = :pluginid AND model = :model AND model_id = :sid", array(":pluginid" => $this->id,":model" => 'Survey',':sid' => $surveyId));
$this->set('nextSurvey', App()->getRequest()->getPost('nextSurvey'), 'Survey', $surveyId);
$this->set('findExistingLink', App()->getRequest()->getPost('findExistingLink'), 'Survey', $surveyId);
$this->set('nextEmail', App()->getRequest()->getPost('nextEmail'), 'Survey', $surveyId);
$this->set('nextMessage', App()->getRequest()->getPost('nextMessage'), 'Survey', $surveyId);
/* Don't update old choice only of choice are updated */
$oldChoice = $this->get('choiceQuestion', 'Survey', $surveyId, null);
$this->set('choiceQuestion', App()->getRequest()->getPost('choiceQuestion'), 'Survey', $surveyId);
if ($this->get('choiceQuestion', 'Survey', $surveyId, null)) {
$title = $this->get('choiceQuestion', 'Survey', $surveyId, null);
$oQuestion = Question::model()->find("sid=:sid and title=:title and language=:language", array(":sid" => $surveyId, ":title" => $title,":language" => $oSurvey->language));
$aoAnswers = Answer::model()->findAll(array(
'condition' => "qid=:qid and language=:language",
'order' => 'sortorder ASC',
'params' => array(":qid" => $oQuestion->qid,":language" => $oSurvey->language)
));
foreach ($aoAnswers as $oAnswers) {
$code = $oAnswers->code;
$this->set('nextSurvey_' . $code, App()->getRequest()->getPost('nextSurvey_' . $code), 'Survey', $surveyId);
$this->set('findExistingLink_' . $code, App()->getRequest()->getPost('findExistingLink_' . $code), 'Survey', $surveyId);
$this->set('nextEmail_' . $code, App()->getRequest()->getPost('nextEmail_' . $code), 'Survey', $surveyId);
$this->set('nextMessage_' . $code, App()->getRequest()->getPost('nextMessage_' . $code), 'Survey', $surveyId);
}
}
if (App()->getRequest()->getPost('save' . get_class($this)) == 'redirect') {
Yii::app()->getController()->redirect(Yii::app()->getController()->createUrl('admin/survey', array('sa' => 'view','surveyid' => $surveyId)));
}
}
$aData = array();
$aData['warningString'] = null;
if (!Yii::getPathOfAlias('getQuestionInformation')) {
$aData['warningString'] = sprintf($this->translate("You must add an activate %s for this plugin."), "<a href='https://gitlab.com/SondagesPro/coreAndTools/getQuestionInformation'>getQuestionInformation</a>");
}
$aSettings = array();
/* Basic settings */
//$aWholeSurveys = Survey::model()->with('permission')
$aWholeSurveys = Survey::model()
->permission(Yii::app()->user->getId())
->with('defaultlanguage')
->findAll(array('order' => 'surveyls_title'));
$sHelpSurveyTable = null;
$iNextSurvey = $this->get('nextSurvey', 'Survey', $surveyId, null);
$aNextSettings = array(
'nextSurvey' => array(
'type' => 'select',
'htmlOptions' => array(
'empty' => $this->translate("None"),
),
'label' => $this->translate("Next survey (by default)."),
'options' => CHtml::listData($aWholeSurveys, 'sid', 'defaultlanguage.surveyls_title'),
'current' => $this->get('nextSurvey', 'Survey', $surveyId, null),
'help' => $this->_getHelpFoSurveySetting($surveyId, $this->get('nextSurvey', 'Survey', $surveyId, null)),
),
'findExistingLink' => array(
'type' => 'boolean',
'label' => $this->translate("Update existing response if exist."),
'help' => $this->translate("If you check this settings and a chain already exist with this respone, previous response was updated, else a new empty response was updated. If you want to keep history : disable this setting."),
'current' => $this->get('findExistingLink', 'Survey', $surveyId, 1),
),
'nextEmail' => array(
'type' => 'string',
'label' => $this->translate("Send email to"),
'help' => $this->translate("You can use Expression Manager with question code"),
'current' => $this->get('nextEmail', 'Survey', $surveyId, null),
),
'nextMessage' => array(
'type' => 'select',
'label' => $this->translate("Mail template to use"),
'htmlOptions' => array(
'empty' => $this->translate("Invitation (Default)"),
),
'options' => array(
"invite" => $this->translate("Invitation"),
"remind" => $this->translate("Reminder"),
"register" => $this->translate("Register"),
"admin_notification" => $this->translate("Admin notification"),
"admin_responses" => $this->translate("Admin detailed response"),
),
'current' => $this->get('nextMessage', 'Survey', $surveyId, null),
),
);
$aSettings[$this->translate("Next survey")] = $aNextSettings;
$oQuestionCriteria = new CDbCriteria();
$oQuestionCriteria->condition = "t.sid =:sid and t.language=:language and parent_qid = 0";
$oQuestionCriteria->params = array(":sid" => $surveyId,":language" => $oSurvey->language);
$oQuestionCriteria->order = "group_order ASC, question_order ASC";
$oQuestionCriteria->addInCondition("type", ['L','O','!']);
$oaQuestion = Question::model()->with('groups')->findAll($oQuestionCriteria);
$aNextQuestionSettings = array(
'choiceQuestion' => array(
'type' => 'select',
'htmlOptions' => array(
'empty' => $this->translate("None"),
),
'label' => $this->translate("Question determining the following survey"),
'options' => CHtml::listData(
$oaQuestion,
'title',
function ($oQuestion) {
return "[" . $oQuestion->title . "] " . viewHelper::flatEllipsizeText($oQuestion->question, 1, 40, "…");
}
),
'current' => $this->get('choiceQuestion', 'Survey', $surveyId, null),
'help' => $this->translate("Only single choice question type can be used for survey selection. The list of available answer update after save this settings."),
),
);
$aSettings[$this->translate("Surveys determined by a question inside this survey")] = $aNextQuestionSettings;
/* Text for default */
$sDefaultText = $this->translate("None");
if (!empty($oNextSurvey)) {
$sDefaultText = $this->translate("Current default");
}
if ($this->get('choiceQuestion', 'Survey', $surveyId, null)) {
$title = $this->get('choiceQuestion', 'Survey', $surveyId, null);
$oQuestion = Question::model()->find("sid=:sid and title=:title and language=:language", array(":sid" => $surveyId, ":title" => $title,":language" => $oSurvey->language));
$aoAnswers = Answer::model()->findAll(array(
'condition' => "qid=:qid and language=:language",
'order' => 'sortorder ASC',
'params' => array(":qid" => $oQuestion->qid,":language" => $oSurvey->language)
));
foreach ($aoAnswers as $oAnswers) {
$code = $oAnswers->code;
$aNextSettings = array(
'nextSurvey_' . $code => array(
'type' => 'select',
'htmlOptions' => array(
'empty' => $sDefaultText,
),
'label' => $this->translate("Next survey according to the choice"),
'options' => CHtml::listData($aWholeSurveys, 'sid', 'defaultlanguage.surveyls_title'),
'current' => intval($this->get('nextSurvey_' . $code, 'Survey', $surveyId, null)),
'help' => $this->_getHelpFoSurveySetting($surveyId, $this->get('nextSurvey_' . $code, 'Survey', $surveyId, null)),
),
'findExistingLink_' . $code => array(
'type' => 'boolean',
'label' => $this->translate("Update existing response if exist."),
'current' => $this->get('findExistingLink_' . $code, 'Survey', $surveyId, 1),
),
'nextEmail_' . $code => array(
'type' => 'string',
'label' => $this->translate("Send email to"),
'help' => $this->translate("You can use Expression Manager with question code"),
'current' => $this->get('nextEmail_' . $code, 'Survey', $surveyId, null),
),
'nextMessage_' . $code => array(
'type' => 'select',
'label' => $this->translate("Mail template to use"),
'htmlOptions' => array(
'empty' => $this->translate("Invitation (Default)"),
),
'options' => array(
"invite" => $this->translate("Invitation"),
"remind" => $this->translate("Reminder"),
"register" => $this->translate("Register"),
"admin_notification" => $this->translate("Admin notification"),
"admin_responses" => $this->translate("Admin detailed response"),
),
'current' => $this->get('nextMessage_' . $code, 'Survey', $surveyId, null),
),
);
$aSettings[sprintf($this->translate("Next survey for %s (%s)"), $code, viewHelper::flatEllipsizeText($oAnswers->answer, 1, 60, "…"))] = $aNextSettings;
}
}
$aData['pluginClass'] = get_class($this);
$aData['surveyId'] = $surveyId;
$aData['title'] = $this->translate("Survey chaining settings");
$aData['aSettings'] = $aSettings;
$aData['assetUrl'] = Yii::app()->assetManager->publish(dirname(__FILE__) . '/assetslegacy3LTS/');
$aSettings = array();
$content = $this->renderPartial('settings', $aData, true);
return $content;
}
/**
* Action to do when survey is completed
*/
public function afterSurveyComplete()
{
if (!Yii::getPathOfAlias('getQuestionInformation')) {
$this->log("You must add an activate getQuestionInformation for this plugin.", \CLogger::LEVEL_ERROR);
return;
}
$nextSurvey = $oNextSurvey = null;
$surveyId = $this->getEvent()->get('surveyId');
$oCurrentSurvey = Survey::model()->findByPk($surveyId);
if (empty($oCurrentSurvey)) {
return;
}
$responseId = $this->getEvent()->get('responseId');
if (empty($responseId)) {
return;
}
$choiceQuestion = $this->get('choiceQuestion', 'Survey', $surveyId, null);
$nextEmailSetting = 'nextEmail';
$nextMessageSetting = 'nextMessage';
$existingLinkSetting = 'findExistingLink';
$oCurrentResponse = \Response::model($surveyId)->findByPk($responseId);
$aCurrentResponseBySGQ = $oCurrentResponse->getAttributes();
$currentCodeToColumn = \getQuestionInformation\helpers\surveyCodeHelper::getAllQuestions($surveyId);
$currentResponse = array();
if (!empty($aCurrentResponseBySGQ['seed'])) {
$currentResponse['seed'] = $aCurrentResponseBySGQ['seed'];
}
if (!empty($aCurrentResponseBySGQ['token'])) {
$currentResponse['token'] = $aCurrentResponseBySGQ['token'];
}
foreach ($aCurrentResponseBySGQ as $sgq => $value) {
if (!empty($currentCodeToColumn[$sgq])) {
$currentResponse[$currentCodeToColumn[$sgq]] = $value;
}
}
$currentChoice = null;
if ($choiceQuestion) {
// Find current value of choiceQuestion -if exist)
if (!empty($currentResponse[$choiceQuestion])) {
$currentChoice = strval($currentResponse[$choiceQuestion]);
$nextSurvey = $this->get('nextSurvey_' . $currentChoice, 'Survey', $surveyId, null);
if ($nextSurvey) {
$nextEmailSetting = 'nextEmail_' . $currentChoice;
$nextMessageSetting = 'nextMessage_' . $currentChoice;
$existingLinkSetting = 'findExistingLink_' . $currentChoice;
}
}
}
if (!$nextSurvey) {
$nextSurvey = $this->get('nextSurvey', 'Survey', $surveyId, null);
}
if (!$nextSurvey) {
return;
}
$this->log($this->translate("Survey selected for $surveyId : $nextSurvey"), \CLogger::LEVEL_INFO);
$oNextSurvey = Survey::model()->findByPk($nextSurvey);
if (!$oNextSurvey) {
$this->log($this->translate("Invalid survey selected for $surveyId (didn't exist)"), \CLogger::LEVEL_WARNING);
return;
}
if (!$this->_hasTokenTable($oNextSurvey->sid) && !$this->_reloadAnyResponseExist()) {
$this->log($this->translate("Invalid survey selected for $surveyId (No token table) and reloadAnyResponse plugin not installed."), \CLogger::LEVEL_WARNING);
return;
}
$sEmail = $this->_EMProcessString($this->get($nextEmailSetting, 'Survey', $surveyId, ""));
/* Ok we get here : do action */
$nextCodeToColumn = array_flip(\getQuestionInformation\helpers\surveyCodeHelper::getAllQuestions($nextSurvey));
$nextExistingCodeToColumn = array_intersect_key($nextCodeToColumn, $currentResponse);
if (empty($nextExistingCodeToColumn)) {
$this->log($this->translate("No question code corresponding for $surveyId"), \CLogger::LEVEL_WARNING);
return;
}
/* Find upload QuestionType */
$aUploadColumns = array();
$oUploadQuestionsType = \Question::model()->findAll(array(
'select' => 'title, sid,gid,qid',
'condition' => "sid = :sid",
'params' => array(":sid" => $nextSurvey),
));
if (!empty($oUploadQuestionsType)) {
foreach ($oUploadQuestionsType as $oQuestion) {
$sqga = $oQuestion->sid . "X" . $oQuestion->gid . "X" . $oQuestion->qid;
if (in_array($sqga, $nextExistingCodeToColumn)) {
$aUploadColumns[$oQuestion->title] = $sqga;
}
}
}
$nextsrid = null;
if ($this->get($existingLinkSetting, 'Survey', $surveyId, 1)) {
/* Find if previous response */
$chainingResponseLink = \surveyChaining\models\chainingResponseLink::model()->find(
"prevsid = :prevsid AND nextsid = :nextsid AND prevsrid = :prevsrid",
array(':prevsid' => $surveyId,':nextsid' => $nextSurvey,':prevsrid' => $responseId)
);
if (!empty($chainingResponseLink)) {
$nextsrid = $chainingResponseLink->nextsrid;
}
/* If don't have : get the inverse */
if (empty($chainingResponseLink)) {
$chainingResponseLinkInverse = \surveyChaining\models\chainingResponseLink::model()->find(
"prevsid = :prevsid AND nextsid = :nextsid AND nextsrid = :nextsrid",
array(':prevsid' => $nextSurvey,':nextsid' => $surveyId,':nextsrid' => $responseId)
);
if (!empty($chainingResponseLinkInverse)) {
$nextsrid = $chainingResponseLinkInverse->prevsrid;
}
}
}
$oResponse = null;
if ($nextsrid) {
$oResponse = Response::model($nextSurvey)->findByPk($nextsrid);
if ($oResponse && !$oNextSurvey->getIsAllowEditAfterCompletion()) {
$oResponse->submitdate = new CDbExpression('NULL');
$oResponse->save(true, array('submitdate'));
}
if (empty($oResponse)) {
$this->log($this->translate("A chaining between $surveyId and $nextSurvey but {$chainingResponseLink->nextsrid} not found. We delete all links."), \CLogger::LEVEL_WARNING);
\surveyChaining\models\chainingResponseLink::model()->deleteAll(
"prevsid = :prevsid AND nextsid = :nextsid AND prevsrid = :prevsrid",
array(':prevsid' => $nextSurvey,':nextsid' => $surveyId,':prevsrid' => $responseId)
);
\surveyChaining\models\chainingResponseLink::model()->deleteAll(
"prevsid = :prevsid AND nextsid = :nextsid AND nextsrid = :nextsrid",
array(':prevsid' => $nextSurvey,':nextsid' => $surveyId,':nextsrid' => $responseId)
);
$chainingResponseLink = null;
}
}
$oToken = null;
if ($this->_hasTokenTable($oNextSurvey->sid) && !$oNextSurvey->getIsAnonymized()) {
/* find token */
if ($oResponse) {
$oToken = Token::model($nextSurvey)->find("token = :token", array(':token' => $oResponse->token));
$oToken->email = $sEmail;
}
/* If token exist : update if needed */
if ($oToken && !$oNextSurvey->getIsAllowEditAfterCompletion()) {
$oToken->completed = "N";
$oToken->usesleft++;
if ($oToken->usesleft < 1) {
$oToken->usesleft = 1;
}
$oToken->save(true, array('completed', 'usesleft'));
}
/* Else create the token */
if (!$oToken) {
$aAttributes = array();
/* To set attributes by current token if exist */
if ($this->_hasTokenTable($oCurrentSurvey->sid) && !$oCurrentSurvey->getIsAnonymized()) {
$oCurrentToken = Token::model($surveyId)->find("token = :token", array(':token' => $currentResponse['token']));
if (!empty($oCurrentToken)) {
$aAttributes = $oCurrentToken->attributes;
unset($aAttributes['tid']);
unset($aAttributes['participant_id']);
unset($aAttributes['token']);
unset($aAttributes['email']);
unset($aAttributes['emailstatus']);
unset($aAttributes['blacklisted']);
unset($aAttributes['sent']);
unset($aAttributes['remindersent']);
unset($aAttributes['remindercount']);
unset($aAttributes['completed']);
unset($aAttributes['usesleft']);
unset($aAttributes['validfrom']);
unset($aAttributes['validuntil']);
}
}
$oToken = $this->_createToken($nextSurvey, $sEmail, $aAttributes);
}
}
/* Create response */
if (!$oResponse) {
$oResponse = Response::create($nextSurvey);
}
foreach ($nextExistingCodeToColumn as $code => $column) {
$oResponse->$column = $currentResponse[$code];
}
/* Default column */
if (!empty($currentResponse['seed'])) {
$oResponse->seed = $currentResponse['seed'];
}
$oResponse->startlanguage = App()->getLanguage();
if ($oToken && !$oNextSurvey->getIsAnonymized()) {
$oResponse->token = $oToken->token;
}
if ($oNextSurvey->datestamp == "Y") {
if (empty($oResponse->startdate)) {
$oResponse->startdate = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig('timeadjust'));
}
$oResponse->datestamp = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig('timeadjust'));
}
if (!$oResponse->save()) {
$this->log("Unable to save response for survey {$surveyId}, response {$responseId} for $nextSurvey", \CLogger::LEVEL_ERROR);
$this->log(CVarDumper::dumpAsString($oResponse->getErrors()), CLogger::LEVEL_ERROR);
return;
}
/* Copy uploaded files */
foreach ($aUploadColumns as $sUploadColumn) {
$uploaddir = Yii::app()->getConfig("uploaddir");
if (!empty($oResponse->$sUploadColumn)) {
$responseJson = $oResponse->$sUploadColumn;
$aUploadedFiles = @json_decode($responseJson, 1);
if (!empty($aUploadedFiles) && is_array($aUploadedFiles)) {
foreach ($aUploadedFiles as $aUploadedFile) {
if (!empty($aUploadedFile['filename'])) {
$file = "{$uploaddir}/surveys/{$surveyId}/files/{$aUploadedFile['filename']}";
if (is_file($file)) {
if (!is_dir("{$uploaddir}/surveys/{$nextSurvey}")) {
mkdir("{$uploaddir}/surveys/{$nextSurvey}");
}
if (!is_dir("{$uploaddir}/surveys/{$nextSurvey}/files")) {
mkdir("{$uploaddir}/surveys/{$nextSurvey}/files");
}
if (!copy($file, "{$uploaddir}/surveys/{$nextSurvey}/files/{$aUploadedFile['filename']}")) {
$this->log("Unable to copy {$aUploadedFile['filename']} from {$surveyId} to {$nextSurvey}", \CLogger::LEVEL_ERROR);
}
} else {
$this->log("Unable to find {$aUploadedFile['filename']} file in survey {$surveyId}", \CLogger::LEVEL_ERROR);
}
} else {
$this->log("Invalid updloaded files in survey {$surveyId}", \CLogger::LEVEL_ERROR);
$this->log(CVarDumper::dumpAsString($aUploadedFile), \CLogger::LEVEL_WARNING);
}
}
}
}
}
/* save links between responses */
if (empty($chainingResponseLink)) {
$chainingResponseLink = new \surveyChaining\models\chainingResponseLink();
$chainingResponseLink->prevsid = $surveyId;
$chainingResponseLink->prevsrid = $responseId;
$chainingResponseLink->nextsid = $nextSurvey;
}
$chainingResponseLink->nextsrid = $oResponse->id;
if (!$chainingResponseLink->save()) {
$this->log("Unable to save response link for {$oResponse->id} survey {$surveyId} linked with response {$responseId} for $nextSurvey", \CLogger::LEVEL_ERROR);
$this->log(CVarDumper::dumpAsString($chainingResponseLink->getErrors()), CLogger::LEVEL_ERROR);
}
/* Get email and send */
$nextMessage = $this->get($nextMessageSetting, 'Survey', $surveyId, "invite");
if ($currentChoice && $nextMessage === '') {
$nextMessage = $this->get('nextMessage', 'Survey', $surveyId, "invite");
}
if ($nextMessage === '') {
$nextMessage = 'invite';
}
if ($this->_hasTokenTable($oNextSurvey->sid) && !$oNextSurvey->getIsAnonymized() && $oToken) {
if ($this->sendSurveyChainingTokenEmail($nextSurvey, $oToken, $nextMessage, $oResponse->id)) {
// All done
}
return;
}
if ($this->_reloadAnyResponseExist()) {
$this->sendSurveyChainingReloadEmail($nextSurvey, $oResponse->id, $sEmail, $nextMessage, $oToken);
} else {
$this->log("reloadAnyResponse not activated for surveyChaining, can send next reponse link", 'error');
}
}
/**
* send email with SURVEYURL to new survey using reloadAnyResponse plugin
* @param integer $iSurvey
* @param integer $iResponse
* @param string $sEmail
* @param string $mailType
* @throws Exception
* @return boolean
*/
private function sendSurveyChainingReloadEmail($nextSurvey, $iResponse, $sEmail, $mailType = 'invite', $oToken = null)
{
if (intval(App()->getConfig('versionnumber')) < 4) {
return $this->_sendSurveyChainingReloadEmailLegacy3LTS($nextSurvey, $iResponse, $sEmail, $mailType, $oToken);
}
$oNextSurvey = Survey::model()->findByPk($nextSurvey);
if ($oNextSurvey->getHasTokensTable() && !empty($oToken)) {
/* Always create token */
$oToken = $this->_createToken($nextSurvey);
/* Set token to exiting response if needed (must not happen ?) */
if ($oToken && !$oNextSurvey->getIsAnonymized()) {
$oResponse = Response::model($nextSurvey)->findByPk($iResponse);
if ($oResponse && $oResponse->token) {
$oToken->token = $oResponse->token;
$oToken->save();
}
}
} else {
$oToken = null;
}
if (empty($sEmail)) {
$this->log("Empty email set for {$iResponse} in survey {$nextSurvey}", \CLogger::LEVEL_INFO);
return false;
}
$token = isset($oToken->token) ? $oToken->token : null;
$responseLink = \reloadAnyResponse\models\responseLink::setResponseLink($nextSurvey, $iResponse, $token);
if ($responseLink->hasErrors()) {
$this->log("Unable to save response reload link for {$iResponse} survey {$nextSurvey}", \CLogger::LEVEL_ERROR);
$this->log(CVarDumper::dumpAsString($responseLink->getErrors()), CLogger::LEVEL_ERROR);
return false;
}
$language = App()->getLanguage();
$mailer = new \LimeMailer();
$mailer->emailType = 'surveychainingreloademail';
$mailer->setSurvey($nextSurvey);
if ($token) {
$mailer->replaceTokenAttributes = true;
$mailer->setToken($oToken->token);
$language = $oToken->language;
}
$aSurveyInfo = getSurveyInfo($nextSurvey, $language);
/* Replace specific word for rwsubject and rawbody */
$specificReplace = array(
'{SURVEYURL}' => '{SURVEYCHAININGURL}',
'%%SURVEYURL%%' => '{RAWSURVEYCHAININGURL}',
'@@SURVEYURL@@' => '{RAWSURVEYCHAININGURL}',
'{SURVEYIDURL}' => '{SURVEYCHAININGURL}',
'%%SURVEYIDURL%%' => '{RAWSURVEYCHAININGURL}',
'@@SURVEYIDURL@@' => '{RAWSURVEYCHAININGURL}',
);
$mailer->addUrlsPlaceholders('SURVEYCHAININGURL'); // Didn't work in 5.6.40, issue in LimeMailer
$mailer->rawSubject = str_replace(
array_keys($specificReplace),
$specificReplace,
$aSurveyInfo['email_' . $mailType . '_subj']
);
$mailer->rawBody = str_replace(
array_keys($specificReplace),
$specificReplace,
$aSurveyInfo['email_' . $mailType]
);
$url = $responseLink->getStartUrl();
$mailer->aReplacements["SURVEYURL"] = $mailer->aReplacements["SURVEYCHAININGURL"] = $url;
$mailer->aReplacements["RAWSURVEYCHAININGURL"] = $url;
if ($mailer->getIsHtml()) {
$mailer->aReplacements["SURVEYCHAININGURL"] = CHtml::link($url, $url);
}
$mailer->setTo($sEmail);
$success = $mailer->sendMessage();
if ($success) {
if ($oToken) {
/* @todo did we need to test sent ? */
$oToken->sent = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", App()->getConfig("timeadjust"));
$oToken->save(true, ['sent']);
}
return true;
}
return false;
}
/**
* send email with SURVEYURL to new survey using reloadAnyResponse plugin
* @param integer $iSurvey
* @param integer $iResponse
* @param string $sEmail
* @param string $mailType
* @throws Exception
* @return boolean
*/
private function _sendSurveyChainingReloadEmailLegacy3LTS($nextSurvey, $iResponse, $sEmail, $mailType = 'invite', $oToken = null)
{
$oNextSurvey = Survey::model()->findByPk($nextSurvey);
if ($this->_hasTokenTable($oNextSurvey->sid) && !empty($oToken->token)) {
/* Always create token */
$oToken = $this->_createToken($nextSurvey);
/* Set token to exiting response if needed */
if ($oToken && !$oNextSurvey->getIsAnonymized()) {
$oResponse = Response::model($nextSurvey)->findByPk($iResponse);
if ($oResponse && $oResponse->token) {
$oToken->token = $oResponse->token;
$oToken->save();
}
}
} else {
$oToken = null;
}
$aReplacement = array();
/* Get survey link */
$token = isset($oToken->token) ? $oToken->token : null;
$responseLink = \reloadAnyResponse\models\responseLink::setResponseLink($nextSurvey, $iResponse, $token);
if ($responseLink->hasErrors()) {
$this->log("Unable to save response reload link for {$iResponse} survey {$nextSurvey}", \CLogger::LEVEL_ERROR);
$this->log(CVarDumper::dumpAsString($responseLink->getErrors()), CLogger::LEVEL_ERROR);
return false;
}
$aReplacements = array();
$aReplacements["SURVEYURL"] = $responseLink->getStartUrl();
$this->log("Try to send an email to $sEmail for $nextSurvey with responseLink", \CLogger::LEVEL_INFO);
if ($this->_sendSurveyChainingEmailLegacy3LTS($nextSurvey, $sEmail, Yii::app()->getLanguage(), $mailType, $aReplacements)) {
return true;
}
return false;
}
/**
* send email with SURVEYURL to new survey
* @param integer $iSurvey
* @param \Tokent $oToken \Token
* @param string $mailType
* @param integer $srid $response->id
* @return boolean
*/
private function sendSurveyChainingTokenEmail($nextSurvey, $oToken, $mailType = 'invite', $srid = null)
{
if (intval(App()->getConfig('versionnumber')) < 4) {
return $this->_sendSurveyChainingTokenEmailLegacy3LTS($nextSurvey, $oToken, $mailType, $srid);
}
if (empty($oToken->email)) {
$this->log("Empty email set for {$oToken->token} in survey {$nextSurvey}", \CLogger::LEVEL_INFO);
return false;