responseListAndManage.php 115 KB
Newer Older
1 2
<?php
/**
3
 * Responses List And Manage
4 5 6 7
 *
 * @author Denis Chenu <denis@sondages.pro>
 * @copyright 2018 Denis Chenu <http://www.sondages.pro>
 * @license GPL v3
8
 * @version 1.13.2
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
 *
 * 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 responseListAndManage extends PluginBase {

    protected $storage = 'DbStorage';
    static protected $description = 'A different way to manage response for a survey';
    static protected $name = 'responseListAndManage';

    /**
     * @var array[] the settings
     */
29
     protected $settings = array(
30 31 32 33 34 35
        'information' => array(
            'type' => 'info',
            'content' => 'Access link is …',
        ),
        'template' => array(
            'type' => 'info',
36
            'default' => 'default',
37 38 39 40 41 42 43 44 45
            'label' => 'Template to be used',
        ),
        'showLogOut' => array(
            'type' => 'boolean',
            'default' => false,
            'label' => 'Show log out',
        ),
        'showAdminLink' => array(
            'type' => 'boolean',
46
            'default' => 1,
47
            'label' => 'Show administration link',
48
        ),
49 50 51 52 53 54
        'forceDownloadImage' => array(
            'type' => 'boolean',
            'default' => 1,
            'label' => 'Force download of image',
            'help' => 'When click on an image (png,jpg,gif or pdf) : image is directly open in browser (if able). You need a javascript solution if you want to open it in new tab',
        ),
55 56
    );

57 58
    protected $mailError;
    protected $mailDebug;
59 60 61 62 63 64 65 66 67 68
    //public $iSurveyId;
    
    /**
     * var array aRenderData
     */
    private $aRenderData = array();

    public function init() {
        $this->subscribe('newDirectRequest');
        $this->subscribe('beforeSurveySettings');
69 70
        //~ $this->subscribe('newSurveySettings');
        $this->subscribe('beforeToolsMenuRender');
71 72 73
        /* API dependant */
        $this->subscribe('getPluginTwigPath');

Chenu Denis's avatar
Chenu Denis committed
74
        /* Need some event in iframe survey */
75
        $this->subscribe('beforeSurveyPage');
76 77
        /* Replace token by the valid one before beforeSurveyPage @todo */
        $this->subscribe('beforeControllerAction');
Chenu Denis's avatar
Chenu Denis committed
78 79 80

        /* Need for own language system */
        $this->subscribe('afterPluginLoad');
81 82 83 84 85 86 87
    }

    /**
     * @see event
     */
    public function beforeSurveyPage()
    {
Chenu Denis's avatar
Chenu Denis committed
88 89 90
        if(!$this->_isUsable()) {
            return;
        }
91 92 93
        if(Yii::app()->session['responseListAndManage'] != $this->getEvent()->get('surveyId')) {
            return;
        }
94 95 96 97
        $surveyId = $this->getEvent()->get('surveyId');
        $currentSrid = isset($_SESSION['survey_'.$surveyId]['srid']) ? $_SESSION['survey_'.$surveyId]['srid'] : null;
        App()->getClientScript()->registerScriptFile(Yii::app()->assetManager->publish(dirname(__FILE__) . '/assets/surveymanaging/surveymanaging.js'),CClientScript::POS_BEGIN);

98 99
        if(Yii::app()->getRequest()->getParam("saveall")) {
            App()->getClientScript()->registerScript("justsaved","autoclose();\n",CClientScript::POS_END);
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
            if($currentSrid) {
                $oSurvey = Survey::model()->findByPk($surveyId);
                if($oSurvey->active == "Y") {
                    $step = isset($_SESSION['survey_'.$surveyId]['step']) ? $_SESSION['survey_'.$surveyId]['step'] : 0;
                    LimeExpressionManager::JumpTo($step, false);
                    $oResponse = SurveyDynamic::model($surveyId)->findByPk($currentSrid);
                    $oResponse->lastpage = $step; // Or restart at 1st page ?
                    // Save must force always to not submitted (draft)
                    $oResponse->submitdate = null;
                    $oResponse->save();
                }
                killSurveySession($surveyId);
                \reloadAnyResponse\models\surveySession::model()->deleteByPk(array('sid'=>$surveyId,'srid'=>$currentSrid));
                if(Yii::getPathOfAlias('renderMessage')) {
                    \renderMessage\messageHelper::renderAlert($this->_translate("Your responses was saved with success, you can close this windows."));
                }
            }
117 118 119
        }
        if(Yii::app()->getRequest()->getParam("clearall")=="clearall" && Yii::app()->getRequest()->getParam("confirm-clearall")) {
            App()->getClientScript()->registerScript("justsaved","autoclose();\n",CClientScript::POS_END);
120
            \reloadAnyResponse\models\surveySession::model()->deleteByPk(array('sid'=>$surveyId,'srid'=>$currentSrid));
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
        }

    }
    /**
     * Add some views for this and other plugin
     */
    public function getPluginTwigPath()
    {
        $viewPath = dirname(__FILE__)."/twig";
        $this->getEvent()->append('add', array($viewPath));
    }

    /** @inheritdoc **/
    public function beforeSurveySettings()
    {
Chenu Denis's avatar
Chenu Denis committed
136 137 138
        if(!$this->_isUsable()) {
            return;
        }
139 140 141
        /* @Todo move this to own page */
        $oEvent = $this->getEvent();
        $iSurveyId = $this->getEvent()->get('survey');
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
        $accesUrl = Yii::app()->createUrl("plugins/direct", array('plugin' => get_class(),'sid'=>$iSurveyId));
        $managementUrl = Yii::app()->createUrl('admin/pluginhelper',
            array(
                'sa' => 'sidebody',
                'plugin' => get_class($this),
                'method' => 'actionSettings',
                'surveyId' => $iSurveyId
            )
        );

        $this->getEvent()->set("surveysettings.{$this->id}", array(
            'name' => get_class($this),
            'settings' => array(
                'link'=>array(
                    'type'=>'info',
157
                    'content'=> CHtml::link($this->_translate("Access to responses listing"),$accesUrl,array("target"=>'_blank','class'=>'btn btn-block btn-default btn-lg')),
158 159 160
                ),
                'linkManagement'=>array(
                    'type'=>'info',
161
                    'content'=> CHtml::link($this->_translate("Manage settings of responses listing"),$managementUrl,array("target"=>'_blank','class'=>'btn btn-block btn-default btn-lg')),
162 163 164 165 166 167 168 169 170 171 172 173 174 175
                ),
            )
        ));
    }

    /**
     * see beforeToolsMenuRender event
     *
     * @return void
     */
    public function beforeToolsMenuRender()
    {
        $event = $this->getEvent();
        $surveyId = $event->get('surveyId');
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
        if(Permission::model()->hasSurveyPermission($surveyId, 'surveysettings', 'update')) {
            $aMenuItem = array(
                'label' => $this->_translate('Response listing settings'),
                'iconClass' => 'fa fa-list-alt ',
                'href' => Yii::app()->createUrl(
                    'admin/pluginhelper',
                    array(
                        'sa' => 'sidebody',
                        'plugin' => get_class($this),
                        'method' => 'actionSettings',
                        'surveyId' => $surveyId
                    )
                ),
            );
            if (class_exists("\LimeSurvey\Menu\MenuItem")) {
                $menuItem = new \LimeSurvey\Menu\MenuItem($aMenuItem);
            } else {
                $menuItem = new \ls\menu\MenuItem($aMenuItem);
            }
            $event->append('menuItems', array($menuItem));
        }
        if(Permission::model()->hasSurveyPermission($surveyId, 'responses', 'read') && $this->get('allowAccess','Survey',$surveyId,'all') ) {
            $aMenuItem = array(
                'label' => $this->_translate('Response listing'),
                'iconClass' => 'fa fa-list-alt ',
                'href' => Yii::app()->createUrl(
                    'plugins/direct',
                    array(
                        'plugin' => get_class($this),
                        'sid' => $surveyId
                    )
                ),
            );
            if (class_exists("\LimeSurvey\Menu\MenuItem")) {
                $menuItem = new \LimeSurvey\Menu\MenuItem($aMenuItem);
            } else {
                $menuItem = new \ls\menu\MenuItem($aMenuItem);
            }
214

215
            $event->append('menuItems', array($menuItem));
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
        }
    }

    /**
     * Main function to replace surveySetting
     * @param int $surveyId Survey id
     *
     * @return string
     */
    public function actionSettings($surveyId)
    {
        $oSurvey=Survey::model()->findByPk($surveyId);
        if(!$oSurvey) {
            throw new CHttpException(404,gT("This survey does not seem to exist."));
        }
        if(!Permission::model()->hasSurveyPermission($surveyId,'surveysettings','update')){
            throw new CHttpException(403);
        }
        if(App()->getRequest()->getPost('save'.get_class($this))) {
            // Adding save part
            $settings = array(
237
                'showId','showCompleted','showSubmitdate','showStartdate','showDatestamp',
238
                'tokenAttributes','surveyAttributes','surveyAttributesPrimary',
239
                'tokenColumnOrder',
240
                'tokenAttributesHideToUser','surveyAttributesHideToUser',
241
                'tokenAttributeGroup', 'tokenAttributeGroupManager', 'tokenAttributeGroupWhole',
242
                'allowAccess','allowSee','allowEdit','allowDelete', 'allowAdd','allowAddSelf','allowAddUser',
243
                'template',
244
                'showFooter',
245
                'filterOnDate','filterSubmitdate','filterStartdate','filterDatestamp',
246
                'showLogOut','showSurveyAdminpageLink',
247
                'showExportLink','exportType','exportHeadexports','exportAnswers',
248 249 250 251
            );
            foreach($settings as $setting) {
                $this->set($setting, App()->getRequest()->getPost($setting), 'Survey', $surveyId);
            }
252

253 254 255 256 257 258 259 260
            $languageSettings = array('description');
            foreach($languageSettings as $setting) {
                $finalSettings = array();
                foreach($oSurvey->getAllLanguages() as $language) {
                    $finalSettings[$language] = App()->getRequest()->getPost($setting.'_'.$language);
                }
                $this->set($setting, $finalSettings, 'Survey', $surveyId);
            }
261 262 263 264

            if(App()->getRequest()->getPost('save'.get_class($this)=='redirect')) {
                Yii::app()->getController()->redirect(Yii::app()->getController()->createUrl('admin/survey',array('sa'=>'view','surveyid'=>$surveyId)));
            }
265
        }
266
        $stateInfo = "<ul class='list'>";
267
        if($this->_allowTokenLink($oSurvey)) {
268
            $stateInfo .= CHtml::tag("li",array("class"=>'text-success'),$this->_translate("Token link and creation work in managing."));
269
        } else {
Chenu Denis's avatar
Chenu Denis committed
270
            $stateInfo .= CHtml::tag("li",array("class"=>'text-warning'),$this->_translate("No Token link and creation can be done in managing. Survey is anonymous or token table didn‘t exist."));
271 272
        }
        if($this->_allowMultipleResponse($oSurvey)) {
273
            $stateInfo .= CHtml::tag("li",array("class"=>'text-success'),$this->_translate("You can create new response for all token."));
274
        } else {
Chenu Denis's avatar
Chenu Denis committed
275
            $stateInfo .= CHtml::tag("li",array("class"=>'text-warning'),$this->_translate("You can not create new response for all token. Only one response is available for each token (see participation setting panel)."));
276 277
        }
        $stateInfo .= "</ul>";
278 279
        $surveyColumnsInformation = new \getQuestionInformation\helpers\surveyColumnsInformation($surveyId,App()->getLanguage());
        $aQuestionList = $surveyColumnsInformation->allQuestionListData();
280 281 282 283 284 285 286 287
        $accesUrl = Yii::app()->createUrl("plugins/direct", array('plugin' => get_class(),'sid'=>$surveyId));
        $aSettings[$this->_translate('Response Management')] = array(
            'link'=>array(
                'type'=>'info',
                'content'=> CHtml::link($this->_translate("Link to response alternate management"),$accesUrl,array("target"=>'_blank','class'=>'btn btn-block btn-default btn-lg')),
            ),
            'infoList' => array(
                'type'=>'info',
288
                'content'=> CHtml::tag("div",array('class'=>'well well-sm'),$stateInfo),
289 290 291
            ),
        );
        $aSettings[$this->_translate('Response Management table')] = array(
292 293 294 295 296 297 298 299 300 301
            'showId' => array(
                'type'=>'boolean',
                'label'=>$this->_translate('Show id of response.'),
                'current'=>$this->get('showId','Survey',$surveyId,1)
            ),
            'showCompleted' => array(
                'type'=>'boolean',
                'label'=>$this->_translate('Show completed state.'),
                'current'=>$this->get('showCompleted','Survey',$surveyId,1)
            ),
302 303 304 305 306 307 308 309
            'tokenAttributes' => array(
                'type'=>'select',
                'label'=>$this->_translate('Token attributes to show in management'),
                'options'=>$this->_getTokensAttributeList($surveyId,'tokens.'),
                'htmlOptions'=>array(
                    'multiple'=>true,
                    'placeholder'=>gT("All"),
                    'unselectValue'=>"",
310
                ),
311 312
                'selectOptions'=>array(
                    'placeholder'=>gT("All"),
313
                ),
314 315
                'current'=>$this->get('tokenAttributes','Survey',$surveyId)
            ),
316 317 318 319 320 321 322 323 324 325
            'tokenColumnOrder' => array(
                'type'=>'select',
                'label'=>$this->_translate('Token attributes order'),
                'options'=>array(
                    'start' => $this->_translate("At start (before primary columns)"),
                    'default' => $this->_translate("Between primary columns and secondary columns (default)"),
                    'end' => $this->_translate("At end (after all other columns)"),
                ),
                'current'=>$this->get('tokenColumnOrder','Survey',$surveyId,'default')
            ),
326 327 328 329 330 331 332 333
            'surveyAttributes' => array(
                'type'=>'select',
                'label'=>$this->_translate('Survey columns to be show in management'),
                'options'=>$aQuestionList['data'],
                'htmlOptions'=>array(
                    'multiple'=>true,
                    'placeholder'=>gT("All"),
                    'unselectValue'=>"",
334
                    'options'=>$aQuestionList['options'], // In dropdown, but not in select2
335
                ),
336 337 338
                'selectOptions'=>array(
                    'placeholder'=>gT("All"),
                    //~ 'templateResult'=>"formatQuestion",
339
                ),
340 341
                'controlOptions' => array(
                    'class'=>'select2-withover ',
342
                ),
343 344
                'current'=>$this->get('surveyAttributes','Survey',$surveyId)
            ),
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
            'surveyAttributesPrimary' => array(
                'type'=>'select',
                'label'=> $this->_translate('Survey columns to be show at first'),
                'help' => $this->_translate('This question are shown at first, just after the id of the reponse.'),
                'options'=>$aQuestionList['data'],
                'htmlOptions'=>array(
                    'multiple'=>true,
                    'placeholder'=>gT("None"),
                    'unselectValue'=>"",
                    'options'=>$aQuestionList['options'], // In dropdown, but not in select2
                ),
                'selectOptions'=>array(
                    'placeholder'=>gT("None"),
                    //~ 'templateResult'=>"formatQuestion",
                ),
                'controlOptions' => array(
                    'class'=>'select2-withover ',
                ),
                'current'=>$this->get('surveyAttributesPrimary','Survey',$surveyId)
            ),
365 366
            'tokenAttributesHideToUser' => array(
                'type'=>'select',
367 368
                'label'=> $this->_translate('Token columns to be hidden to user (include group administrator)'),
                'help' => $this->_translate('This column are shown only to LimeSurvey administrator.'),
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
                'options'=>$this->_getTokensAttributeList($surveyId,'tokens.'),
                'htmlOptions'=>array(
                    'multiple'=>true,
                    'placeholder'=>gT("None"),
                    'unselectValue'=>"",
                ),
                'selectOptions'=>array(
                    'placeholder'=>gT("None"),
                    //~ 'templateResult'=>"formatQuestion",
                ),
                'controlOptions' => array(
                    'class'=>'select2-withover ',
                ),
                'current'=>$this->get('tokenAttributesHideToUser','Survey',$surveyId)
            ),
            'surveyAttributesHideToUser' => array(
                'type'=>'select',
386 387
                'label'=> $this->_translate('Survey columns to be hidden to user (include group administrator)'),
                'help' => $this->_translate('This column are shown only to LimeSurvey administrator.'),
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
                'options'=>$aQuestionList['data'],
                'htmlOptions'=>array(
                    'multiple'=>true,
                    'placeholder'=>gT("None"),
                    'unselectValue'=>"",
                    'options'=>$aQuestionList['options'], // In dropdown, but not in select2
                ),
                'selectOptions'=>array(
                    'placeholder'=>gT("None"),
                    //~ 'templateResult'=>"formatQuestion",
                ),
                'controlOptions' => array(
                    'class'=>'select2-withover ',
                ),
                'current'=>$this->get('surveyAttributesHideToUser','Survey',$surveyId)
            ),
404 405 406 407 408
            'showFooter' => array(
                'type'=>'boolean',
                'label'=>$this->_translate('Show footer with count and sum.'),
                'current'=>$this->get('showFooter','Survey',$surveyId,0)
            ),
409
        );
410 411 412 413 414 415
        $aSettings[$this->_translate('Date/time response management')] = array(
            'filterOnDate' => array(
                'type'=>'boolean',
                'label'=>$this->_translate('Show filter on date question.'),
                'current'=>$this->get('filterOnDate','Survey',$surveyId,1)
            ),
416 417
            'showDateInfo' => array(
                'type' => 'info',
418
                'content' => CHtml::tag("div",array("class"=>"well"),$this->_translate("All this settings after need date stamped survey.")),
419
            ),
420 421 422 423 424 425
            'showStartdate' => array(
                'type'=>'boolean',
                'label'=>$this->_translate('Show start date.'),
                
                'current'=>$this->get('showStartdate','Survey',$surveyId,0)
            ),
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
            'filterStartdate' => array(
                'type'=>'select',
                'options' => array(
                    0 => gT("No"),
                    1 => gT("Yes"),
                    2 => $this->_translate("Yes with time"),
                ),
                'label'=>$this->_translate('Show filter on start date.'),
                'current'=>$this->get('filterStartdate','Survey',$surveyId,0)
            ),
            'showSubmitdate' => array(
                'type'=>'boolean',
                'label'=>$this->_translate('Show submit date.'),
                'current'=>$this->get('showSubmitdate','Survey',$surveyId,0)
            ),
            'filterSubmitdate' => array(
                'type'=>'select',
                'options' => array(
                    0 => gT("No"),
                    1 => gT("Yes"),
                    2 => $this->_translate("Yes with time"),
                ),
                'label'=>$this->_translate('Show filter on submit date.'),
                'current'=>$this->get('filterSubmitdate','Survey',$surveyId,0)
            ),
451 452 453 454 455
            'showDatestamp' => array(
                'type'=>'boolean',
                'label'=>$this->_translate('Show last action date.'),
                'current'=>$this->get('showDatestamp','Survey',$surveyId,0)
            ),
456 457 458 459 460 461 462 463 464 465
            'filterDatestamp' => array(
                'type'=>'select',
                'options' => array(
                    0 => gT("No"),
                    1 => gT("Yes"),
                    2 => $this->_translate("Yes with time"),
                ),
                'label'=>$this->_translate('Show filter on start date.'),
                'current'=>$this->get('filterDatestamp','Survey',$surveyId,0)
            ),
466
        );
467
        /* Descrition by lang */
468 469 470 471 472 473 474 475 476 477
        $aDescription = array();
        $aDescriptionCurrent = $this->get('description','Survey',$surveyId);
        $languageData = getLanguageData(false,Yii::app()->getLanguage());
        foreach($oSurvey->getAllLanguages() as $language) {
            $aDescription['description_'.$language] = array(
                'type' => 'text',
                'label' => sprintf($this->_translate("In %s language (%s)"),$languageData[$language]['description'],$languageData[$language]['nativedescription']),
                'current' => (isset($aDescriptionCurrent[$language]) ? $aDescriptionCurrent[$language] : ""),
            );
        }
478
        $aSettings[$this->_translate('Description and helper for responses listing')] = $aDescription;
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
        /* Template to be used */
        if(version_compare(Yii::app()->getConfig('versionnumber'),"3",">=")) {
            $oTemplates = TemplateConfiguration::model()->findAll(array(
                'condition'=>'sid IS NULL',
                'order'=>'template_name',
            ));
            $aTemplates = CHtml::listData($oTemplates,'template_name','template_name');
        }
        if(version_compare(Yii::app()->getConfig('versionnumber'),"3","<")) {
          $aTemplates = array_keys(Template::getTemplateList());
        }
        $default = $this->get('template',null,null,App()->getConfig('defaulttheme',App()->getConfig('defaulttemplate')));
        $aSettings[$this->_translate('Template to be used')] = array(
            'template' => array(
                'type' => 'select',
                'label'=> $this->_translate('Template to be used'),
                'options'=>$aTemplates,
                'htmlOptions' => array(
                    'empty'=> sprintf($this->_translate("Leave default (%s)"),$default),
                ),
                'current' => $this->get('template','Survey',$surveyId),
            )
        );
        /* Token attribute usage */
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
        $aSettings[$this->_translate('Response Management token attribute usage')] = array(
            'tokenAttributeGroup' => array(
                'type'=>'select',
                'label'=>$this->_translate('Token attributes for group'),
                'options'=>$this->_getTokensAttributeList($surveyId,''),
                'htmlOptions'=>array(
                    'empty'=>$this->_translate("None"),
                ),
                'current'=>$this->get('tokenAttributeGroup','Survey',$surveyId)
            ),
            'tokenAttributeGroupManager' => array(
                'type'=>'select',
                'label'=>$this->_translate('Token attributes for group manager'),
                'options'=>$this->_getTokensAttributeList($surveyId,''),
                'htmlOptions'=>array(
                    'empty'=>$this->_translate("None"),
                ),
                'current'=>$this->get('tokenAttributeGroupManager','Survey',$surveyId)
            ),
            //~ 'tokenAttributeGroupWhole' => array(
                //~ 'type'=>'boolean',
                //~ 'label'=>$this->_translate('User of group can see and manage all group response'),
                //~ 'help'=>$this->_translate('Else only group manager can manage other group response.'),
                //~ 'current'=>$this->get('tokenAttributeGroupWhole','Survey',$surveyId,1)
            //~ ),
        );
529 530
        /* @todo : get settings of reloadAnyResponse and set warning + readonly on some settings */
        
531
        $aSettings[$this->_translate('Response Management access and right')] = array(
532 533 534
            'infoRights' => array(
                'type'=>'info',
                'content'=>CHtml::tag("ul",array('class'=>'well well-sm list-unstyled'),
535
                    CHtml::tag("li",array(),$this->_translate("Currently, for LimeSurvey admin user, for survey with token, need token read right.")) .
536 537
                    CHtml::tag("li",array(),$this->_translate("For user, except for No : they always have same rights than other, for example if you allow delete to admin user, an user with token can delete his response with token.")) .
                    CHtml::tag("li",array(),$this->_translate("To disable access for user with token you can set this settings to No or only for LimeSurvey admin.")) .
538
                    CHtml::tag("li",array('class'=>'text-warning'),sprintf("<strong>%s</strong>%s",$this->_translate("Warning"),$this->_translate(": you need to update reloadAnyResponse settings and right. This was not fixed here."))) .
539 540 541
                    ""
                ),
            ),
542 543 544 545
            'allowAccess' => array(
                'type'=>'select',
                'label'=>$this->_translate('Allow to access of tool.'),
                'options'=>array(
Chenu Denis's avatar
Chenu Denis committed
546
                    'limesurvey'=>$this->_translate("Only for LimeSurvey administrator (According to LimeSurvey Permission)"),
547
                    'all'=>$this->_translate("All (need a valid token)"),
548 549 550 551 552 553 554
                ),
                'htmlOptions'=>array(
                    'empty'=>gT("None"),
                ),
                'help'=>$this->_translate('You can disable all access with token here. If user can access to the tool, he have same right than LimeSurvey admin on his responses.'),
                'current'=>$this->get('allowAccess','Survey',$surveyId,'all')
            ),
555 556 557 558
            'allowSee' => array(
                'type'=>'select',
                'label'=>$this->_translate('Allow view response of group'),
                'options'=>array(
Chenu Denis's avatar
Chenu Denis committed
559
                    'limesurvey'=>$this->_translate("Only for LimeSurvey administrator"),
560
                    'admin'=>$this->_translate("For group administrator and LimeSurvey administrator"),
561
                    'all'=>$this->_translate("All (with a valid token)"),
562
                ),
563 564
                'htmlOptions'=>array(
                    'empty'=>gT("No"),
565
                ),
566
                'help'=>$this->_translate('Only related to Group responses not to single user responses with token.'),
567 568 569 570 571 572
                'current'=>$this->get('allowSee','Survey',$surveyId,'all')
            ),
            'allowEdit' => array(
                'type'=>'select',
                'label'=>$this->_translate('Allow edit response of group'),
                'options'=>array(
Chenu Denis's avatar
Chenu Denis committed
573
                    'limesurvey'=>$this->_translate("Only for LimeSurvey administrator"),
574
                    'admin'=>$this->_translate("For group administrator and LimeSurvey administrator"),
575
                    'all'=>$this->_translate("All (with a valid token)"),
576
                ),
577 578
                'htmlOptions'=>array(
                    'empty'=>gT("No"),
579
                ),
580
                'help'=>$this->_translate('Need view rights.'),
581 582 583 584 585 586
                'current'=>$this->get('allowEdit','Survey',$surveyId,'admin')
            ),
            'allowDelete' => array(
                'type'=>'select',
                'label'=>$this->_translate('Allow deletion of response'),
                'options'=>array(
587
                    'limesurvey'=>$this->_translate("Only for LimeSurvey administrator"),
588
                    'admin'=>$this->_translate("For group administrator and LimeSurvey administrator"),
589
                    'all'=>$this->_translate("All (with a valid token)"),
590 591 592 593
                ),
                'htmlOptions'=>array(
                    'empty'=>gT("No"),
                ),
594
                'help'=>$this->_translate('Need view rights.'),
595 596 597 598 599 600
                'current'=>$this->get('allowDelete','Survey',$surveyId,'admin')
            ),
            'allowAdd' => array(
                'type'=>'select',
                'label'=>$this->_translate('Allow add response'),
                'options'=>array(
601
                    'limesurvey'=>$this->_translate("Only for LimeSurvey administrator"),
602
                    'admin'=>$this->_translate("For group administrator and LimeSurvey administrator"),
603
                    'all'=>$this->_translate("All (with a valid token)"),
604 605 606 607
                ),
                'htmlOptions'=>array(
                    'empty'=>gT("No"),
                ),
608
                'help'=>$this->_translate('Need view rights, for administrator, allow to choose token for creation.'),
609 610
                'current'=>$this->get('allowAdd','Survey',$surveyId,'admin')
            ),
611 612 613
            'allowAddSelf' => array(
                'type'=>'boolean',
                'label'=>$this->_translate('Allow add response with existing token according to survey setting'),
Chenu Denis's avatar
Chenu Denis committed
614
                'help'=>$this->_translate('If survey settings allow user to create new response, add a button to create a new response.'),
615 616
                'current'=>$this->get('allowAddSelf','Survey',$surveyId,true)
            ),
617 618 619 620
            'allowAddUser' => array(
                'type'=>'select',
                'label'=>$this->_translate('Allow add token user'),
                'options'=>array(
621
                    'limesurvey'=>$this->_translate("Only for LimeSurvey administrator"),
622
                    'admin'=>$this->_translate("For group administrator and LimeSurvey administrator"),
623
                    'all'=>$this->_translate("All (with a valid token)"),
624 625 626 627
                ),
                'htmlOptions'=>array(
                    'empty'=>gT("No"),
                ),
628
                'help'=>$this->_translate('Need add response right.'),
629 630
                'current'=>$this->get('allowAddUser','Survey',$surveyId,'admin')
            ),
631 632 633 634
        );

        $exportList = $this->_getExportList();
        $aSettings[$this->_translate('User tools')] = array(
635
            'showLogOut' => array(
636 637 638 639 640 641 642 643 644
                'type'=>'select',
                'label'=>$this->_translate('Show log out button'),
                'options'=>array(
                    'limesurvey'=>$this->_translate("Only for LimeSurvey administrator"),
                    'all'=>gT("Yes"),
                ),
                'htmlOptions'=>array(
                    'empty'=>gT("No"),
                ),
645
                'current'=>$this->get('showLogOut','Survey',$surveyId,$this->get('showLogOut',null,null,$this->settings['showLogOut']['default']) ? 'admin': null)
646 647 648 649 650 651 652 653 654 655 656 657
            ),
            'showSurveyAdminpageLink' => array(
                'type'=>'select',
                'label'=>$this->_translate('Show survey admin page link'),
                'options'=>array(
                    'limesurvey'=>$this->_translate("All LimeSurvey administrator"),
                    'admin'=>$this->_translate("LimeSurvey administrator with survey settings right"),
                ),
                'htmlOptions'=>array(
                    'empty'=>gT("No"),
                ),
                'help'=>$this->_translate('Need add response right.'),
658
                'current'=>$this->get('showSurveyAdminpageLink','Survey',$surveyId,$this->get('showAdminLink',null,null,$this->settings['showAdminLink']['default']) ? 'admin': null)
659
            ),
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
            'showExportLink' => array(
                'type'=>'select',
                'label'=>$this->_translate('Show export for checked response'),
                'options'=>array(
                    'limesurvey'=>$this->_translate("Only for LimeSurvey administrator"),
                    'all'=>gT("Yes"),
                ),
                'current'=>$this->get('showExportLink','Survey',$surveyId,$this->get('showExportLink',null,null,'limesurvey')),
            ),
            'exportType' => array(
                'type' => 'select',
                'label'=>$this->_translate('Export type'),
                'options'=>$exportList,
                'htmlOptions'=>array(
                    'empty'=>gT("None"),
                ),
                'current'=>$this->get('exportType','Survey',$surveyId),
            ),
            'exportHeadexports' => array(
                'type' => 'select',
                'label'=>$this->_translate('Export questions as'),
                'options'=> array(
                    'code' => gT("Question code"),
                    'abbreviated' => gT("Abbreviated question text"),
                    'full' => gT("Full question text"),
                    'codetext' => gT("Question code & question text"),
                ),
                'current'=>$this->get('exportHeadexports','Survey',$surveyId,'full'),
            ),
            'exportAnswers' => array(
                'type' => 'select',
                'label'=>$this->_translate('Export responses as'),
                'options'=> array(
                    'short' => gT("Answer codes"),
                    'long' => gT("Full answers"),
                ),
                'current'=>$this->get('exportAnswers','Survey',$surveyId,'long'),
            ),
698
        );
699

700
        
701 702 703 704 705 706 707 708
        $aData['pluginClass']=get_class($this);
        $aData['surveyId']=$surveyId;
        $aData['title'] = "";
        $aData['warningString'] = null;
        $aData['aSettings']=$aSettings;
        $aData['assetUrl']=Yii::app()->assetManager->publish(dirname(__FILE__) . '/assets/settings');
        $content = $this->renderPartial('settings', $aData, true);
        return $content;
709
    }
710 711 712 713 714 715 716

    /**
     * Export response
     * @param int $surveyId Survey id
     * @param string|null $currenttoken token to be used for export : seems not sent currently (see LS issue)
     * @return mixed
     */
717
    public function _doExport($surveyId)
718 719 720 721 722 723 724 725
    {
        $currenttoken = Yii::app()->getRequest()->getParam('currenttoken');
        $userHaveRight = false;
        $settingAllowAccess = $this->get('showExportLink','Survey',$surveyId,'limesurvey');
        if(empty($settingAllowAccess)) {
            throw new CHttpException(403,$this->_translate("This action was not allowed"));
        }
        $exportType = $this->get('exportType','Survey',$surveyId);
726

727 728 729 730 731 732 733 734 735
        if(empty($exportType)) {
            throw new CHttpException(403,$this->_translate("This action was not allowed"));
        }
        if (Permission::model()->hasSurveyPermission($surveyId, 'responses', 'export')) {
            $userHaveRight = true;
        }
        if (!$userHaveRight && $settingAllowAccess == 'limesurvey') {
            throw new CHttpException(401,$this->_translate("This action was not allowed with your current rights."));
        }
736
        $oSurvey = \Survey::model()->findByPk($surveyId);
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
        if (!$userHaveRight && !$this->_allowTokenLink($oSurvey)) {
            throw new CHttpException(403,$this->_translate("This action was not allowed"));
        }
        if(!$userHaveRight && !$currenttoken) {
            throw new CHttpException(401,$this->_translate("This action was not allowed without a valid token."));
        }
        $checkeds = Yii::app()->getRequest()->getParam("checkeds","");
        $aFilters = array();
        $aChecked = explode(",",$checkeds);
        $aChecked = array_filter($aChecked,  function($id) {
            return ctype_digit($id) || is_int($id);
        });
        if(!empty($aChecked)) {
            $aFilters[] = " id IN (".implode(",",$aChecked).")";
        }
        if($currenttoken) {
            $aTokens = $this->_getTokensList($surveyId,$currenttoken);
            $aTokens = array_map( function($token) {
                return Yii::app()->getDb()->quoteValue($token);
            },$aTokens);
        }
        if(!empty($aTokens)) {
            $aFilters[] = ' {{survey_' . $surveyId . '}}.token IN ('.implode(",",$aTokens).')';
        }
        $sFilter = implode(" AND ",$aFilters);

        /* language … */
        $language = Survey::model()->findByPk($surveyId)->language;
        /* columns : add an option */
        $survey = \Survey::model()->findByPk($surveyId);
        if(intval(Yii::app()->getConfig('versionnumber')) < 3) {
            $survey = $surveyId;
        }
        $aFields=array_keys(createFieldMap($survey,'full',true,false,$language));
        
        Yii::app()->loadHelper('admin/exportresults');
        Yii::import('application.helpers.viewHelper');
        $oExport=new \ExportSurveyResultsService();
        $exports = $oExport->getExports();
        $oFormattingOptions=new \FormattingOptions();
        $oFormattingOptions->responseMinRecord = 1;
        $oFormattingOptions->responseMaxRecord = SurveyDynamic::model($surveyId)->getMaxId();
        $oFormattingOptions->selectedColumns=$aFields;
        $oFormattingOptions->responseCompletionState = 'all';
        $oFormattingOptions->headingFormat = $this->get('exportHeadexports','Survey',$surveyId,'full');
        $oFormattingOptions->answerFormat = $this->get('exportAnswers','Survey',$surveyId,'long');
        $oFormattingOptions->output='display';
        /* Hack action id to set to remotecontrol */
        $action = new stdClass();
        $action->id='remotecontrol';
        Yii::app()->controller->__set('action',$action);
        /* Export as display */
        //viewHelper::disableHtmlLogging();
        $oExport->exportSurvey($surveyId,$language, $exportType,$oFormattingOptions, $sFilter);
        exit;
    }
793 794 795 796 797
    /**
    * @see newSurveySettings
    */
    public function newSurveySettings()
    {
Chenu Denis's avatar
Chenu Denis committed
798 799 800
        if(!$this->_isUsable()) {
            return;
        }
801 802 803 804 805 806 807 808 809
        $event = $this->event;
        foreach ($event->get('settings') as $name => $value) {
            $this->set($name, $value, 'Survey', $event->get('survey'));
        }
    }

    /** @inheritdoc **/
    public function newDirectRequest()
    {
810
        if($this->getEvent()->get('target') != get_class($this)) {
Chenu Denis's avatar
Chenu Denis committed
811 812
            return;
        }
813 814
        if(!$this->_isUsable()) {
            // throw error ?
815 816 817
            return;
        }
        $this->_setConfig();
818
        $surveyId = App()->getRequest()->getQuery('sid',App()->getRequest()->getQuery('surveyid'));
819 820 821 822
        if(App()->getRequest()->getQuery('logout') ) {
            $this->_doLogout($surveyId);
            App()->end(); // Not needed but more clear
        }
823
        if($surveyId && App()->getRequest()->getQuery('delete') ) {
824 825 826
            $this->_deleteResponseSurvey($surveyId,App()->getRequest()->getQuery('delete'));
            App()->end(); // Not needed but more clear
        }
827 828 829 830
        if($surveyId && App()->getRequest()->getQuery('action')=='adduser' ) {
            $this->_addUserForSurvey($surveyId);
            App()->end(); // Not needed but more clear
        }
831 832 833 834
        if($surveyId && App()->getRequest()->getQuery('action')=='download' ) {
            $this->_downloadFile($surveyId);
            App()->end(); // Not needed but more clear
        }
835 836 837 838
        if($surveyId && App()->getRequest()->getQuery('action')=='export' ) {
            $this->_doExport($surveyId);
            App()->end(); // Not needed but more clear
        }
839 840 841 842 843 844 845
        if($surveyId) {
            $this->_doSurvey($surveyId);
            App()->end(); // Not needed but more clear
        }
        $this->_doListSurveys();
    }

846 847 848 849 850 851 852 853 854 855 856 857
    /**
     * Download a file by manager
     */
    private function _downloadFile($surveyId) {
        $srid = Yii::app()->getRequest()->getParam('srid');
        $qid = Yii::app()->getRequest()->getParam('qid');
        $fileIndex = Yii::app()->getRequest()->getParam('fileindex');
        $oSurvey = Survey::model()->findByPk($surveyId);
        $oResponse = Response::model($surveyId)->findByPk($srid);
        if(!$oResponse) {
            throw new CHttpException(404);
        }
858 859
        if (!Permission::model()->hasSurveyPermission($surveyId, 'responses', 'read')) {
            if(!$this->_allowTokenLink($oSurvey)) {
860 861 862 863 864 865 866 867 868 869
                throw new CHttpException(403);
            }
            $currentToken = $this->_getCurrentToken($surveyId);
            if($currentToken) {
                throw new CHttpException(403);
            }
            if($currentToken != $oResponse->token) {
                throw new CHttpException(403);
            }
        }
870
        
871 872 873 874 875 876 877 878 879 880 881 882 883
        $aQuestionFiles = $oResponse->getFiles($qid);
        if (empty($aQuestionFiles[$fileIndex])) {
            throw new CHttpException(404,gT("Sorry, this file was not found."));
        }
        $aFile = $aQuestionFiles[$fileIndex];
        $sFileRealName = Yii::app()->getConfig('uploaddir')."/surveys/".$surveyId."/files/".$aFile['filename'];
        if(!file_exists($sFileRealName)) {
            throw new CHttpException(404,gT("Sorry, this file was not found."));
        }
        $mimeType = CFileHelper::getMimeType($sFileRealName, null, false);
        if (is_null($mimeType)) {
            $mimeType = "application/octet-stream";
        }
884 885 886 887
        $shownInline = false;
        if( !$this->get('forceDownloadImage',null,null,$this->settings['forceDownloadImage']['default']) && in_array($mimeType,array("image/gif","image/jpeg","image/pjpeg","image/png","application/pdf")) ) {
            $shownInline = true;
        }
888
        @ob_clean();
889 890 891
        if(!$shownInline) {
            header('Content-Description: File Transfer');
        }
892
        header('Content-Type: '.$mimeType);
893 894 895 896 897
        if(!$shownInline) {
            header('Content-Disposition: attachment; filename="'.sanitize_filename(rawurldecode($aFile['name'])).'"');
        } else {
            header('Content-Disposition: inline; filename="'.sanitize_filename(rawurldecode($aFile['name'])).'"');
        }
898 899 900 901 902 903
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: '.filesize($sFileRealName));
        readfile($sFileRealName);
904
        Yii::app()->end();
905
    }
906 907 908 909 910
    /**
     * Managing access to survey
     */
    private function _doSurvey($surveyId)
    {
911
        $this->aRenderData['surveyId'] = $surveyId;
912 913 914 915
        Yii::import('application.helpers.viewHelper');
        $oSurvey=Survey::model()->findByPk($surveyId);
        /* Must fix rights */
        $userHaveRight = false;
916 917 918 919
        $settingAllowAccess = $this->get('allowAccess','Survey',$surveyId,'all');
        if(empty($settingAllowAccess)) {
            throw new CHttpException(403);
        }
920
        if (Permission::model()->hasSurveyPermission($surveyId, 'responses', 'read')) {
Chenu Denis's avatar
Chenu Denis committed
921 922
            if(App()->getRequest()->isPostRequest && App()->getRequest()->getPost('login_submit')) {
                /* redirect to avoid CRSF when reload */
923
                Yii::app()->getController()->redirect(array("plugins/direct", 'plugin' => get_class(),'sid'=>$surveyId));
Chenu Denis's avatar
Chenu Denis committed
924
            }
925 926
            $userHaveRight = true;
        }
927 928 929
        if (!$userHaveRight && $settingAllowAccess == 'limesurvey') {
            $this->_doLogin();
        }
930
        if (!$userHaveRight && !$this->_allowTokenLink($oSurvey)) {
931 932 933
            $this->_doLogin();
        }
        if(!$userHaveRight && App()->getRequest()->getPost('token')) {
934 935 936 937 938 939 940 941 942 943 944
            $currentToken = App()->getRequest()->getPost('token');
            $oToken = Token::model($surveyId)->findByToken($currentToken);
            if($oToken) {
                $this->_setCurrentToken($surveyId,$currentToken);
                /* redirect to avoid CRSF when reload */
                Yii::app()->getController()->redirect(array("plugins/direct", 'plugin' => get_class(),'sid'=>$surveyId));
            } else {
                $this->aRenderData['error'] = $this->_translate("This code is invalid.");
            }
        }
        $currentToken = $this->_getCurrentToken($surveyId);
945
        if(!$userHaveRight && $currentToken) {
946
            $userHaveRight = true;
947 948
            $this->_setCurrentToken($surveyId,$currentToken);
            Yii::app()->user->setState('disableTokenPermission',true);
949
        }
950
        
951
        if(!$userHaveRight) {
952
            if($this->_allowTokenLink($oSurvey) && !Yii::app()->getRequest()->getParam('admin')) {
953 954 955
                $this->_showTokenForm($surveyId);
            } else {
                $this->_doLogin();
956
                //throw new CHttpException(401,$this->_translate("Sorry, no access on this survey."));
957 958 959 960 961 962
            }
        }
        $oSurvey = Survey::model()->findByPk($surveyId);
        $language = App()->getlanguage();
        if(!in_array($language,$oSurvey->getAllLanguages())) {
            $language = $oSurvey->language;
963
            App()->setLanguage($language);
964
        }
965
        $this->aRenderData['aSurveyInfo'] = getSurveyInfo($surveyId, $language);
966 967 968 969 970 971 972
        /* See https://github.com/LimeSurvey/LimeSurvey/commit/0ffc127bfceac4aa7658595b624ac18a2dcce2aa */
        if(Yii::app()->getConfig('debug') && version_compare(Yii::app()->getConfig('versionnumber'),"3.14.8","<=") && version_compare(Yii::app()->getConfig('versionnumber'),"3.0.0",">=")) {
            $sessionSurvey = array(
                "s_lang" => $language
            );
            Yii::app()->session['survey_'.$surveyId] = $sessionSurvey;
        }
973 974 975 976
        Yii::app()->session['responseListAndManage'] = $surveyId;
        Yii::import(get_class($this).'.models.ResponseExtended');
        $mResponse = ResponseExtended::model($surveyId);
        $mResponse->setScenario('search');
977
        $mResponse->showFooter = $this->get('showFooter','Survey',$surveyId,false);
978
        $mResponse->filterOnDate = (bool) $this->get('filterOnDate','Survey',$surveyId,true);
979 980 981 982
        $mResponse->filterSubmitDate = (int) $this->get('filterSubmitDate','Survey',$surveyId,0);
        $mResponse->filterStartdate = (int) $this->get('filterStartdate','Survey',$surveyId,0);
        $mResponse->filterDatestamp = (int) $this->get('filterDatestamp','Survey',$surveyId,0);

983 984 985 986 987 988 989
        $filters = Yii::app()->request->getParam('ResponseExtended');
        if (!empty($filters)) {
            $mResponse->setAttributes($filters, false);
            if(!empty($filters['completed'])) {
                $mResponse->setAttribute('completed', $filters['completed']);
            }
        }
990 991 992 993
        $tokensFilter = Yii::app()->request->getParam('TokenDynamic');
        if (!empty($tokensFilter)) {
            $mResponse->setTokenAttributes($tokensFilter);
        }
994 995 996 997
        /* Access with token */
        $isManager = false;
        $tokenAttributeGroup = $this->get('tokenAttributeGroup','Survey',$surveyId);
        $tokenAttributeGroupManager = $this->get('tokenAttributeGroupManager','Survey',$surveyId);
998

999
        /* Get the final allowed according to current token) */
1000 1001
        $allowAccess = $allowSee = $allowEdit = $allowDelete = $allowAdd = false;
        $settingAllowAccess = $this->get('allowAccess','Survey',$surveyId,'all');
1002 1003 1004 1005
        $settingAllowSee = $this->get('allowSee','Survey',$surveyId,'all');
        $settingAllowEdit = $this->get('allowEdit','Survey',$surveyId,'admin');
        $settingAllowDelete = $this->get('allowDelete','Survey',$surveyId,'admin');
        $settingAllowAdd = $this->get('allowAdd','Survey',$surveyId,'admin');
1006 1007
        $settingAllowAddUser = $this->get('allowAddUser','Survey',$surveyId,'admin');

1008 1009 1010 1011 1012
        $tokenAttributeGroup = $this->get('tokenAttributeGroup','Survey',$surveyId,null);
        $tokenAttributeGroupManager = $this->get('tokenAttributeGroupManager','Survey',$surveyId,null);
        $tokenGroup = null;
        $tokenAdmin = null;
        $isManager = false;
1013
        /* Set the default according to Permission */
1014
        if(empty($currentToken) && $this->_isLsAdmin()) {
1015 1016 1017 1018 1019 1020 1021
            $allowAccess = Permission::model()->hasSurveyPermission($surveyId, 'responses', 'read');
            if($this->_surveyHasTokens($oSurvey)) {
                $allowAccess = $settingAllowAccess && Permission::model()->hasSurveyPermission($surveyId, 'token', 'read');
            }
            $allowSee = $allowAccess && $settingAllowSee && Permission::model()->hasSurveyPermission($surveyId, 'responses', 'read');
            $allowEdit = $allowSee && $settingAllowEdit && Permission::model()->hasSurveyPermission($surveyId, 'responses', 'update');
            $allowDelete = $allowSee && $settingAllowDelete && Permission::model()->hasSurveyPermission($surveyId, 'responses', 'delete');
1022
            $allowAdd = $settingAllowAdd && Permission::model()->hasSurveyPermission($surveyId, 'responses', 'create');
1023
            $allowAddUser = $this->_allowTokenLink($oSurvey) && $settingAllowAddUser && Permission::model()->hasSurveyPermission($surveyId, 'token', 'create');
1024
        }
1025
        if($currentToken) {
1026 1027
            $aTokens = (array) $currentToken;
            $oToken = Token::model($surveyId)->findByToken($currentToken);
1028 1029
            $tokenGroup = (!empty($tokenAttributeGroup) && !empty($oToken->$tokenAttributeGroup)) ? $oToken->$tokenAttributeGroup : null;
            $tokenAdmin = (!empty($tokenAttributeGroupManager) && !empty($oToken->$tokenAttributeGroupManager)) ? $oToken->$tokenAttributeGroupManager : null;
1030
            $isManager = ((bool) $tokenAdmin) && trim($tokenAdmin) !== '0';
1031
            $allowAccess = ($settingAllowAccess == 'all') || ($settingAllowAccess == 'admin' && $isManager);
1032 1033 1034
            $allowSee = ($settingAllowSee == 'all') || ($settingAllowSee == 'admin' && $isManager);
            $allowEdit = $allowSee && (($settingAllowEdit == 'all') || ($settingAllowEdit == 'admin' && $isManager));
            $allowDelete = ($settingAllowDelete == 'all') || ($settingAllowDelete == 'admin' && $isManager);
1035
            $allowAdd = ($settingAllowAdd == 'all') || ($settingAllowAdd == 'admin' && $isManager); // all add with any token (show token list)
1036
            $allowAddUser = $this->_allowTokenLink($oSurvey) && ( ($settingAllowAddUser == 'all') || ($settingAllowAddUser == 'admin' && $isManager));
1037
            $oTokenGroup = Token::model($surveyId)->findAll("token = :token",array(":token"=>$currentToken));
1038
            if($tokenGroup) {
1039
                $oTokenGroup = Token::model($surveyId)->findAll($tokenAttributeGroup."= :group",array(":group"=>$tokenGroup));
1040
                if($allowSee) {
1041 1042 1043 1044
                    $aTokens = CHtml::listData($oTokenGroup,'token','token');
                }
            }
            $mResponse->setAttribute('token', $aTokens);
1045

1046
            if(!$allowAccess && Permission::model()->hasSurveyPermission($surveyId, 'responses', 'read')) {
1047 1048
                throw new CHttpException(403, $this->_translate('You are not allowed to use reponse management with this token.'));
            }
1049
        }
1050
        Yii::app()->user->setState('responseListAndManagePageSize',intval(Yii::app()->request->getParam('pageSize',Yii::app()->user->getState('responseListAndManagePageSize',50))));
1051 1052 1053 1054 1055 1056
        // Check if allow check
        $selectableRows = 0;
        if($this->get('exportType','Survey',$surveyId) && $this->get('showExportLink','Survey',$surveyId,$this->get('showExportLink',null,null,'limesurvey'))) {
            if(Permission::model()->hasSurveyPermission($surveyId, 'response', 'export')) {
                $selectableRows = 2;
            }
1057
            if($selectableRows == 0 && $currentToken && $this->get('showExportLink','Survey',$surveyId) == 'all') {
1058 1059 1060 1061
                $selectableRows = 2;
            }
        }

1062 1063
        /* Add a new */
        $tokenList = null;
1064
        $singleToken = null;
1065
        if($this->_allowTokenLink($oSurvey)) {
1066
            if(Permission::model()->hasSurveyPermission($surveyId, 'responses', 'create')) {
1067 1068 1069 1070 1071
                if($this->_allowMultipleResponse($oSurvey)) {
                    $oToken = Token::model($surveyId)->findAll("token is not null and token <> ''");
                } else {
                    $oToken = Token::model($surveyId)->with('responses')->findAll("t.token is not null and t.token <> '' and responses.id is null");
                }
1072 1073 1074
                if(count($oToken) == 1) {
                    $singleToken = $oToken[0]->token;
                }
1075
                $tokenList = CHtml::listData($oToken,'token',function($oToken){
1076 1077 1078 1079 1080
                    return CHtml::encode(trim($oToken->firstname.' '.$oToken->lastname.' ('.$oToken->token.')'));
                },
                $tokenAttributeGroup);
            }
            if($currentToken) {
1081 1082 1083
                if(is_array($currentToken)) {
                    $currentToken = array_shift(array_values($currentToken));
                }
1084
                $tokenList = array($currentToken=>$currentToken);
1085 1086 1087
                if($allowAdd) { /* Adding for all group */
                    $criteria = new CDbCriteria();
                    if($this->_allowMultipleResponse($oSurvey)) {
1088
                        $criteria->condition = "t.token is not null and t.token <> ''";
1089 1090 1091 1092 1093
                    } else {
                        $criteria->condition = "t.token is not null and t.token <> '' and responses.id is null";
                    }
                    $criteria->addInCondition('t.token',$aTokens);
                    $oToken = Token::model($surveyId)->with('responses')->findAll($criteria);
1094 1095 1096
                    if(count($oToken) == 1) {
                        $singleToken = $oToken[0]->token;
                    }
1097 1098 1099 1100 1101 1102
                    $tokenList = CHtml::listData($oTokenGroup,'token',function($oToken){
                        return CHtml::encode(trim($oToken->firstname.' '.$oToken->lastname.' ('.$oToken->token.')'));
                    },
                    $tokenAttributeGroup);
                }
            }
1103 1104 1105 1106 1107
            if(!empty($tokenList) && !empty($tokenList[''])) {
                $emptyTokenGroup = $tokenList[''];
                unset($tokenList['']);
                $tokenList = array_merge($emptyTokenGroup,$tokenList);
            }
1108
        }
1109

1110
        $adminAction = $this->_getAdminMenu($surveyId);
1111 1112
        $this->aRenderData['adminAction'] = empty($adminAction) ? "" : $adminAction." ";;

1113
        $addNew ='';
1114
        if(Permission::model()->hasSurveyPermission($surveyId, 'responses', 'create') && !$this->_surveyHasTokens($oSurvey)) {
1115
            $addNew = CHtml::link("<i class='fa fa-plus-circle' aria-hidden='true'></i> ".$this->_translate("Create an new response"),
1116
                array("survey/index",'sid'=>$surveyId,'newtest'=>"Y"),
1117
                array('class'=>'btn btn-default btn-sm  addnew')
1118 1119
            );
        }
1120
        if($allowAdd && $singleToken) {
1121
            if($this->_allowMultipleResponse($oSurvey)) {
1122
                $addNew = CHtml::link("<i class='fa fa-plus-circle' aria-hidden='true'></i> ".$this->_translate("Create an new response"),
1123
                    array("survey/index",'sid'=>$surveyId,'newtest'=>"Y",'srid'=>'new','token'=>$singleToken),
1124 1125 1126
                    array('class'=>'btn btn-default btn-sm addnew')
                );
            }
1127
        }
1128
        if(!$allowAdd && $currentToken) {
1129
            if($this->get('allowAddSelf','Survey',$surveyId,true) && $this->_allowMultipleResponse($oSurvey)) {
1130
                $addNew = CHtml::link("<i class='fa fa-plus-circle' aria-hidden='true'></i> ".$this->_translate("Create an new response"),
1131
                    array("survey/index",'sid'=>$surveyId,'newtest'=>"Y",'srid'=>'new','token'=>$currentToken),
1132 1133 1134 1135
                    array('class'=>'btn btn-default btn-sm addnew')
                );
            }
        }
1136
        if($allowAdd && !empty($tokenList) && !$singleToken) {
1137 1138 1139
            $addNew  = CHtml::beginForm(array("survey/index"),'get',array('class'=>"form-inline"));
            $addNew .= CHtml::hiddenField('sid',$surveyId);
            $addNew .= CHtml::hiddenField('newtest',"Y");
1140 1141
            //~ $addNew .= '<div class="form-group"><div class="input-group">';
            $addNew .= CHtml::dropDownList('token',$currentToken,$tokenList,array('class'=>'form-control input-sm','empty'=>gT("Please choose...")));
1142
            $addNew .= CHtml::htmlButton("<i class='fa fa-plus-circle' aria-hidden='true'></i> ".$this->_translate("Create an new response"),
1143 1144 1145 1146
                array("type"=>'button','name'=>'srid','value'=>'new','class'=>'btn btn-default btn-sm addnew')
            );
            //~ $addNew .= '</div></div>';

1147 1148
            $addNew .= CHtml::endForm();
        }
1149

1150
        $this->aRenderData['addNew'] = empty($addNew) ? "" : $addNew." ";;
1151 1152
        /* Contruct column */
        /* Put the button here, more easy */
1153 1154 1155 1156
        $updateButtonUrl = "";
        if(Permission::model()->hasSurveyPermission($surveyId, 'responses', 'update')) {
            $updateButtonUrl = 'App()->createUrl("survey/index",array("sid"=>'.$surveyId.',"srid"=>$data["id"],"newtest"=>"Y"))';
        }
1157
        if($this->_allowTokenLink($oSurvey)) {
1158 1159
            $updateButtonUrl = 'App()->createUrl("survey/index",array("sid"=>'.$surveyId.',"srid"=>$data["id"],"newtest"=>"Y"))';
            if($currentToken) {
1160
                if( $allowEdit ) {
1161
                    $updateButtonUrl = 'App()->createUrl("survey/index",array("sid"=>'.$surveyId.',"token"=>"'.$currentToken.'","srid"=>$data["id"],"newtest"=>"Y"))';
1162
                } elseif($settingAllowEdit) {
1163
                    $updateButtonUrl = '("'.$currentToken.'" == $data["token"]) ? App()->createUrl("survey/index",array("sid"=>'.$surveyId.',"token"=>"'.$currentToken.'","srid"=>$data["id"],"newtest"=>"Y")) : null';
1164 1165
                } else {
                    $updateButtonUrl = '';
1166 1167 1168 1169 1170 1171
                }
            }
        }
        $deleteButtonUrl = "";
        if(Permission::model()->hasSurveyPermission($surveyId, 'responses', 'delete')) {
            $deleteButtonUrl = 'App()->createUrl("plugins/direct",array("plugin"=>"'.get_class().'","sid"=>'.$surveyId.',"delete"=>$data["id"]))';
1172
        }
1173
        if($this->_allowTokenLink($oSurvey) && $oSurvey->anonymized != 'Y') {
1174
            $deleteButtonUrl = 'App()->createUrl("plugins/direct",array("plugin"=>"'.get_class().'","sid"=>'.$surveyId.',"token"=>$data["token"],"delete"=>$data["id"]))';
1175
            if($currentToken) {
1176
                if( $allowDelete ) {
1177
                    $deleteButtonUrl = 'App()->createUrl("plugins/direct",array("plugin"=>"'.get_class().'","sid"=>'.$surveyId.',"token"=>$data["token"],"delete"=>$data["id"]))';
1178
                } elseif($settingAllowDelete) {
1179
                    $deleteButtonUrl = '("'.$currentToken.'" == $data["token"]) ? App()->createUrl("plugins/direct",array("plugin"=>"'.get_class().'","sid"=>'.$surveyId.',"token"=>$data["token"],"delete"=>$data["id"])) : null';
1180 1181
                } else {
                    $deleteButtonUrl = "";
1182 1183
                }
            }
1184
        }
1185 1186

        $aColumns = array();
1187
        $disableTokenPermission = (bool) $currentToken;
1188 1189 1190
        /* Get the selected columns only */
        $tokenAttributes = $this->get('tokenAttributes','Survey',$surveyId);
        $surveyAttributes = $this->get('surveyAttributes','Survey',$surveyId);
1191
        $surveyAttributesPrimary = $this->get('surveyAttributesPrimary','Survey',$surveyId);
1192
        $filteredArr = array();
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
        $aRestrictedColumns = array();
        if(empty($tokenAttributes)) {
            $tokenAttributes = array_keys($this->_getTokensAttributeList($surveyId,'tokens.'));
        }
        /* remove tokens.token if user didn't have right to edit */
        if($currentToken && !$allowEdit) {
            /* unset by value */
            $tokenAttributes = array_values(array_diff($tokenAttributes, array('tokens.token')));
        }
        if(empty($surveyAttributes)) {
            $surveyAttributes = \getQuestionInformation\helpers\surveyColumnsInformation::getAllQuestionListData($surveyId,App()->getLanguage());
            $surveyAttributes = array_keys($surveyAttributes['data']);
        }
1206 1207 1208 1209 1210 1211 1212 1213 1214
        if(is_string($surveyAttributes)) {
            $surveyAttributes = array($surveyAttributes);
        }
        if(empty($surveyAttributesPrimary)) {
            $surveyAttributesPrimary = array();
        }
        if(is_string($surveyAttributesPrimary)) {
            $surveyAttributesPrimary = array($surveyAttributesPrimary);
        }
1215 1216 1217 1218
        if(!empty($surveyAttributesPrimary)) {
            $surveyAttributes = array_diff ($surveyAttributes,$surveyAttributesPrimary);
        }
        $baseColumns = array();
1219
        if($this->get('showId','Survey',$surveyId,1)) {
1220
            $baseColumns[] = 'id';
1221 1222
        }
        if($this->get('showCompleted','Survey',$surveyId,1)) {
1223
            $baseColumns[] = 'completed';
1224 1225
        }
        if($oSurvey->datestamp && $this->get('showStartdate','Survey',$surveyId,0)) {
1226
            $baseColumns[] = 'startdate';
1227
        }
1228 1229 1230
        if($oSurvey->datestamp && $this->get('showSubmitDate','Survey',$surveyId,0)) {
            $baseColumns[] = 'submitdate';
        }
1231
        if($oSurvey->datestamp && $this->get('showDatestamp','Survey',$surveyId,0)) {
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
            $baseColumns[] = 'datestamp';
        }
        $aRestrictedColumns = array_merge($baseColumns,$tokenAttributes,$surveyAttributes,$surveyAttributesPrimary);
        switch ($this->get('tokenColumnOrder','Survey',$surveyId,'default')) {
            case "start":
                $aRestrictedColumns = array_merge($baseColumns,$tokenAttributes,$surveyAttributesPrimary,$surveyAttributes);
                break;
            case "end":
                $aRestrictedColumns = array_merge($baseColumns,$surveyAttributesPrimary,$surveyAttributes,$tokenAttributes);
                break;
            case "default":
            default:
                $aRestrictedColumns = array_merge($baseColumns,$surveyAttributesPrimary,$tokenAttributes,$surveyAttributes);
1245
        }
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
        if($currentToken) {
            $tokenAttributesHideToUser = $this->get('tokenAttributesHideToUser','Survey',$surveyId);
            if(!empty($tokenAttributesHideToUser)) {
                $aRestrictedColumns = array_diff($aRestrictedColumns,$tokenAttributesHideToUser);
            }
            $surveyAttributesHideToUser = $this->get('surveyAttributesHideToUser','Survey',$surveyId);
            if(!empty($surveyAttributesHideToUser)) {
                $aRestrictedColumns = array_diff($aRestrictedColumns,$surveyAttributesHideToUser);
            }
        }
1256 1257 1258
        $mResponse->setRestrictedColumns($aRestrictedColumns);
        $aColumns = $mResponse->getGridColumns($disableTokenPermission);
        /* Get columns by order now … */
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
        $aOrderedColumn = array();
        if($selectableRows) {
            $aOrderedColumn['selected'] = array(
                'class'=>'CCheckBoxColumn',
            );
        }
        $aOrderedColumn['button'] = array(
            'htmlOptions' => array('nowrap'=>'nowrap'),
            'class'=>'bootstrap.widgets.TbButtonColumn',
            'template'=>'{update}{delete}',
            'updateButtonUrl'=>$updateButtonUrl,
            'deleteButtonUrl'=>$deleteButtonUrl,
            'footer' => ($this->get('showFooter','Survey',$surveyId,false) ? $this->_translate("Answered count and sum") : null),
1272 1273 1274 1275
        );
        foreach($aRestrictedColumns as $key) {
            if(isset($aColumns[$key])) {
                $aOrderedColumn[$key] = $aColumns[$key];
1276 1277
            }
        }
1278
        $this->aRenderData['allowAddUser'] = $allowAddUser;
Chenu Denis's avatar
Chenu Denis committed
1279 1280
        $this->aRenderData['addUser'] = array();
        $this->aRenderData['addUserButton'] = '';
1281
        if($allowAddUser) {
Chenu Denis's avatar
Chenu Denis committed
1282
            $this->aRenderData['addUserButton'] = CHtml::htmlButton("<i class='fa fa-user-plus ' aria-hidden='true'></i>".$this->_translate("Create an new user"),
1283
                array("type"=>'button','name'=>'adduser','value'=>'new','class'=>'btn btn-default btn-sm addnewuser')
Chenu Denis's avatar
Chenu Denis committed
1284
            );
1285
            $this->aRenderData['addUser'] = $this->_addUserDataForm($surveyId,$currentToken);
1286
        }
1287 1288 1289
        if(empty($this->aRenderData['lang'])) {
            $this->aRenderData['lang'] = array();
        }
1290
        $this->aRenderData['lang']['Close'] = gT("Close");
1291 1292
        //$this->aRenderData['lang']['Delete'] = $this->_translate("Delete");
        if($oSurvey->allowprev == "Y") {
Chenu Denis's avatar
Chenu Denis committed
1293
            $this->aRenderData['lang']['Previous'] = gT("Previous");
1294 1295
        }
        if($oSurvey->allowsave == "Y") { // We don't need to test token, we don't shown default save part …
Chenu Denis's avatar
Chenu Denis committed
1296
            $this->aRenderData['lang']['Save'] = gT("Save");
1297 1298
        }
        if($oSurvey->format!="A") {
Chenu Denis's avatar
Chenu Denis committed
1299
            $this->aRenderData['lang']['Next'] = gT("Next");
1300
        }
Chenu Denis's avatar
Chenu Denis committed
1301
        $this->aRenderData['lang']['Submit'] = gT("Submit");
1302
        $this->aRenderData['model'] = $mResponse;
1303 1304
        // Add comment block
        $aDescriptionCurrent = $this->get('description','Survey',$surveyId);
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
        $sDescriptionCurrent = isset($aDescriptionCurrent[Yii::app()->getLanguage()]) ? $aDescriptionCurrent[Yii::app()->getLanguage()] : "";
        $aReplacement = array(
            'SID' => $surveyId,
            'TOKEN' => $currentToken,
        );
        if(version_compare(App()->getConfig("versionnumber"),"3","<") ) {
            $sDescriptionCurrent = LimeExpressionManager::ProcessString($sDescriptionCurrent,null,$aReplacement);
        } else {
            $sDescriptionCurrent = LimeExpressionManager::ProcessString($sDescriptionCurrent,null,$aReplacement);
        }
1315 1316

        $this->aRenderData['selectableRows'] = $selectableRows;
1317
        $this->aRenderData['description'] = $sDescriptionCurrent;
1318
        $this->aRenderData['columns'] = $aOrderedColumn;
1319 1320 1321 1322 1323 1324
        $this->_render('responses');
    }

    private function _deleteResponseSurvey($surveyId,$srid)
    {
        $oSurvey = Survey::model()->findByPk($surveyId);
1325 1326 1327 1328 1329 1330 1331
        if(!$oSurvey) {
            throw new CHttpException(404, $this->_translate("Invalid survey id."));
        }
        $oResponse = Response::model($surveyId)->findByPk($srid);
        if(!$oResponse) {
            throw new CHttpException(404, $this->_translate("Invalid response id."));
        }
1332 1333
        //echo "Work in progress";
        $allowed = false;
1334
        /* Is an admin */
1335 1336 1337
        if($this->get('allowDelete','Survey',$surveyId,'admin') && Permission::model()->hasSurveyPermission($surveyId, 'response', 'delete')) {
            $allowed = true;
        }
1338
        /* Is not an admin */
1339
        if(!$allowed && $this->get('allowDelete','Survey',$surveyId,'admin') && $this->_surveyHasTokens($oSurvey)) {
1340
            $whoIsAllowed = $this->get('allowDelete','Survey',$surveyId,'admin');
1341
            $token = App()->getRequest()->getQuery('token');
1342 1343 1344 1345 1346 1347 1348 1349 1350
            $tokenAttributeGroup = $this->get('tokenAttributeGroup','Survey',$surveyId,null);
            $tokenAttributeGroupManager = $this->get('tokenAttributeGroupManager','Survey',$surveyId,null);
            $tokenGroup = null;
            $tokenAdmin = null;
            if($token && $this->_allowTokenLink($oSurvey)) {
                $oToken =  Token::model($surveyId)->findByToken($token);
                $tokenGroup = (!empty($tokenAttributeGroup) && !empty($oToken->$tokenAttributeGroup)) ? $oToken->$tokenAttributeGroup : null;
                $tokenAdmin = (!empty($tokenAttributeGroupManager) && !empty($oToken->$tokenAttributeGroupManager)) ? $oToken->$tokenAttributeGroupManager