reloadAnyResponse.php 15 KB
Newer Older
1 2 3 4 5 6 7
<?php
/**
 * Plugin helper for limesurvey : new class and function allowing to reload any survey
 *
 * @author Denis Chenu <denis@sondages.pro>
 * @copyright 2018 Denis Chenu <http://www.sondages.pro>
 * @license AGPL v3
8
 * @version 0.4.0
9 10 11 12 13 14 15 16 17 18 19 20 21
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */
class reloadAnyResponse extends PluginBase {

22 23
  protected $storage = 'DbStorage';

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

27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
  /**
   * @var array[] the settings
   */
  protected $settings = array(
    'information' => array(
        'type' => 'info',
        'content' => 'The default settings for all surveys. Remind no system is set in this plugin to show or send link to user.',
    ),
    'allowAdminUser' => array(
        'type'=>'checkbox',
        'htmlOptions'=>array(
            'value'=>1,
            'uncheckValue'=>0,
        ),
        'label'=>"Allow admin user to reload any survey with response id.",
        'default'=>1,
    ),
44 45 46 47 48 49 50 51 52
    'allowToken' => array(
        'type'=>'checkbox',
        'htmlOptions'=>array(
            'value'=>1,
            'uncheckValue'=>0,
        ),
        'label'=>"Allow user with a valid token.",
        'default'=>1,
    ),
53 54 55 56 57 58
    'uniqueCodeCreate' => array(
        'type'=>'checkbox',
        'htmlOptions'=>array(
            'value'=>1,
            'uncheckValue'=>0,
        ),
Chenu Denis's avatar
Chenu Denis committed
59 60
        'label'=>"Create automatically unique code for all surveys.",
        'help'=>"If code exist, it can be always used.",
61 62
        'default'=>0,
    ),
Chenu Denis's avatar
Chenu Denis committed
63 64 65 66 67 68 69 70 71 72
    '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,
    ),
73 74 75 76 77
    //~ 'uniqueCodeCode' => array(
        //~ 'type'=>'string',
        //~ 'label'=>"Code in GET params to test.",
        //~ 'default'=>'code',
    //~ ),
78 79 80
  );

  /** @inheritdoc **/
81 82 83 84 85
  public function init()
  {
    $this->subscribe('beforeActivate');
    $oPlugin = Plugin::model()->find("name = :name",array("name"=>get_class($this)));
    if($oPlugin && $oPlugin->active) {
Chenu Denis's avatar
Chenu Denis committed
86
      $this->_setConfig();
87
    }
88
    /* Managing unique code */
89 90
    $this->subscribe('afterModelSave');
    $this->subscribe('afterModelDelete');
91
    /* Get the survey by srid and code */
92
    $this->subscribe('beforeSurveyPage');
93 94
    /* Replace existing system if srid = new */
    $this->subscribe('beforeLoadResponse');
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
    /* Survey settings */
    $this->subscribe('beforeSurveySettings');
    $this->subscribe('newSurveySettings');
  }

  /** @inheritdoc **/
  public function getPluginSettings($getValues=true)
  {
    /* @todo translation of label and help */
    return parent::getPluginSettings($getValues);
  }

  /** @inheritdoc **/
  public function beforeSurveySettings()
  {
    $oEvent = $this->event;
    /* currentDefault translation */
    $allowAdminUserDefault = $this->get('allowAdminUser',null,null,$this->settings['allowAdminUser']['default']) ? gT('Yes') : gT('No');
    $uniqueCodeCreateDefault = $this->get('uniqueCodeCreate',null,null,$this->settings['uniqueCodeCreate']['default']) ? gT('Yes') : gT('No');
Chenu Denis's avatar
Chenu Denis committed
114
    $uniqueCodeAccessDefault = $this->get('uniqueCodeAccess',null,null,$this->settings['uniqueCodeAccess']['default']) ? gT('Yes') : gT('No');
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132

    $oEvent->set("surveysettings.{$this->id}", array(
      'name' => get_class($this),
      'settings' => array(
        'allowAdminUser'=>array(
          'type'=>'select',
          'label'=>$this->gT("Allow admin user to reload any survey with response id."),
          'options'=>array(
            1 =>gT("Yes"),
            0 =>gT("No"),
          ),
          'htmlOptions'=>array(
            'empty' => CHtml::encode(sprintf($this->gT("Use default (%s)"),$allowAdminUserDefault)),
          ),
          'current'=>$this->get('allowAdminUser','Survey',$oEvent->get('survey'),"")
        ),
        'uniqueCodeCreate'=>array(
          'type'=>'select',
Chenu Denis's avatar
Chenu Denis committed
133
          'label'=>$this->gT("Create automatically code."),
134 135 136 137 138 139 140 141 142
          'options'=>array(
            1 =>gT("Yes"),
            0 =>gT("No"),
          ),
          'htmlOptions'=>array(
            'empty' => CHtml::encode(sprintf($this->gT("Use default (%s)"),$uniqueCodeCreateDefault)),
          ),
          'current'=>$this->get('uniqueCodeCreate','Survey',$oEvent->get('survey'),"")
        ),
Chenu Denis's avatar
Chenu Denis committed
143 144 145 146 147 148 149 150 151 152 153 154
        'uniqueCodeAccess'=>array(
          'type'=>'select',
          'label'=>$this->gT("Allow entering unique code if exist."),
          'options'=>array(
            1 =>gT("Yes"),
            0 =>gT("No"),
          ),
          'htmlOptions'=>array(
            'empty' => CHtml::encode(sprintf($this->gT("Use default (%s)"),$uniqueCodeAccessDefault)),
          ),
          'current'=>$this->get('uniqueCodeAccess','Survey',$oEvent->get('survey'),"")
        ),
155 156 157 158 159 160 161 162 163 164 165
      ),
    ));
  }

  /** @inheritdoc **/
  public function newSurveySettings()
  {
    $event = $this->event;
    foreach ($event->get('settings') as $name => $value) {
      $this->set($name, $value, 'Survey', $event->get('survey'));
    }
166 167 168 169 170 171 172 173 174 175 176 177 178
  }

  /** @inheritdoc **/
  public function beforeActivate()
  {
    $this->_createDb();
  }

  /** @inheritdoc **/
  public function afterModelSave()
  {
    $oModel = $this->getEvent()->get('model');
    $className = get_class($oModel);
179 180 181

    /* Delete all link when set a survey to inactive (@todo : test it) */
    if($className == 'Survey') {
Chenu Denis's avatar
Chenu Denis committed
182 183 184 185 186 187
      $sid = isset($oModel->sid) ? $oModel->sid : null;
      if($oModel->sid && $oModel->active != 'Y') {
        $deleted = \reloadAnyResponse\models\responseLink::model()->deleteAll("sid = sid",array('sid'=>$oModel->sid));
        if($deleted>0) { // Don't log each time, can be saved for something other …
          $this->log(sprintf("%d responseLink deleted for %d",$deleted,$oModel->sid),CLogger::LEVEL_INFO);
        }
188 189 190 191
      }
    }

    /* Create responlink for survey and srid (work when start a survey) */
192 193
    if($className == 'SurveyDynamic' || $className == 'Response') {
      $sid = str_replace(array('{{survey_','}}'),array('',''),$oModel->tableName());
194
      /* Test for sid activation */
195
      if(!$this->_getIsActivated('uniqueCodeCreate',$sid)) {
196 197
        return;
      }
198
      $srid = isset($oModel->id) ? $oModel->id : null;
199
      if($sid && $srid) {
Chenu Denis's avatar
Chenu Denis committed
200
        $responseLink = \reloadAnyResponse\models\responseLink::model()->findByPk(array('sid'=>$sid,'srid'=>$srid));
201
        /* @todo : add a way to reset potential token ? */
202
        if(!$responseLink) {
203
          /* @todo replace by \reloadAnyResponse\models\responseLink::getResponseLink('sid'=>$sid,'srid'=>$srid,$token,false) */
204
          $token = isset($oModel->token) ? $oModel->token : null;
205 206
          $responseLink = \reloadAnyResponse\models\responseLink::setResponseLink($sid,$srid,$token);
          if(!$responseLink) {
207 208
            $this->log("Unable to save responseLink with following errors.",CLogger::LEVEL_ERROR);
            $this->log(CVarDumper::dumpAsString($responseLink->getErrors()),CLogger::LEVEL_ERROR);
Chenu Denis's avatar
Chenu Denis committed
209
          }
210 211 212 213 214 215 216 217
        }
      }
    }
  }

  /** @inheritdoc **/
  public function afterModelDelete()
  {
218 219
    $oModel = $this->getEvent()->get('model');
    $className = get_class($oModel);
220 221 222 223
    if($className == 'SurveyDynamic' || $className == 'Response') {
      $sid = str_replace(array('{{survey_','}}'),array('',''),$oModel->tableName());
      $srid = isset($oModel->id) ? $oModel->id : null;
      if($srid) {
Chenu Denis's avatar
Chenu Denis committed
224
        \reloadAnyResponse\models\responseLink::model()->deleteByPk(array('sid'=>$sid,'srid'=>$srid));
225 226 227 228
      }
    }
  }

229 230 231 232 233
  /** @See event */
  public function beforeLoadResponse()
  {
    $srid = App()->getRequest()->getQuery('srid');
    if($srid=='new') {
234 235 236 237 238
        $surveyid = $this->getEvent()->get('surveyId');
        $token = App()->getRequest()->getParam('token');
        $this->getEvent()->set('response',
            $this->_createNewResponse($surveyid,$token)
        );
239 240
    }
  }
241 242 243 244 245 246 247 248
  /** @inheritdoc **/
  public function beforeSurveyPage()
  {
    $srid = App()->getRequest()->getQuery('srid');
    $surveyid = $this->getEvent()->get('surveyId');
    if(!$srid) {
        return;
    }
249
    $oSurvey = Survey::model()->findByPk($surveyid);
250
    $token = App()->getRequest()->getParam('token');
251 252 253
    if($srid == "new") {
        // Done in beforeLoadResponse
      return;
254
    }
255 256
    //~ $accesscode = App()->getRequest()->getQuery($this->get('uniqueCodeCode'),null,null,$this->settings['uniqueCodeCode']['default']);
    $accesscode = App()->getRequest()->getQuery('code');
257
    $editAllowed = false;
258
    if($srid && $accesscode && $this->_getIsActivated('uniqueCodeAccess',$surveyid)) {
Chenu Denis's avatar
Chenu Denis committed
259
      $responseLink = \reloadAnyResponse\models\responseLink::model()->findByPk(array('sid'=>$surveyid,'srid'=>$srid));
260 261 262
      if($responseLink && $responseLink->accesscode == $accesscode) {
          $editAllowed = true;
      }
263
      if(!$responseLink) {
264
            throw new CHttpException(404,$this->gT("Sorry, this response didn't exist."));
265 266
      }
      if($responseLink && $responseLink->accesscode != $accesscode) {
267
            throw new CHttpException(401,$this->gT("Sorry, this access code is invalid."));
268 269
      }
    }
270
    if(!$editAllowed && $this->_getIsActivated('allowToken',$surveyid) && !$oSurvey->getIsAnonymized()) {
271 272 273 274
      $editAllowed = true;
    }
    if(!$editAllowed && $this->_getIsActivated('allowAdminUser',$surveyid) && Permission::model()->hasSurveyPermission($surveyid,'response','update')) {
      $editAllowed = true;
275
    }
276 277 278
    
    if(!$editAllowed) {
        throw new CHttpException(401,$this->gT("Sorry, something happen bad."));
279 280
        return;
    }
281

282 283
    $this->_loadReponse($surveyid,$srid,App()->getRequest()->getParam('token'));
  }
284

285
  /**
286 287 288
   * Get boolean value for setting activation
   * @param string existing $setting
   * @param integer $surveyid
289 290
   * @return boolean
   */
291
  private function _getIsActivated($setting,$surveyid)
292
  {
Chenu Denis's avatar
Chenu Denis committed
293
    $activation = $this->get($setting,'Survey',$surveyid,"");
294 295 296 297 298 299 300 301 302
    if($activation === '') {
      $activation = $this->get($setting,null,null,$this->settings[$setting]['default']);
    }
    return (bool) $activation;
  }
  /**
   * Create needed DB
   * @return viod
   */
303 304 305 306 307 308 309 310 311 312 313 314 315
  private function _createDb()
  {
    if (!$this->api->tableExists($this, 'responseLink'))
    {
      $this->api->createTable($this, 'responseLink', array(
          'sid'=>'int',
          'srid'=>'int',
          'token'=>'text',
          'accesscode'=>'text',
      ));
    }
  }

316 317 318 319
  /**
   * Add needed alias and put it in autoloader
   * @return void
   */
Chenu Denis's avatar
Chenu Denis committed
320
  private function _setConfig()
321 322 323 324 325
  {
    Yii::setPathOfAlias(get_class($this), dirname(__FILE__));
  }

  /**
326
   * Create Survey and add current response in $_SESSION
327 328 329 330 331 332 333
   * @param integer $surveydi
   * @param integer $srid
   * @throws Error 404
   * @return void
   */
  private function _loadReponse($surveyid,$srid,$token = null)
  {
334 335 336 337

    if(isset($_SESSION['survey_'.$surveyid]['srid']) && $_SESSION['survey_'.$surveyid]['srid'] == $srid) {
      return;
    }
338 339 340 341 342 343 344 345 346 347 348
    $oResponse = SurveyDynamic::model($surveyid)->find("id = :srid",array(':srid'=>$srid));
    if(!$oResponse) {
      throw new CHttpException(404, $this->gT('Response not found.'));
    }
    $oSurvey = Survey::model()->findByPk($surveyid);
    // Validate token
    if(!Permission::model()->hasSurveyPermission($surveyid,'response','update') && $oResponse->token) {
      if($oResponse->token != $token) {
        throw new CHttpException(401, $this->gT('Access to this response need valid token.'));
      }
    }
349
    killSurveySession($surveyid); // Is this needed ?
350 351 352 353
    LimeExpressionManager::SetDirtyFlag();
    $_SESSION['survey_'.$surveyid]['srid'] = $oResponse->id;
    if (!empty($oResponse->lastpage)) {
        $_SESSION['survey_'.$surveyid]['LEMtokenResume'] = true;
354
        // If the response was completed start at the beginning and not at the last page - just makes more sense
355 356 357
        if (empty($oResponse->submitdate)) {
            $_SESSION['survey_'.$surveyid]['step'] = $oResponse->lastpage;
        }
358 359 360 361 362
        if(!empty($oResponse->submitdate) && $oSurvey->alloweditaftercompletion != 'Y') {
            $oResponse->submitdate = null;
            $oResponse->save();
            // Better to set Survey to alloweditaftercompletion == 'Y', but unable at this time on afterFindSurvey event
        }
363 364 365 366 367
    }
    buildsurveysession($surveyid);
    if (!empty($oResponse->submitdate)) {
        $_SESSION['survey_'.$surveyid]['maxstep'] = $_SESSION['survey_'.$surveyid]['totalsteps'];
    }
368

369 370
    randomizationGroupsAndQuestions($surveyid);
    initFieldArray($surveyid, $_SESSION['survey_'.$surveyid]['fieldmap']);
371
    loadanswers();
372
  }
Chenu Denis's avatar
Chenu Denis committed
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
  /**
   * Create a new response for token
   * @param int $surveyid
   * @param string $token
   * @return null|\Response
   */
  private function _createNewResponse($surveyid,$token) {
      $oSurvey = Survey::model()->findByPk($surveyid);
      if(!$oSurvey->getHasTokensTable()) {
        return;
      }
      if($oSurvey->getIsAnonymized()) {
        return;
      }
      if(!$oSurvey->tokenanswerspersistence) {
        return;
      }
      if(!$oSurvey->alloweditaftercompletion) {
        return;
      }
    /* some control */
    if(!(
      ($this->_getIsActivated('allowAdminUser',$surveyid) && Permission::model()->hasSurveyPermission($surveyid,'response','create'))
      ||
      ($this->_getIsActivated('allowToken',$surveyid))
      )) {
      // Disable here
      $this->log("Try to create a new reponse with token but without right",'warning');
      return;
    }
    $oToken = Token::model($surveyid)->findByAttributes(array('token' => $token));
    if(empty($oToken)) {
      return;
    }
    $oResponse = Response::create($surveyid);
    $oResponse->token = $oToken->token;
    $oResponse->startlanguage = Yii::app()->getLanguage();
    /* @todo generate if not set */
    $oResponse->seed = isset($_SESSION['survey_'.$surveyid]['startingValues']['seed']) ? $_SESSION['survey_'.$surveyid]['startingValues']['seed'] : null;
    $oResponse->lastpage=-1;
    if($oSurvey->datestamp == 'Y') {
        $date = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig('timeadjust'));
        $oResponse->datestamp = $date;
        $oResponse->startdate = $date;
    }
    $oResponse->save();
    return $oResponse;
  }
Chenu Denis's avatar
Chenu Denis committed
422 423 424 425 426 427 428 429 430 431 432 433
  /**
   * @inheritdoc adding string, by default current event
   * @param string
   */
  public function log($message, $level = \CLogger::LEVEL_TRACE,$logDetail = null)
  {
    if(!$logDetail && $this->getEvent()) {
      $logDetail = $this->getEvent()->getEventName();
    } // What to put if no event ?
    parent::log($message, $level);
    Yii::log($message, $level,'application.plugins.reloadAnyResponse.'.$logDetail);
  }
434
  
435
}