/
TokensController.php
272 lines (252 loc) · 11.1 KB
/
TokensController.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
<?php
namespace ls\controllers;
use ls\models\Token;
use Yii;
use ls\pluginmanager\PluginEvent;
class TokensController extends Controller
{
public function actions() {
return [
'captcha' => [
'class' => \CCaptchaAction::class,
'testLimit' => 1
]
];
}
public function actionResponses($id, $surveyId) {
$this->layout = 'bare';
$survey = \ls\models\Survey::model()->findByPk($surveyId);
$token = \ls\models\Token::model($survey->sid)->findByPk($id);
$criteria = new \CDbCriteria();
$criteria->order = 'submitdate DESC';
$criteria->addColumnCondition(['token' => $token->token]);
$dataProvider = new \CActiveDataProvider(\ls\models\Response::model($survey->sid), [
'criteria' => $criteria,
'pagination' => [
'pageSize' => 50
],
'sort' => false
]);
$this->menus['survey'] = $survey;
if ($dataProvider->totalItemCount > 0) {
$this->render('responses', [
'dataProvider' => $dataProvider,
'survey' => $survey,
// 'wrapper' => 'col-md-10 col-md-offset-2'
]);
} else {
echo "No responses for this token";
}
}
public function actionCreate($surveyId)
{
$survey = \ls\models\Survey::model()->findByPk($surveyId);
$this->menus['survey'] = $survey;
if (!$survey->bool_usetokens) {
throw new \CHttpException(412, "The survey you selected does not have tokens enabled");
}
$token = \ls\models\Token::create($survey->sid);
if (App()->request->isPostRequest) {
$token->setAttributes(App()->request->getPost(\CHtml::modelName($token)));
// Validate & safe.
if ($token->save()) {
// On success.
App()->user->setFlash('success', 'ls\models\Token created');
$this->redirect(['tokens/index', 'surveyId' => $survey->sid]);
}
}
$this->render('create', ['token' => $token, 'survey' => $survey]);
}
/**
* @param $surveyId
* @param $id
*/
public function actionView($surveyId, $id) {
$survey = \ls\models\Survey::model()->findByPk($surveyId);
$this->menus['survey'] = $survey;
$token = $this->loadModel($id, $surveyId);
return $this->renderText($this->widget(\WhDetailView::class, [
'data' => $token
], true));
}
/**
* @param $surveyId
* @param $id
* @throws \CHttpException
*/
public function actionUpdate($surveyId, $id)
{
/**
* @todo Add permission check.
*/
$survey = \ls\models\Survey::model()->findByPk($surveyId);
$this->menus['survey'] = $survey;
$token = $this->loadModel($id, $surveyId);
if (App()->request->isPutRequest) {
$token->setAttributes(App()->request->getPost(\CHtml::modelName($token)));
// Validate & safe.
if ($token->save()) {
// On success.
App()->user->setFlash('success', gT('Token updated'));
// $this->redirect(['tokens/index', 'surveyId' => $survey->sid]);
}
}
$this->render('update', ['token' => $token, 'survey' => $survey]);
}
public function actionIndex($surveyId)
{
/**
* @todo Add permission check.
*/
$survey = \ls\models\Survey::model()->findByPk($surveyId);
$this->menus['survey'] = $survey;
if (!$survey->bool_usetokens) {
throw new \CHttpException(412, "The survey you selected does not have tokens enabled.");
}
if (!\ls\models\Token::valid($survey->sid)) {
\ls\models\Token::createTable($survey->sid);
}
$dataProvider = new \CActiveDataProvider(\ls\models\Token::model($survey->sid), [
'pagination' => [
'pageSize' => 50
]
]);
return $this->render('index', ['dataProvider' => $dataProvider, 'survey' => $survey]);
}
public function actionRegister($surveyId)
{
$this->layout = 'minimal';
if (null === $survey = \ls\models\Survey::model()->findByPk($surveyId)) {
throw new \CHttpException(404, "The survey in which you are trying to participate does not seem to exist. It may have been deleted or the link you were given is outdated or incorrect.");
} elseif (!$survey->bool_allowregister) {
throw new \CHttpException(403, "The survey in which you are trying to register does not allow registration. It may have been updated or the link you were given is outdated or incorrect.");
}
$token = \ls\models\Token::create($survey->sid, 'register');
if (App()->request->isPostRequest) {
$token->setAttributes(App()->request->getPost(get_class($token)));
$token->generateToken();
if ($token->save()) {
$this->renderText($this->sendRegistrationEmail($token));
return;
}
}
$this->render('register', ['survey' => $survey, 'token' => $token]);
}
/**
* Send the register email with $_POST value
* @param $iSurveyId Survey Id to register
* @return boolean : if email is set to sent (before SMTP problem)
*/
protected function sendRegistrationEmail(\ls\models\Token $token){
$sLanguage=App()->language;
$iSurveyId = $token->surveyId;
$aSurveyInfo=getSurveyInfo($iSurveyId ,$sLanguage);
$aMail['subject']=$aSurveyInfo['email_register_subj'];
$aMail['message']=$aSurveyInfo['email_register'];
$aReplacementFields= [];
$aReplacementFields["{ADMINNAME}"]=$aSurveyInfo['adminname'];
$aReplacementFields["{ADMINEMAIL}"]=$aSurveyInfo['adminemail'];
$aReplacementFields["{SURVEYNAME}"]=$aSurveyInfo['name'];
$aReplacementFields["{SURVEYDESCRIPTION}"]=$aSurveyInfo['description'];
$aReplacementFields["{EXPIRY}"]=$aSurveyInfo["expiry"];
foreach($token->attributes as $attribute=>$value){
$aReplacementFields["{".strtoupper($attribute)."}"]=$value;
}
$useHtmlEmail = (getEmailFormat($iSurveyId) == 'html');
$aMail['subject']=preg_replace("/{TOKEN:([A-Z0-9_]+)}/","{"."$1"."}",$aMail['subject']);
$aMail['message']=preg_replace("/{TOKEN:([A-Z0-9_]+)}/","{"."$1"."}",$aMail['message']);
$aReplacementFields["{SURVEYURL}"] = App()->createAbsoluteUrl("/survey/index/sid/{$iSurveyId}",
['lang'=>$sLanguage,'token'=> $token->token]);
$aReplacementFields["{OPTOUTURL}"] = App()->createAbsoluteUrl("/optout/tokens/surveyid/{$iSurveyId}",
['langcode'=>$sLanguage,'token'=> $token->token]);
$aReplacementFields["{OPTINURL}"] = App()->createAbsoluteUrl("/optin/tokens/surveyid/{$iSurveyId}",
['langcode'=>$sLanguage,'token'=> $token->token]);
foreach(['OPTOUT', 'OPTIN', 'SURVEY'] as $key)
{
$url = $aReplacementFields["{{$key}URL}"];
if ($useHtmlEmail)
$aReplacementFields["{{$key}URL}"] = "<a href='{$url}'>" . htmlspecialchars($url) . '</a>';
$aMail['subject'] = str_replace("@@{$key}URL@@", $url, $aMail['subject']);
$aMail['message'] = str_replace("@@{$key}URL@@", $url, $aMail['message']);
}
// Replace the fields
$aMail['subject']=\ls\helpers\Replacements::ReplaceFields($aMail['subject'], $aReplacementFields);
$aMail['message']=\ls\helpers\Replacements::ReplaceFields($aMail['message'], $aReplacementFields);
$sFrom = "{$aSurveyInfo['adminname']} <{$aSurveyInfo['adminemail']}>";
$sBounce=getBounceEmail($iSurveyId);
$sTo=$token->email;
// Plugin event for email handling (Same than admin token but with register type)
$event = new PluginEvent('beforeTokenEmail');
$event->set('type', 'register');
$event->set('subject', $aMail['subject']);
$event->set('to', $sTo);
$event->set('body', $aMail['message']);
$event->set('from', $sFrom);
$event->set('bounce',$sBounce );
$event->set('token', $token->attributes);
$aMail['subject'] = $event->get('subject');
$aMail['message'] = $event->get('body');
$sTo = $event->get('to');
$sFrom = $event->get('from');
if ($event->get('send', true) == false)
{
$message = $event->get('message', '');
if($event->get('error')==null){// mimic token system, set send to today
$today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'));
$token->sent = $today;
$token->save();
}
}
elseif (SendEmailMessage($aMail['message'], $aMail['subject'], $sTo, $sFrom, App()->name,$useHtmlEmail,$sBounce))
{
// TLR change to put date into sent
$today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'));
$token->sent = $today;
$token->save();
$message = "<div id='wrapper' class='message tokenmessage'>"
. "<p>".gT("Thank you for registering to participate in this survey.")."</p>\n"
. "<p>{$this->sMailMessage}</p>\n"
. "<p>".sprintf(gT("Survey administrator %s (%s)"),$aSurveyInfo['adminname'],$aSurveyInfo['adminemail'])."</p>"
. "</div>\n";
}
else
{
$message = "<div id='wrapper' class='message tokenmessage'>"
. "<p>".gT("Thank you for registering to participate in this survey.")."</p>\n"
. "<p>".gT("You are registred but an error happen when trying to send the email, please contact the survey administrator.")."</p>\n"
. "<p>".sprintf(gT("Survey administrator %s (%s)"),$aSurveyInfo['adminname'],$aSurveyInfo['adminemail'])."</p>"
. "</div>\n";
}
return $message;
}
/**
* @param type $id
* @param null $surveyId
* @return \ls\models\Token
* @throws \CHttpException
*/
public function loadModel($id, $surveyId = null)
{
if (!isset($surveyId)) {
throw new \InvalidArgumentException("SurveyID is required when loading token.");
} elseif (!\ls\models\Token::valid($surveyId)) {
throw new \CHttpException(404, gT("Token table not found"));
} elseif (null === $result = \ls\models\Token::model($surveyId)->findByPk($id)) {
throw new \CHttpException(404, gT("Token not found"));
}
return $result;
}
/**
* @param int $id
* @param int $surveyId
* @todo Add permission check.
*/
public function actionDelete($id, $surveyId) {
if ($this->loadModel($id, $surveyId)->delete()) {
App()->user->setFlash('success', gT("Token deleted"));
} else {
App()->user->setFlash('success', gT("Could not delete token"));
}
$this->redirect(['tokens/index', 'surveyId' => $surveyId]);
}
}