updateTokenAfterSubmit.php 12.1 KB
Newer Older
1 2 3 4 5 6 7
<?php
/**
 * Update (and reset if needed) token code after submission
 *
 * @author Denis Chenu <denis@sondages.pro>
 * @copyright 2018 Denis Chenu <http://www.sondages.pro>
 * @license GPL v3
8
 * @version 0.3.2
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
 *
 * 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 updateTokenAfterSubmit extends PluginBase {

    static protected $description = 'Update (and reset if needed) token code after submission';
    static protected $name = 'updateTokenAfterSubmit';

    protected $storage = 'DbStorage';

    public function init() {
28 29
        $this->subscribe('afterSurveyComplete','afterSurveyComplete');
        $this->subscribe('afterSurveyQuota','afterSurveyQuota');
30 31 32 33 34
        /* Survey settings */
        $this->subscribe('beforeSurveySettings');
        $this->subscribe('newSurveySettings');
    }

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
    public function afterSurveyComplete() {
        if($this->updateToken()) {
            if($this->get('autoRedirect','Survey',$surveyId,1)) {
                $surveyId = $this->getEvent()->get('surveyId');
                $language = Yii::app()->getLanguage();
                $oSurveyLanguageSettings = SurveyLanguageSetting::model()->findByPk(array('surveyls_survey_id'=>$surveyId, 'surveyls_language'=>$language));
                if(!empty($oSurveyLanguageSettings) && !empty($oSurveyLanguageSettings->surveyls_url)) {
                    header("Location: {$oSurveyLanguageSettings->surveyls_url}");
                }
            }
        }
    }

    public function afterSurveyQuota() {
        $this->updateToken();
    }

    /**
     * update token and response
     * @return boolean if action is done (with or without success)
     */
56 57 58 59 60 61
    public function updateToken() {
        $surveyId = $this->getEvent()->get('surveyId');
        $responseId = $this->getEvent()->get('responseId');
        if(empty($responseId)) {
            return;
        }
62 63 64
        if(!$this->_surveySettingsAllowUsage($surveyId)) {
            return;
        }
65 66 67 68 69
        $fixedCode = $this->get('fixedCode','Survey',$surveyId,"");
        if(trim($fixedCode) === "") {
            return;
        }
        $oSurvey = Survey::model()->findByPk($surveyId);
70 71 72 73 74 75
        if(intval(Yii::app()->getConfig('versionnumber')) >= 3) {
            $hasTokenTable = $oSurvey->getHasTokensTable();
        } else {
            $hasTokenTable = Survey::model()->hasTokens($surveyId);
        }
        if(!$hasTokenTable) {
76 77
            return;
        }
78 79 80 81 82 83 84 85 86 87 88 89 90

        $resetTokenResponse = $this->get('resetTokenResponse','Survey',$surveyId,"");
        if(empty($resetTokenResponse)) {
            if($oSurvey->alloweditaftercompletion == "Y") {
                $resetTokenResponse = "N";
            } else {
                $resetTokenResponse = "Y";
            }
        }
        $bResetTokenResponse = $resetTokenResponse == "Y";

        $oResponse = Response::model($surveyId)->findByPk($responseId);
        if(empty($oResponse) || empty($oResponse->token)) {
91 92
            return;
        }
93 94
        $token = $oResponse->token;

95 96 97 98 99 100 101 102 103
        if(substr($token, -strlen($fixedCode)) === $fixedCode){
            return;
        }
        $oToken = Token::model($surveyId)->find("token = :token",array(":token" => $token));
        if(empty($oToken)) {
            $this->log("Token code {$token} not found in survey {$surveyId}",'error');
            return;
        }
        $oToken->token = $token.$fixedCode;
104 105

        if($bResetTokenResponse) {
106 107 108
            $oToken->completed = "N";
            $oToken->usesleft++;
        }
109 110 111 112 113 114 115 116 117 118 119 120
        if($this->get('keepTrackOn','Survey',$surveyId,"")) {
            $keepTrackOn = $this->get('keepTrackOn','Survey',$surveyId,"");
            $currentTrack = isset($oToken->$keepTrackOn) ? $oToken->$keepTrackOn : null;
            if(!is_null($currentTrack)) {
                $numberTrack = 0;
                if(substr($currentTrack, 0, strlen("updateTokenAfterSubmit-")) === "updateTokenAfterSubmit-") {
                    $numberTrack = intval(substr($currentTrack,strlen("updateTokenAfterSubmit-")));
                }
                $numberTrack++;
                $oToken->$keepTrackOn = "updateTokenAfterSubmit-".$numberTrack;
            }
        }
121 122
        if($this->get('emailUpdatedTo','Survey',$surveyId,"")) {
            $emailUpdatedTo = $this->get('emailUpdatedTo','Survey',$surveyId,"");
123 124 125 126 127
            if(intval(Yii::app()->getConfig('versionnumber')) >= 3) {
                $emailUpdatedTo = LimeExpressionManager::ProcessStepString($emailUpdatedTo,array(),3,true); // as static
            } else {
                $emailUpdatedTo = LimeExpressionManager::ProcessString($emailUpdatedTo,null, array(), false, 3, 1, false, false, true);
            }
128 129 130
            $oToken->scenario = 'allowinvalidemail'; // Need diable rule
            $oToken->email = $emailUpdatedTo;
        }
131 132 133 134 135 136
        if(!$oToken->save()) {
            $this->log("Unable to update token code {$token} in survey {$surveyId}",'error');
            $this->log(sprintf("With error %",CVarDumper::dumpAsString($oToken->getErrors(), 2, false)),'warning');
        } else {
            $this->log("Update token code {$token} in survey {$surveyId} with success",'info');
        }
137 138

        if($bResetTokenResponse) {
139
            $oResponse->submitdate = null;
140
            $oResponse->lastpage = 1;
141
        }
142 143 144 145 146 147 148 149
        $oResponse->token = $token.$fixedCode;
        if(!$oResponse->save()) {
            $this->log("Unable to update response {$responseId} in survey {$surveyId}",'error');
            $this->log(sprintf("With error %",CVarDumper::dumpAsString($oResponse->getErrors(), 2, false)),'warning');
        } else {
            $this->log("Update response {$responseId} in survey {$surveyId} with success",'info');
        }
        return true;
150 151 152 153 154 155 156
    }

    /** @inheritdoc **/
    public function beforeSurveySettings()
    {
        $oEvent = $this->event;
        $surveyId = $oEvent->get('survey');
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
        $oSurvey = Survey::model()->findByPk($surveyId);
        $aSettings = array();
        if(!$this->_surveySettingsAllowUsage($surveyId)) {
            $aSettings['warning']= array(
                'type' => 'info',
                'content' => "<div class='alert alert-warning warning'>".$this->_translate("Curent settings disallow usage of this plugin: anonymized responses and token-based response persistence must be on")."</div>",
            );
        } else {
            if($oSurvey->autoredirect == "Y") {
                $aSettings['warning']= array(
                    'type' => 'info',
                    'content' => "<div class='alert alert-warning warning'>".$this->_translate("Automatically load URL when survey complete is activated, this disable usage of this plugin.")."</div>",
                );
            }
        }
        $aSettings = array_merge($aSettings,array(
            'fixedCode' => array(
                'type' => 'string',
                'label' => $this->_translate("Fixed code to add when survey is submitted."),
                'help' => $this->_translate("This code is added at the end of the token only if it does not end already with this code."),
                'current' => $this->get('fixedCode','Survey',$surveyId,"")
            ),
            'keepTrackOn' => array(
                'type' => 'select',
                'options' => $this->_getTokensAttributeList($surveyId),
                'htmlOptions' => array(
                    'empty' => $this->_translate("No tracking on token table"),
184
                ),
185 186 187 188 189 190 191 192 193
                'label' => $this->_translate("Where to keep track information about updated token."),
                'help' => $this->_translate("Data for this token is updated to updateTokenAfterSubmit-X, where X is the number of updating done."),
                'current'=>$this->get('keepTrackOn','Survey',$surveyId,""),
            ),
            'resetTokenResponse' => array(
                'type' => 'select',
                'options' => array(
                    'Y'=>gT("Yes"),
                    'N'=>gT("No"),
194
                ),
195 196
                'htmlOptions' => array(
                    'empty' => $this->_translate("Automatic"),
197
                ),
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
                'label' => $this->_translate("Reset token and response to allow editing response. "),
                'help' => $this->_translate("Token is reset to not completed and response to not submitted.Automatic mean do it if survey don‘t allow edit after completion."),
                'current'=>$this->get('resetTokenResponse','Survey',$surveyId,""),
            ),
            'emailUpdatedTo' => array(
                'type' => 'string',
                'label' => $this->_translate("Update email with new value."),
                'help' => $this->_translate("Usage of expression is allowed and invalid email is saved too."),
                'current'=>$this->get('emailUpdatedTo','Survey',$surveyId,""),
            ),
            'autoRedirect' => array(
                'type' => 'boolean',
                'label' => $this->_translate("Automatically load URL after this plugin action."),
                'help' => $this->_translate("You can‘t use automatically load URL when survey complete from limesurvey core, then if needed activate it here. Warning : no replacement is done on the url. This redirection is done only if token are updated."),
                'current'=>$this->get('autoRedirect','Survey',$surveyId,0),
            ),
        ));
        $oEvent->set("surveysettings.{$this->id}", array(
            'name' => get_class($this),
            'settings' => $aSettings
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
        ));
    }

    /** @inheritdoc **/
    public function newSurveySettings()
    {
        $event = $this->getEvent();
        foreach ($event->get('settings') as $name => $value) {
          $this->set($name, $value, 'Survey', $event->get('survey'));
        }
    }

    /**
     * get the token attribute in listData
     * @param integer $surveyId
     * @param string $prefix
     * @return array
     */
    private function _getTokensAttributeList($surveyId,$prefix="") {
        $oSurvey = Survey::model()->findByPk($surveyId);
        $aTokenAttributes = array(
            $prefix.'firstname'=>gT("First name"),
            $prefix.'lastname'=>gT("Last name"),
            $prefix.'email'=>gT("Email"),
            $prefix.'emailstatus'=>gT("Email status"),
        );
        foreach($oSurvey->getTokenAttributes() as $attribute=>$information) {
            $aTokenAttributes[$prefix.$attribute] = empty($information['description']) ? $attribute : $information['description'];
        }
        return $aTokenAttributes;
    }

    /**
     * Own translation using parent::gT
     * @see parent::gT
     */
    public function _translate($string, $sEscapeMode = 'unescaped', $sLanguage = NULL) {
        if(intval(Yii::app()->getConfig('versionnumber')) >= 3) {
            return parent::gT($string, $sEscapeMode, $sLanguage );
        }
        return $string;
    }

    /**
    * @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();
269 270 271 272
        }
        if(empty($logDetail)) {
            $logDetail = "unknow";
        }
273 274 275
        if(intval(Yii::app()->getConfig('versionnumber')) >= 3) {
            parent::log($message, $level);
        }
276 277 278 279 280 281 282 283 284 285 286 287
        Yii::log($message, $level,'application.plugins.updateTokenAfterSubmit.'.$logDetail);
    }

    /**
     * Find if survey settings allow usage of this plugin
     * @param integer $surveyId
     * return boolean
     */
    private function _surveySettingsAllowUsage($surveyId)
    {
        $oSurvey = Survey::model()->findByPk($surveyId);
        return ($oSurvey->anonymized !="Y" && $oSurvey->tokenanswerspersistence =="Y");
288 289
    }
}