reloadAnyResponse.php 63.7 KB
Newer Older
1 2 3 4 5
<?php
/**
 * Plugin helper for limesurvey : new class and function allowing to reload any survey
 *
 * @author Denis Chenu <denis@sondages.pro>
6
 * @copyright 2018-2021 Denis Chenu <http://www.sondages.pro>
7
 * @license AGPL v3
8
 * @version 4.1.2
9 10 11 12 13 14 15 16 17 18 19
 *
 * 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.
 */
Chenu Denis's avatar
Chenu Denis committed
20 21 22
class reloadAnyResponse extends PluginBase
{
    protected $storage = 'DbStorage';
23

Chenu Denis's avatar
Chenu Denis committed
24 25
    protected static $description = 'New class and function allowing to reload any survey.';
    protected static $name = 'reloadAnyResponse';
26

Chenu Denis's avatar
Chenu Denis committed
27
    protected static $dbVersion = 4;
28

Chenu Denis's avatar
Chenu Denis committed
29 30 31 32
    /* @var null|interger Keep reload srid during all events */
    private $reloadedSrid = null;
    /* @var null|string Keep reload token during all events */
    private $reloadedToken = null;
Chenu Denis's avatar
Chenu Denis committed
33

Chenu Denis's avatar
Chenu Denis committed
34 35
    /* @var null|interger Keep current surveyid */
    private $surveyId = null;
36

Chenu Denis's avatar
Chenu Denis committed
37 38 39 40
    /**
     * @var array[] the settings
     */
    protected $settings = array(
41 42 43 44 45 46 47
    '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(
48
            'value'=>1,
49 50 51 52 53
            'uncheckValue'=>0,
        ),
        'label'=>"Allow admin user to reload any survey with response id.",
        'default'=>1,
    ),
54 55 56 57 58 59 60 61 62 63
    '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,
    ),
64
    'allowTokenUser' => array(
Chenu Denis's avatar
Chenu Denis committed
65 66 67 68
        'type'=>'select',
        'options'=>array(
            1 => "Yes",
            0 => "No",
69 70
        ),
        'label'=>"Allow user with a valid token.",
Chenu Denis's avatar
Chenu Denis committed
71 72 73 74 75 76 77 78 79 80 81
        'default' => 1,
    ),
    'allowTokenGroupUser' => array(
        'type'=>'select',
        'options'=>array(
            1 => "Yes",
            0 => "No",
        ),
        'label'=>"Allow user with a token in same group.",
        'help' => "Group is related to User group management from responseListAndManage plugin",
        'default' => 1,
82
    ),
83 84 85 86 87 88
    'uniqueCodeCreate' => array(
        'type'=>'checkbox',
        'htmlOptions'=>array(
            'value'=>1,
            'uncheckValue'=>0,
        ),
Chenu Denis's avatar
Chenu Denis committed
89 90
        'label'=>"Create automatically unique code for all surveys.",
        'help'=>"If code exist, it can be always used.",
91 92
        'default'=>0,
    ),
Chenu Denis's avatar
Chenu Denis committed
93 94 95 96 97 98 99 100 101 102
    '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,
    ),
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
    '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,
    ),
133 134 135 136 137 138 139
    'disableMultiAccess' => array(
        'type'=>'info',
        'content'=>"<div class='alert alert-info'>You need renderMessage for disabling multiple access.</div>",
        'default'=>1,
    ),
    'multiAccessTime'=>array(
        'type'=>'int',
140
        'label' => 'Time for disable multiple access (in minutes) (config.php settings replace it of not exist)',
141 142 143
        '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,
144
            'placeholder'=>'Disable',
145
        ),
Chenu Denis's avatar
Chenu Denis committed
146
        'default' => '',
147
    ),
148 149 150 151 152 153 154 155 156 157
    '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,
    ),
Chenu Denis's avatar
Chenu Denis committed
158
    'replaceDefaultSave'=>array(
159 160 161 162 163
        'type'=>'select',
        'options'=>array(
            0 => "Never",
            1 => "When survey is reloaded by access code or token.",
            2 => "Always, each time survey is reloaded.",
Chenu Denis's avatar
Chenu Denis committed
164
        ),
165
        'label' => 'Replace the default LimeSurvey system if survey reloaded',
166
        'help' => 'When participant try to save a reloaded reponse : it was directly saved without showing the save form.',
Chenu Denis's avatar
Chenu Denis committed
167 168
        'default' => 1,
    ),
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
    'clearAllAction'=>array(
        'type'=>'select',
        'options'=>array(
            'reset' => "Reset session, don‘t delete current response",
            'partial' => "Reset session, delete current response if was not submitted.",
            'all' => "Reset session, delete current response in any condition.",
        ),
        'label' => "Action when using clearall action.",
        'help' => "Action to do when participant want to clear all. Default action by LimeSurvey was to delete not submitted response.",
        'default' => 'partial',
    ),
    'clearAllActionForced'=>array(
        'type'=>'checkbox',
        'htmlOptions'=>array(
            'value'=>1,
            'uncheckValue'=>0,
        ),
        'label' => "Replace clearall action even if response was not reloaded",
        'default' => 0,
    ),
    'reloadResetSubmitted'=>array(
        'type'=>'checkbox',
        'htmlOptions'=>array(
            'value'=>1,
            'uncheckValue'=>0,
        ),
        'label' => "When survey is save or move for the 1st time : reset it as not submitted.",
        'default' => 1,
    ),
Chenu Denis's avatar
Chenu Denis committed
198 199 200 201 202 203 204
    'keepMaxStep'=>array(
        'type'=>'checkbox',
        'htmlOptions'=>array(
            'value'=>1,
            'uncheckValue'=>0,
        ),
        'label' => "Keep max step during each load and save.",
205
        'help' => "Warning : when set this by default : it update all current survey table",
Chenu Denis's avatar
Chenu Denis committed
206 207
        'default' => 0,
    ),
208
    /* surveySession settings */
209 210 211 212 213 214 215 216 217 218 219
    '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).',
Chenu Denis's avatar
Chenu Denis committed
220
        'default' => '',
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
    ),
    '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).',
Chenu Denis's avatar
Chenu Denis committed
242
        'default' => '',
243
    ),
244 245
  );

Chenu Denis's avatar
Chenu Denis committed
246 247 248 249 250 251 252
    /** @inheritdoc **/
    public function init()
    {
        /* Set path of Alias at start */
        Yii::setPathOfAlias(get_class($this), dirname(__FILE__));
        /* Set the config */
        $this->subscribe('afterPluginLoad', 'setConfigInAfterPluginLoad');
Chenu Denis's avatar
Chenu Denis committed
253

Chenu Denis's avatar
Chenu Denis committed
254 255 256
        if (Yii::app() instanceof CConsoleApplication) {
            return;
        }
Chenu Denis's avatar
Chenu Denis committed
257

Chenu Denis's avatar
Chenu Denis committed
258 259 260 261 262 263 264
        /* 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');
265

Chenu Denis's avatar
Chenu Denis committed
266 267 268 269 270 271 272 273 274 275 276 277
        /* Get the survey by srid and code */
        /* Save current session */
        $this->subscribe('beforeSurveyPage');
        /* Some needed action when srid is set */
        $this->subscribe('getPluginTwigPath');
        /* Replace existing system if srid = new */
        $this->subscribe('beforeLoadResponse');
        /* Add a checker when multiple tab is open */
        $this->subscribe('beforeQuestionRender');
        /* Survey settings */
        $this->subscribe('beforeSurveySettings');
        $this->subscribe('newSurveySettings');
278

Chenu Denis's avatar
Chenu Denis committed
279 280 281 282 283 284 285
        /* delete current session*/
        $this->subscribe("afterSurveyComplete", 'afterSurveyDeleteSurveySession');
        $this->subscribe("afterSurveyQuota", 'afterSurveyDeleteSurveySession');
        /* delete current session when unload */
        $this->subscribe("newDirectRequest", 'newDirectRequest');
        /* redirect to editing survey */
        $this->subscribe("beforeControllerAction", 'beforeControllerAction');
286

Chenu Denis's avatar
Chenu Denis committed
287 288 289
        /* Logout remove all session, survey too, then must delete current related surveySessionId */
        $this->subscribe("beforeLogout", "deleteAllBySessionId");
    }
290

291 292 293 294 295 296 297 298 299 300
    /**
    * Delete all related current survey session from this user
    * @return @void
    */
    public function deleteAllBySessionId()
    {
        if (!$this->getEvent()) {
            throw new CHttpException(403);
        }
        \reloadAnyResponse\models\surveySession::deleteAllBySessionId();
301
    }
302

303 304 305
    /** @inheritdoc **/
    public function getPluginSettings($getValues=true)
    {
Chenu Denis's avatar
Chenu Denis committed
306
        if (!Permission::model()->hasGlobalPermission('settings', 'read')) {
307 308
            throw new CHttpException(403);
        }
309 310 311 312 313 314 315
        /* @todo translation of label and help */
        $pluginSetting = parent::getPluginSettings($getValues);
        return $pluginSetting;
    }
    /** @inheritdoc **/
    public function saveSettings($settings)
    {
Chenu Denis's avatar
Chenu Denis committed
316
        if (!Permission::model()->hasGlobalPermission('settings', 'update')) {
317 318
            throw new CHttpException(403);
        }
319 320
        parent::saveSettings($settings);
    }
321

Chenu Denis's avatar
Chenu Denis committed
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
    /** @inheritdoc **/
    public function beforeSurveySettings()
    {
        if (!$this->getEvent()) {
            throw new CHttpException(403);
        }
        $oEvent = $this->event;
        $oSurvey = Survey::model()->findByPk($oEvent->get('survey'));
        /* 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');
        $allowTokenGroupUserDefault = $this->get('allowTokenGroupUser', null, null, $this->settings['allowTokenGroupUser']['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');
        $replaceDefaultSaveDefault = $this->get('replaceDefaultSave', null, null, $this->settings['replaceDefaultSave']['default']);
        $clearAllActionDefault = $this->get('clearAllAction', null, null, $this->settings['clearAllAction']['default']);
        $reloadResetSubmittedDefault = $this->get('reloadResetSubmitted', null, null, $this->settings['reloadResetSubmitted']['default']) ? gT('Yes') : gT('No');
        $keepMaxStepDefault = $this->get('keepMaxStep', null, null, $this->settings['keepMaxStep']['default']) ? gT('Yes') : gT('No');
341

Chenu Denis's avatar
Chenu Denis committed
342
        switch ($clearAllActionDefault) {
343 344 345 346 347 348 349 350 351 352 353 354
            case 'reset':
                $clearAllActionDefault = $this->_translate("Do not delete");
                break;
            case 'all':
                $clearAllActionDefault = $this->_translate("Always delete");
                break;
            case 'partial':
                $clearAllActionDefault = $this->_translate("Delete not submitted");
                break;
            default:
                /* Must not come here, show the current value */
        }
355
  
Chenu Denis's avatar
Chenu Denis committed
356
        switch ($replaceDefaultSaveDefault) {
357 358 359 360 361 362 363 364 365 366 367
            case 0:
                $replaceDefaultSaveDefault = $this->_translate("never");
                break;
            case 1:
            default:
                $replaceDefaultSaveDefault = $this->_translate("with access code or token");
                break;
            case 2:
                $replaceDefaultSaveDefault = $this->_translate("always");
                break;
        }
368

Chenu Denis's avatar
Chenu Denis committed
369 370
        $clearAllActionForcedDefault =  $this->get('clearAllActionForced', null, null, $this->settings['clearAllActionForced']['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');
371

Chenu Denis's avatar
Chenu Denis committed
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
        /* Helper */
        $allowTokenUserHelp = "<ul>";
        if ($oSurvey->getIsAnonymized()) {
            $allowTokenUserHelp .= "<li class='text-danger'>".$this->_translate("Token user can not edit response because survey is anonymous.")."</li>";
        } else {
            $allowTokenUserHelp .= "<li class='text-success'>".$this->_translate("Token user can edit response.")."</li>";
        }
        //~ /* Check what happen */
        if ($oSurvey->getIsAllowEditAfterCompletion() || !$oSurvey->getIsShowWelcome()) {
            $allowTokenUserHelp .= "<li class='text-success'>".$this->_translate("User with a submitted token can edit response in any conditions.")."</li>";
        } else {
            $allowTokenUserHelp .= "<li class='text-danger'>".$this->_translate("User with a submitted token can not edit response because allow edit after completion is not active and show welcome text is active.")."</li>";
        }
        if ($oSurvey->getIsTokenAnswersPersistence() && $oSurvey->getIsShowWelcome()) {
            $allowTokenUserHelp .= "<li class='text-danger'>".$this->_translate("User can not create a new response until all are submitted because allow edit after completion is not active and show welcome text is active.")."</li>";
        } else {
            $allowTokenUserHelp .= "<li class='text-success'>".$this->_translate("User can create a new response in any conditions.")."</li>";
        }
        $allowTokenUserHelp .= "</ul>";
        $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 reload or create responses."),
                    'help' =>  $allowTokenUserHelp,
                    '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'), "")
                ),
                'allowTokenGroupUser'=>array(
                    'type' => 'select',
                    'label' => $this->_translate("Allow participant with token in same group to reload responses."),
                    'help' => $this->_translate("Related to responseListAndManage user. This need allowing token user to reload reponse."),
                    'options'=>array(
                        1 => gT("Yes"),
                        0 => gT("No"),
                        ),
                    'htmlOptions'=>array(
                        'empty' => CHtml::encode(sprintf($this->_translate("Use default (%s)"), $allowTokenGroupUserDefault)),
                    ),
                    'current'=>$this->get('allowTokenGroupUser', '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)),
                    ),
454 455 456 457 458 459 460
                    'current' => $this->get('uniqueCodeAccess', 'Survey', $oEvent->get('survey'), ""),
                ),
                /* Specific disable */
                'extraFilters' => array(
                    'type' => 'text',
                    'label' => $this->_translate("Extra condition for allowing edition."),
                    'default' => '',
461
                    'current' => $this->get('extraFilters', 'Survey', $oEvent->get('survey'), ""),
462 463
                    'help' => $this->_translate('One field by line, field must be a valid question code (single question only). Field and value are separated by colon (<code>:</code>).')
                        . "<br>" . $this->_translate('If user try to edit an unavailable response, a 404 error is shown.'),
Chenu Denis's avatar
Chenu Denis committed
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
                ),
                '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'), "")
                ),
                /* Replacing save */
                'replaceDefaultSave' => array(
                    'type'=>'select',
                    'options'=>array(
                        0 =>gT("Never"),
                        1 =>gT("If reloaded with access code or token"),
                        2 =>gT("Always (if reloaded)"),
                    ),
                    'htmlOptions'=>array(
                        'empty' => CHtml::encode(sprintf($this->_translate("Use default (%s)"), $replaceDefaultSaveDefault)),
                    ),
                    'label' => $this->_translate("Save reloaded response transparently."),
                    'help' => $this->_translate("Replace the LimeSurvey save form : directly save the current reponse when user click on save all."),
                    'current'=>$this->get('replaceDefaultSave', 'Survey', $oEvent->get('survey'), "")
                ),
                /* Clear all action */
                'clearAllAction' => array(
                    'type'=>'select',
                    'options'=>array(
                        'reset' =>gT("Reset session, don‘t delete current response"),
                        'partial' =>gT("Reset session, delete current response if was not submitted."),
                        'all' =>gT("Reset session, delete current response in any condition."),
                    ),
                    'htmlOptions'=>array(
                        'empty' => CHtml::encode(sprintf($this->_translate("Use default (%s)"), $clearAllActionDefault)),
                    ),
                    'label' => $this->_translate("Action when using clearall action."),
                    'help' => $this->_translate("Action to do when participant want to clear all. Default action by LimeSurvey was to delete not submitted answer."),
                    'current'=>$this->get('clearAllAction', 'Survey', $oEvent->get('survey'), "")
                ),
                'clearAllActionForced' => array(
                    'type'=>'select',
                    'options'=>array(
                        1 =>gT("Yes"),
                        0 =>gT("No"),
                    ),
                    'htmlOptions'=>array(
                        'empty' => CHtml::encode(sprintf($this->_translate("Use default (%s)"), $clearAllActionForcedDefault)),
                    ),
                    'label' => $this->_translate("Replace clearall action even if response is not reloaded."),
                    'current'=>$this->get('clearAllActionForced', 'Survey', $oEvent->get('survey'), "")
                ),
                /* Reset to not submitted when open */
                'reloadResetSubmitted' => array(
                    'type'=>'select',
                    'options'=>array(
                        1 =>gT("Yes"),
                        0 =>gT("No"),
                    ),
                    'label' => $this->_translate("Reset submitdate on the first action done."),
                    'help' => $this->_translate("When a submitted survey is open without action : nothing was updated, if user do an action : you can choose to reset the respnse to not submitted."),
                    'htmlOptions'=>array(
                        'empty' => CHtml::encode(sprintf($this->_translate("Use default (%s)"), $reloadResetSubmittedDefault)),
                    ),
                    'current'=>$this->get('reloadResetSubmitted', 'Survey', $oEvent->get('survey'), "")
                ),
                /* Save (abnd load) max step */
                'keepMaxStep' => array(
                'type'=>'select',
                'options'=>array(
                    1 =>gT("Yes"),
                    0 =>gT("No"),
                ),
                'label' => $this->_translate("Keep max page seen when load and save."),
                'help' => $this->_translate("Add a column in database to keep max page seen. Reload it when load response."),
                'htmlOptions'=>array(
                    'empty' => CHtml::encode(sprintf($this->_translate("Use default (%s)"), $keepMaxStepDefault)),
                ),
                'current'=>$this->get('reloadResetSubmitted', 'Survey', $oEvent->get('survey'), "")
                ),
            ),
        ));
560
    }
561

562
    /**
Chenu Denis's avatar
Chenu Denis committed
563
     * When need to do something
564 565 566
     */
    public function beforeControllerAction()
    {
567 568 569
        if (!$this->getEvent()) {
            throw new CHttpException(403);
        }
Chenu Denis's avatar
Chenu Denis committed
570
        if ($this->getEvent()->get("controller") == "survey" && $this->getEvent()->get("action") == "index") {
571
            $this->checkSurveyAttributes();
572
            return;
573
        }
Chenu Denis's avatar
Chenu Denis committed
574
        if (!$this->get('replaceEditResponse') || !$this->get('allowAdminUser')) {
575 576
            return;
        }
Chenu Denis's avatar
Chenu Denis committed
577
        if ($this->getEvent()->get("controller") != "admin") {
578 579
            return;
        }
Chenu Denis's avatar
Chenu Denis committed
580
        if ($this->getEvent()->get("action") != "dataentry") {
581 582
            return;
        }
Chenu Denis's avatar
Chenu Denis committed
583
        if ($this->getEvent()->get("subaction") != "editdata") {
584 585 586 587
            return;
        }
        $surveyid = App()->getRequest()->getParam('surveyid');
        $srid = App()->getRequest()->getParam('id');
Chenu Denis's avatar
Chenu Denis committed
588
        if (!Permission::model()->hasSurveyPermission($surveyid, 'response', 'update')) {
589 590
            return;
        }
591 592
        $criteria = \reloadAnyResponse\Utilities::getResponseCriteria($surveyid, $srid);
        $oResponse = Response::model($surveyid)->find($criteria);
Chenu Denis's avatar
Chenu Denis committed
593
        if (empty($oResponse)) {
594 595 596 597
            return;
        }
        $surveyLink = Yii::app()->createUrl("survey/index", array('sid' => $surveyid,'srid'=>$srid,'newtest'=>'Y'));

Chenu Denis's avatar
Chenu Denis committed
598
        $this->getEvent()->set('run', false);
599
        App()->getController()->redirect($surveyLink);
600
    }
601

602 603 604 605
    /**
     * Check if survey seetings need to be updated with current params
     * @return void
     */
606
    private function checkSurveyAttributes()
607 608 609
    {
        $sid = App()->getRequest()->getParam('sid');
        $srid = App()->getRequest()->getParam('srid');
Chenu Denis's avatar
Chenu Denis committed
610
        if (empty($srid)) {
611 612
            $srid = \reloadAnyResponse\Utilities::getCurrentSrid($sid);
        }
Chenu Denis's avatar
Chenu Denis committed
613
        if (empty($srid)) {
614 615 616
            return;
        }
        $token = App()->getRequest()->getParam('token');
Chenu Denis's avatar
Chenu Denis committed
617
        if (empty($token)) {
618 619
            $token = \reloadAnyResponse\Utilities::getCurrentReloadedToken($sid);
        }
Chenu Denis's avatar
Chenu Denis committed
620 621
        $startUrl = new \reloadAnyResponse\StartUrl($sid, $token);
        if (!$startUrl->isAvailable()) {
622 623 624 625
            return;
        }
        $this->subscribe('afterFindSurvey', 'setSurveyEditable');
    }
626

627 628 629 630 631 632
    /**
     * Set a surey as editable
     * @see afterFindSurvey event
     */
    public function setSurveyEditable()
    {
633 634 635
        if (!$this->getEvent()) {
            throw new CHttpException(403);
        }
Chenu Denis's avatar
Chenu Denis committed
636
        $this->getEvent()->set('alloweditaftercompletion', 'Y');
637
    }
638 639 640 641

    /** @inheritdoc **/
    public function newSurveySettings()
    {
642 643 644
        if (!$this->getEvent()) {
            throw new CHttpException(403);
        }
645 646 647 648 649
        $event = $this->event;
        foreach ($event->get('settings') as $name => $value) {
            $this->set($name, $value, 'Survey', $event->get('survey'));
        }
    }
650

Chenu Denis's avatar
Chenu Denis committed
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
    /** @inheritdoc
     * Delete all response link when survey is set to active != Y
     **/
    public function afterSurveySave()
    {
        if (!$this->getEvent()) {
            throw new CHttpException(403);
        }
        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);
                }
            }
        }
668
    }
669

Chenu Denis's avatar
Chenu Denis committed
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
    /** @inheritdoc
     * Delete all response link when survey is deleted
     **/
    public function afterSurveyDelete()
    {
        if (!$this->getEvent()) {
            throw new CHttpException(403);
        }
        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);
                }
            }
        }
687
    }
688

Chenu Denis's avatar
Chenu Denis committed
689 690 691 692 693 694 695 696 697 698 699 700
    /** @inheritdoc
     * Delete all response link when surveys is deleted
     * @todo
     **/
    public function beforeSurveyDeleteMany()
    {
        if (!$this->getEvent()) {
            throw new CHttpException(403);
        }
        if ($this->_getCurrentSetting('deleteLinkWhenSurveyDeleted')) {
            $criteria = $this->getEvent()->get('filterCriteria');
        }
701
    }
702

Chenu Denis's avatar
Chenu Denis committed
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
    /** @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()
    {
        if (!$this->getEvent()) {
            throw new CHttpException(403);
        }
        $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);
                    }
                }
            }
        }
738 739
    }

Chenu Denis's avatar
Chenu Denis committed
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
    /**
     * @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->getEvent()) {
            throw new CHttpException(403);
        }
        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));
                }
            }
        }
762 763
    }

Chenu Denis's avatar
Chenu Denis committed
764 765 766 767 768 769 770 771 772 773 774 775
    /** @See event */
    public function beforeLoadResponse()
    {
        if (!$this->getEvent()) {
            throw new CHttpException(403);
        }
        $srid = App()->getRequest()->getQuery('srid');
        $surveyId = $this->getEvent()->get('surveyId');
        $oSurvey = Survey::model()->findByPk($surveyId);
        $oResponses = $this->getEvent()->get('responses');
        $oResponse = $this->getEvent()->get('response');/* Get the current response set */
        $token = App()->getRequest()->getParam('token');
776

Chenu Denis's avatar
Chenu Denis committed
777 778
        /* control multi access to token with token and allow edit reponse */
        $oSurvey = Survey::model()->findByPk($surveyId);
779 780 781 782
        if ($srid == 'new' && $token && $this->_getIsActivated('allowTokenUser', $surveyId)) {
            \reloadAnyResponse\Utilities::setCurrentReloadedWay($surveyId, 'token');
        }

Chenu Denis's avatar
Chenu Denis committed
783 784 785
        if (empty($oSurvey) || $oSurvey->tokenanswerspersistence != "Y") {
            return;
        }
786

Chenu Denis's avatar
Chenu Denis committed
787 788 789 790 791 792 793 794 795 796
        if ($srid == 'new' && $token && $this->_getIsActivated('allowTokenUser', $surveyId)) {
            if ($oSurvey->tokenanswerspersistence != "Y" || $oSurvey->showwelcome != 'Y' || $oSurvey->format == 'A') {
                /* Check if create or not … */
                $this->getEvent()->set('response', false);
                return;
            }
        }
        /* if srid is set : all is already done */
        /* need to check maxstep */
        if (!$this->_getCurrentSetting('multiAccessTime', $surveyId)) {
797 798
            return;
        }
799

Chenu Denis's avatar
Chenu Denis committed
800 801 802 803 804 805 806 807 808 809 810 811 812
        if (is_null($oResponse)) {
            if (empty($oResponses[0]->submitdate) || $oSurvey->alloweditaftercompletion == 'Y') {
                $oResponse = $oResponses[0];
            }
        }
        if (empty($oResponse)) {
            return;
        }
        if ($since = \reloadAnyResponse\models\surveySession::getIsUsed($surveyId, $oResponse->id, !$this->noactionByUserAgent())) {
            $this->_endWithEditionMessage($since);
        }
        if (!$this->noactionByUserAgent()) {
            \reloadAnyResponse\models\surveySession::saveSessionTime($surveyId, $oResponse->id);
813
        }
814
    }
815 816 817 818

    /** @inheritdoc **/
    public function beforeSurveyPage()
    {
819 820 821
        if (!$this->getEvent()) {
            throw new CHttpException(403);
        }
822 823
        /* Save current session Id to allow same user to reload survey in same browser */
        /* resetAllSessionVariables regenerate session id */
824
        /* Keep previous session id, if user reload start url it reset the sessionId, need to leav access */
825
        $surveyid = $this->getEvent()->get('surveyId');
Chenu Denis's avatar
Chenu Denis committed
826
        /* Multiple access to same survey checking */
Chenu Denis's avatar
Chenu Denis committed
827 828 829
        $multiAccessTime = $this->_getCurrentSetting('multiAccessTime', $surveyid);
        if ($multiAccessTime !== '') {
            Yii::app()->setConfig('surveysessiontime_limit', $multiAccessTime);
830
        }
831
        $disableMultiAccess = true;
Chenu Denis's avatar
Chenu Denis committed
832
        if ($multiAccessTime === '0' /* disable by survey */|| $multiAccessTime === ''/* disable globally */) {
833 834
            $disableMultiAccess = false;
        }
Chenu Denis's avatar
Chenu Denis committed
835
        if ($disableMultiAccess) {
836 837
            $this->checkAccessByUserAgent();
        }
Chenu Denis's avatar
Chenu Denis committed
838

839 840
        /* For token : @todo in beforeReloadReponse */
        /* @todo : delete surveySession is save or clearall action */
Chenu Denis's avatar
Chenu Denis committed
841
        if ($disableMultiAccess && ($since = \reloadAnyResponse\models\surveySession::getIsUsed($surveyid, null, !$this->noactionByUserAgent()))) {
842 843
            /* This one is done with current session : maybe allow to keep srid in session and reload it ? */
            killSurveySession($surveyid);
844
            $this->_endWithEditionMessage($since);
845
        }
846 847 848 849 850 851 852
        /* Clear all action */
        $isClearAll = (App()->request->getPost('clearall') == 'clearall' || App()->request->getPost('move') == 'clearall') && App()->request->getPost('confirm-clearall') == 'confirm';
        if ($isClearAll) {
            $this->actionOnClearAll($surveyid);
            /* If we are there : LS must do it's own action */
            return;
        }
Chenu Denis's avatar
Chenu Denis committed
853
        /* Check POST and current session : throw error if needed */
Chenu Denis's avatar
Chenu Denis committed
854
        if (App()->getRequest()->getPost('reloadAnyResponseSrid')) {
855 856
            $currentReloadedSrid = \reloadAnyResponse\Utilities::getCurrentReloadedSrid($surveyid);
            $currentSrid = \reloadAnyResponse\Utilities::getCurrentSrid($surveyid);
857
            \reloadAnyResponse\Utilities::setSaveAutomatic($surveyid);
858
            if ($currentSrid != App()->getRequest()->getPost('reloadAnyResponseSrid') || $currentReloadedSrid != $currentSrid) {
Chenu Denis's avatar
Chenu Denis committed
859 860 861
                throw new CHttpException(400, $this->_translate("Your current session seems invalid with current data."));
            }
            $token = \reloadAnyResponse\Utilities::getCurrentReloadedToken($surveyid);
Chenu Denis's avatar
Chenu Denis committed
862
            \reloadAnyResponse\Utilities::resetLoadedReponse($surveyid, $currentSrid, $token, $this->_getCurrentSetting('reloadResetSubmitted', $surveyid));
863
            $this->surveyId = $surveyid;
Chenu Denis's avatar
Chenu Denis committed
864 865 866 867
            $this->reloadedSrid = $currentSrid;
            return;
        }
        /* Check srid */
868
        $srid = App()->getRequest()->getQuery('srid');
Chenu Denis's avatar
Chenu Denis committed
869
        if (!$srid) {
Chenu Denis's avatar
Chenu Denis committed
870
            $this->reloadedSrid = \reloadAnyResponse\Utilities::getCurrentReloadedSrid($surveyid);
Chenu Denis's avatar
Chenu Denis committed
871
            if ($disableMultiAccess  && !$this->noactionByUserAgent()) {
Chenu Denis's avatar
Chenu Denis committed
872 873
                /* Always save current srid if needed , only reload can disable this */
                \reloadAnyResponse\models\surveySession::saveSessionTime($surveyid);
874
            }
875
            $this->surveyId = $surveyid;
876 877 878 879
            return;
        }
        $oSurvey = Survey::model()->findByPk($surveyid);
        $token = App()->getRequest()->getParam('token');
Chenu Denis's avatar
Chenu Denis committed
880 881 882
        if ($srid == "new" || \reloadAnyResponse\Utilities::getCurrentReloadedSrid($surveyid) == "new") {
            $oStarurl = new \reloadAnyResponse\StartUrl($surveyid, $token);
            if ($oStarurl->isAvailable()) {
883 884 885
                $this->reloadedSrid = "new";
                $this->surveyId = $surveyid;
            }
Chenu Denis's avatar
Chenu Denis committed
886
            return;
887
        }
Chenu Denis's avatar
Chenu Denis committed
888
        if ($this->loadReponse($surveyid, $srid, App()->getRequest()->getParam('token'), App()->getRequest()->getParam('code'))) {
889
            $this->surveyId = $surveyid;
Chenu Denis's avatar
Chenu Denis committed
890
            $this->reloadedSrid = $srid;
891
            $this->reloadedToken = App()->getRequest()->getParam('token');
892
        }
Chenu Denis's avatar
Chenu Denis committed
893
    }
894

895 896 897 898 899 900
    /**
     * @see getPluginTwigPath event
     * Do some action when srid is potentially set
     */
    public function getPluginTwigPath()
    {
901 902 903
        if (!$this->getEvent()) {
            throw new CHttpException(403);
        }
904
        $this->unsubscribe('getPluginTwigPath');
Chenu Denis's avatar
Chenu Denis committed
905
        if (!$this->surveyId) {
906 907
            return;
        }
Chenu Denis's avatar
Chenu Denis committed
908
        \reloadAnyResponse\Utilities::fixToken($this->surveyId);
909
        $srid = \reloadAnyResponse\Utilities::getCurrentSrid($this->surveyId);
Chenu Denis's avatar
Chenu Denis committed
910 911
        if ($this->reloadedSrid == "new") {
            if ($srid) {
912 913
                \reloadAnyResponse\Utilities::setSaveAutomatic($this->surveyId);
                $this->reloadedSrid = \reloadAnyResponse\Utilities::getCurrentSrid($this->surveyId);
Chenu Denis's avatar
Chenu Denis committed
914
                \reloadAnyResponse\Utilities::setCurrentReloadedSrid($this->surveyId, $srid);
915
            } else {
916 917
                /* What happen ? Unsure on what to do . */
                \reloadAnyResponse\Utilities::setCurrentReloadedSrid($this->surveyId, null);
918
            }
919
        }
Chenu Denis's avatar
Chenu Denis committed
920 921
        if ($srid) {
            if (\reloadAnyResponse\Utilities::getSetting($this->surveyId, 'keepMaxStep')) {
Chenu Denis's avatar
Chenu Denis committed
922 923
                \reloadAnyResponse\Utilities::setMaxStep($this->surveyId, $srid);
            }
924 925 926 927 928
            $ajaxUrl = Yii::app()->getController()->createUrl(
                'plugins/direct',
                array('plugin' => get_class($this), 'function' => 'close','sid'=>$this->surveyId,'srid'=>$srid)
            );
            $onBeforeUnload = "window.onbeforeunload = function(e) {\n";
Chenu Denis's avatar
Chenu Denis committed
929
            $onBeforeUnload .= "    jQuery.ajax({ async: false, url:'{$ajaxUrl}' });\n";
930
            $onBeforeUnload .= "}\n";
Chenu Denis's avatar
Chenu Denis committed
931
            Yii::app()->getClientScript()->registerScript("reloadAnyResponseBeforeUnload", $onBeforeUnload, CClientScript::POS_HEAD);
932 933
        }
    }
934

Chenu Denis's avatar
Chenu Denis committed
935 936 937 938 939 940
    /**
     * @see getPluginTwigPath event
     * Here : adding path to twig (when needed only)
     */
    public function addPluginTwigPath()
    {
941 942 943
        if (!$this->getEvent()) {
            throw new CHttpException(403);
        }
Chenu Denis's avatar
Chenu Denis committed
944
        $viewPath = dirname(__FILE__)."/twig";
Chenu Denis's avatar
Chenu Denis committed
945
        $this->getEvent()->append('add', array($viewPath));
Chenu Denis's avatar
Chenu Denis committed
946 947
    }

Chenu Denis's avatar
Chenu Denis committed
948 949 950 951 952 953 954
    /**
     * @see beforeQuestionRender event
     * Adding a POST value with current reloaded Srid
     * @return void
     */
    public function beforeQuestionRender()
    {
955 956 957
        if (!$this->getEvent()) {
            throw new CHttpException(403);
        }
Chenu Denis's avatar
Chenu Denis committed
958 959 960
        if ($this->reloadedSrid) {
            $hiddenInput = CHtml::hiddenField('reloadAnyResponseSrid', $this->reloadedSrid);
            $this->getEvent()->set("answers", $this->getEvent()->get("answers").$hiddenInput);
Chenu Denis's avatar
Chenu Denis committed
961 962 963
        }
        $this->reloadedSrid = null;
    }
964 965 966
    /**
     * Delete SurveySession for this event srid
     */
Chenu Denis's avatar
Chenu Denis committed
967
    public function afterSurveyDeleteSurveySession()
968
    {
969 970 971
        if (!$this->getEvent()) {
            throw new CHttpException(403);
        }
972 973
        $surveyId = $this->getEvent()->get('surveyId');
        $responseId = $this->getEvent()->get('responseId');
Chenu Denis's avatar
Chenu Denis committed
974
        if (!empty($surveyId) && !empty($responseId)) {
Chenu Denis's avatar
Chenu Denis committed
975 976
            \reloadAnyResponse\models\surveySession::model()->deleteByPk(array('sid'=>$surveyId,'srid'=>$responseId));
        }
977
    }
978 979 980 981

    /** @inheritdoc **/
    public function newDirectRequest()
    {
982 983 984
        if (!$this->getEvent()) {
            throw new CHttpException(403);
        }
Chenu Denis's avatar
Chenu Denis committed
985
        if ($this->getEvent()->get('target') != get_class($this)) {
986 987 988 989
            return;
        }
        $surveyId = Yii::app()->getRequest()->getParam('sid');
        $responseId = Yii::app()->getRequest()->getParam('srid');
990 991 992 993
        if(\reloadAnyResponse\Utilities::getCurrentReloadedSrid($surveyId) != $responseId && \reloadAnyResponse\Utilities::getCurrentSrid($surveyId) != $responseId) {
            \Yii::log(sprintf("Try to reset session for %s in %s", $responseId, $surveyId), \CLogger::LEVEL_INFO, 'plugin.reloadAnyResponse.newDirectRequest');
            return;
        }
Chenu Denis's avatar
Chenu Denis committed
994
        if ($surveyId && $responseId) {
995 996 997 998
            \reloadAnyResponse\models\surveySession::model()->deleteByPk(array('sid'=>$surveyId,'srid'=>$responseId));
        }
    }

999 1000 1001 1002 1003
    /**
     * action on clear all, result are end or return.
     * @param integer $surveyId
     * @return void
     */
1004
    private function actionOnClearAll($surveyId)
1005
    {
1006
        $srid = \reloadAnyResponse\Utilities::getCurrentSrid($surveyId);
Chenu Denis's avatar
Chenu Denis committed
1007 1008 1009
        if(empty($srid)) {
            return;
        }
Chenu Denis's avatar
Chenu Denis committed
1010
        \reloadAnyResponse\models\surveySession::model()->deleteByPk(array('sid'=>$surveyId,'srid'=>$srid));
1011

Chenu Denis's avatar
Chenu Denis committed
1012
        $reloadedSrid = App()->getRequest()->getPost('reloadAnyResponseSrid');
Chenu Denis's avatar
Chenu Denis committed
1013
        if ($srid && $reloadedSrid  && $reloadedSrid != $srid) {
1014
            /* Must throw error : else potential deletion of bad survey */
1015 1016 1017
            /* Lets do the default action */
            return;
        }
Chenu Denis's avatar
Chenu Denis committed
1018
        if (empty($reloadedSrid)) {
1019 1020
            $reloadedSrid = \reloadAnyResponse\Utilities::getCurrentReloadedSrid($surveyId);
        }
Chenu Denis's avatar
Chenu Denis committed
1021
        if (!$reloadedSrid && $this->_getCurrentSetting('clearAllActionForced', $surveyId)) {
1022 1023 1024
            /* seems not reloaded : quit */
            return;
        }
1025
        $this->reloadedSrid = $reloadedSrid;
Chenu Denis's avatar
Chenu Denis committed
1026 1027
        $this->reloadedToken = \reloadAnyResponse\Utilities::getCurrentReloadedToken($surveyId<