autoCommentIterativeQuestionnaire.php 90.7 KB
Newer Older
Chenu Denis's avatar
Chenu Denis committed
1 2
<?php
/**
3 4
 * autoCommentIterativeQuestionnaire Plugin for LimeSurvey
 * Creates automatic comment questions, and for iterative quesitonnaires, create a new questionnaire from a previous round questionnaire
Chenu Denis's avatar
Chenu Denis committed
5 6
 *
 * @author Denis Chenu <denis@sondages.pro>
7 8
 * @copyright 2014-2018 Denis Chenu <http://sondages.pro>
 * @copyright 2014-2018 Belgian Health Care Knowledge Centre (KCE) <http://kce.fgov.be>
9
 * @license AGPL v3
10
 * @version 3.1.2
Chenu Denis's avatar
Chenu Denis committed
11 12 13 14 15
 *
 * 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.
16
 *
Chenu Denis's avatar
Chenu Denis committed
17 18 19 20 21 22
 * 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.
 *
 */
23
class autoCommentIterativeQuestionnaire extends PluginBase {
Chenu Denis's avatar
Chenu Denis committed
24 25

    protected $storage = 'DbStorage';
26
    static protected $name = 'autoCommentIterativeQuestionnaire';
27
    static protected $description = 'Creates automatic comment questions, and for iterative quesitonnaires, create a new questionnaire from a previous round questionnaire - v3.0';
Chenu Denis's avatar
Chenu Denis committed
28 29 30 31 32 33

    private $iSurveyId=false;
    private $bSurveyActivated=false;
    private $sTableName="";
    private $sError="Unknow error.";
    private $sLanguage="";
34
    private $bUpdateHistory=false;
Chenu Denis's avatar
Chenu Denis committed
35
    private static $aValidQuestion=array("!","L","O");
36 37
    private static $aTextQuestion=array("S","T","U");

Chenu Denis's avatar
Chenu Denis committed
38
    private $oldSchema;
Chenu Denis's avatar
Chenu Denis committed
39
    private $aResult=array('success'=>array(),'warning'=>array(),'error'=>array());
Chenu Denis's avatar
Chenu Denis committed
40
    //~ private $validatescore,$scoreforyes,$scoreforno;
Chenu Denis's avatar
Chenu Denis committed
41 42

    private $aDelphiCodes=array(
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
        'hist'=>array(
            'questiontype'=>"X",
            'select'=>array(
                'label'=>"Display the question (text) from the previous round",
                'options'=>array(
                    'none'=>'No, do not display it',
                    'hide'=>'No, do not display it',
                    'create'=>"Yes, display it",
                    'update'=>"Yes, display it",
                    "show"=>"Yes, display it, but don’t update",
                ),
            ),
        ),
        'comm'=>array(
            'questiontype'=>"T",
            'create'=>  false,
            'select'=>array(
                    'label'=>"Comment question (automatic)",
                    'options'=>array(
                        'none'=>'No creation of this question',
                        'create'=>"Create question with default text (and Show it)",
                    ),
                ),
            'condition'=>"{QCODE}.valueNAOK< 0",
            'hidevalidate'=>false,
        ),
    );
Chenu Denis's avatar
Chenu Denis committed
70 71
    private $aLang=array(
            'hist'=>array(
Chenu Denis's avatar
Chenu Denis committed
72
                'view'=>"Show the history question",
Chenu Denis's avatar
Chenu Denis committed
73 74 75 76 77
                'createupdate'=>"Create an history question with actual question text",
                'update'=>"Update history with <strong>actual</strong> question text",
                ),
            'comm'=>array(
                'view'=>"Have a question for comment (Disagree)",
78
                'create'=>"Create a question to enter comment (automatic :assesment of question is under 0)",
Chenu Denis's avatar
Chenu Denis committed
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
                'createupdate'=>"Create a question to enter comment (when disagree : with condition : assesment of question is under 0 (score))",
                'update'=>"",
                ),
            'comh'=>array(
                'view'=>"Shown the comment for reason of disagree list",
                'create'=>"Create an empty question for reason of disagree list",
                'createupdate'=>"Create and update a question for reason of disagree list (only if question have comment)",
                'update'=>"Update the reason of disagree list",
                ),
            'cgd'=>array(
                'view'=>"Have a question for alternative comment (Agree)",
                'create'=>"Create a question to enter alternative comment (agree : with condition : assesment of question is upper 0 (score))",
                'createupdate'=>"Create a question to enter alternative comment (agree : with condition : assesment of question is upper 0 (score))",
                'update'=>"",
                ),
            'cgdh'=>array(
                'view'=>"Shown the comment for reason of agree list",
                'create'=>"Create an empty question for reason of agree list",
                'createupdate'=>"Create and update a question for reason of agree list (only if question have comment)",
                'update'=>"Update the reason of agree list",
                ),
            );
101 102

    /** @inheritdoc */
103 104
    public function init() {
        /* Basic settings */
Chenu Denis's avatar
Chenu Denis committed
105 106
        $this->subscribe('beforeSurveySettings');
        $this->subscribe('newSurveySettings');
107 108 109 110 111 112 113

        /* Add the link in menu */
        $this->subscribe('beforeToolsMenuRender');
        // Add the Question attribute for managing help to content
        $this->subscribe('newQuestionAttributes');
        $this->subscribe('beforeQuestionRender');

114 115
        // Update own var for language
        $this->_updateLanguageString();
116 117
    }

118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
    /* Update language string in var */
    private function _updateLanguageString()
    {
        $this->sError = $this->gT("Unknow error.");
        $this->aDelphiCodes=array_merge($this->aDelphiCodes, array(
            'hist'=>array(
                'select'=>array(
                    'label'=>$this->gT("Display the question (text) from the previous round"),
                    'options'=>array(
                        'none'=>$this->gT("No, do not display it"),
                        'hide'=>$this->gT("No, do not display it"),
                        'create'=>$this->gT("Yes, display it"),
                        'update'=>$this->gT("Yes, display it"),
                        'show'=>$this->gT("Yes, display it, but don’t update"),
                    ),
                ),
            ),
            'comm'=>array(
                'select'=>array(
                    'label'=>$this->gT("Comment question (automatic)"),
                    'options'=>array(
                        'none'=>$this->gT("No creation of this question"),
                        'create'=>$this->gT("Create question with default text (and Show it)"),
                    ),
                ),
            ),
        ));
        $this->aLang=array(
            'hist'=>array(
                'view'=>$this->gT("Show the history question"),
                'createupdate'=>$this->gT("Create an history question with actual question text"),
                'update'=>$this->gT("Update history with current question text"),
            ),
            'comm'=>array(
                'view'=>$this->gT("Have a question for comment (Disagree)"),
                'create'=>$this->gT("Create a question to enter comment (automatic :assesment of question is under 0)"),
                'createupdate'=>$this->gT("Create a question to enter comment (when disagree : with condition : assesment of question is under 0 (score))"),
                'update'=>"",
            ),
            'comh'=>array(
                'view'=>$this->gT("Shown the comment for reason of disagree list"),
                'create'=>$this->gT("Create an empty question for reason of disagree list"),
                'createupdate'=>$this->gT("Create and update a question for reason of disagree list (only if question have comment)"),
                'update'=>$this->gT("Update the reason of disagree list"),
            ),
            'cgd'=>array(
                'view'=>$this->gT("Have a question for alternative comment (Agree)"),
                'create'=>$this->gT("Create a question to enter alternative comment (agree : with condition : assesment of question is upper 0 (score))"),
                'createupdate'=>$this->gT("Create a question to enter alternative comment (agree : with condition : assesment of question is upper 0 (score))"),
                'update'=>"",
            ),
            'cgdh'=>array(
                'view'=>$this->gT("Shown the comment for reason of agree list"),
                'create'=>$this->gT("Create an empty question for reason of agree list"),
                'createupdate'=>$this->gT("Create and update a question for reason of agree list (only if question have comment)"),
                'update'=>$this->gT("Update the reason of agree list"),
            ),
        );
    }
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
    /** @inheritdoc */
    public function newQuestionAttributes() {
        $questionAttributes=array(
            'iterativeQuestion'=> array(
                'types' => "X",
                'category' => gT('Display'),
                'sortorder' => 200,
                'inputtype'=>'switch',
                'options'=>array(
                    0=>gT('No'),
                    1=>gT('Yes')
                ),
                'default'=>0,
                'caption' => $this->gT("Show help as history"),
                'help' => $this->gT("If you use iterative questionaire, this question help are shown as history. Automatically set by iterative questionaire."),
            ),
        );
        $this->getEvent()->append('questionAttributes', $questionAttributes);
    }

    /** @inheritdoc */
    public function beforeQuestionRender() {
        if($this->getEvent()->get('type') != "X") {
            return;
        }
        $oEvent = $this->getEvent();
        $isIterativeQuestion = QuestionAttribute::model()->find(
            "qid = :qid and attribute = :attribute",
            array(":qid"=>$oEvent->get('qid'),":attribute" => 'iterativeQuestion')
        );
        if(empty($isIterativeQuestion) || $isIterativeQuestion->value == 0) {
            return;
        }
        $historyId = "ciq-history-".$oEvent->get('qid');
        $questionText = $oEvent->get('text');
        $questionHelp = $oEvent->get('help');
        $oEvent->set('class',$oEvent->get('class').' aciq-history');
        $oEvent->set('help',"");
        $newText = CHtml::tag('div',array('class'=>"panel-heading"),
                        CHtml::tag('a',array('data-toggle'=>'collapse','href'=>"#".$historyId,'aria-expanded'=>"false",'aria-controls'=>$historyId),$questionText)
                    )
                 . CHtml::tag('div',array('class'=>"panel-collapse collapse",'id'=>$historyId,'aria-labelledby'=>$historyId),
                        CHtml::tag('div',array('class'=>'panel-body'),$questionHelp)
                    );
        $newText = CHtml::tag('div',array('class'=>"panel panel-default"),$newText);
        $oEvent->set('text',$newText);
223 224 225
        if(!Yii::app()->clientScript->hasPackage('autoCommentIterativeQuestionnaire')) {
            Yii::setPathOfAlias('autoCommentIterativeQuestionnaire',dirname(__FILE__));
            Yii::app()->clientScript->addPackage( 'autoCommentIterativeQuestionnaire', array(
226 227 228 229
                'basePath'    => 'autoCommentIterativeQuestionnaire.assets',
                'css'         => array('autoCommentIterativeQuestionnaire.css'),
                //~ 'js'          => array('questionExtraSurvey.js'),
            ));
230
            Yii::app()->getClientScript()->registerPackage('autoCommentIterativeQuestionnaire');
231 232 233 234 235
        }
    }

    /** Menu and settings part */

236
    /** @inheritdoc */
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
    public function beforeToolsMenuRender()
    {
        $event = $this->getEvent();
        $surveyId = $event->get('surveyId');
        if(!Permission::model()->hasSurveyPermission($surveyId, 'surveycontent', 'update')) {
            return;
        }
        // Did we have an old survey ?
        $aTables = App()->getApi()->getOldResponseTables($surveyId);
        if(count($aTables)>0) {
            $method = 'actionSelect';
        } else {
            $method = 'actionCheck';
        }
        $aMenuItem = array(
252
            'label' => $this->gT('Iteration'),
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
            'iconClass' => 'fa fa-refresh',
            'href' => Yii::app()->createUrl(
                'admin/pluginhelper',
                array(
                    'sa' => 'sidebody',
                    //~ 'href' => $url,
                    'plugin' => get_class($this),
                    'method' => $method,
                    '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));
Chenu Denis's avatar
Chenu Denis committed
271 272
    }

273
    /** @inheritdoc */
Chenu Denis's avatar
Chenu Denis committed
274 275 276 277 278
    public function beforeSurveySettings()
    {
        $oEvent = $this->event;
        $iSurveyId=$oEvent->get('survey');
        $oSurvey=Survey::model()->findByPk($iSurveyId);
279 280
        if(
          $oSurvey && $oSurvey->assessments=='Y'
Chenu Denis's avatar
Chenu Denis committed
281 282 283
          && Permission::model()->hasSurveyPermission($iSurveyId, 'surveycontent', 'update')
        )
        {
Chenu Denis's avatar
Chenu Denis committed
284
            $aSettings=array();
Chenu Denis's avatar
Chenu Denis committed
285 286 287 288

            // Setting for language
            $oSurvey=Survey::model()->findByPk($iSurveyId);
            $aLangs=$oSurvey->getAllLanguages();
Chenu Denis's avatar
Chenu Denis committed
289
            //$sScoreDefault=$this->get('validatescore', 'Survey', $oEvent->get('survey'),$this->get('validatescore',null,null,$this->settings['validatescore']['default']));
Chenu Denis's avatar
Chenu Denis committed
290 291 292 293
            foreach($aLangs as $sLang)
            {
                $aSettings["historytext_{$sLang}"]=array(
                    'type'=>'string',
294 295 296 297 298
                    'label'=>sprintf($this->gT("Sentence added before old proposal history (%s)"),$sLang),
                    'htmlOptions' => array(
                        'placeholder' => $this->gT('Previous proposal and result','html',$sLang)
                    ),
                    'current' => $this->get("historytext_{$sLang}", 'Survey', $oEvent->get('survey'),""),
Chenu Denis's avatar
Chenu Denis committed
299 300 301 302 303 304
                );
            }
            foreach($aLangs as $sLang)
            {
                $aSettings["commenttext_{$sLang}"]=array(
                    'type'=>'string',
305 306 307 308 309
                    'label'=>sprintf($this->gT("Sentence for the comments question show if user choose a answer with value less than 0 (%s)"),$sLang),
                    'htmlOptions' => array(
                        'placeholder' => $this->gT('Can you explain why you disagree with this proposal.','html',$sLang)
                    ),
                    'current' => $this->get("commenttext_{$sLang}", 'Survey', ""),
Chenu Denis's avatar
Chenu Denis committed
310 311
                );
            }
Chenu Denis's avatar
Chenu Denis committed
312

Chenu Denis's avatar
Chenu Denis committed
313 314 315 316
            foreach($aLangs as $sLang)
            {
                $aSettings["commenthist_{$sLang}"]=array(
                    'type'=>'string',
Chenu Denis's avatar
Chenu Denis committed
317
                    'label'=>"Sentence added before comment list ({$sLang})",
318 319 320 321
                    'htmlOptions' => array(
                        'placeholder' => $this->gT('Previous comments.','html',$sLang)
                    ),
                    'current' => $this->get("commenthist_{$sLang}", 'Survey', $oEvent->get('survey'),""),
Chenu Denis's avatar
Chenu Denis committed
322 323
                );
            }
Chenu Denis's avatar
Chenu Denis committed
324

325
            // Default history
326 327 328
            $aSettings["updatequestion"]=array(
                'type'=>'select',
                'label'=>"Update and create history question by default.",
329
                'class'=>' delphiinput',
330 331 332 333 334 335
                'options' => array(
                  'Y'=>gt("Yes"),
                  'N'=>gt("No"),
                  ),
                'current' => $this->get("updatequestion", 'Survey', $oEvent->get('survey'),"Y"),
            );
Chenu Denis's avatar
Chenu Denis committed
336 337
            // Did we have an old survey ?
            $aTables = App()->getApi()->getOldResponseTables($iSurveyId);
338
            if(count($aTables)>0) {
Chenu Denis's avatar
Chenu Denis committed
339 340
                $aSettings['launch']=array(
                    'type'=>'link',
341
                    'link'=>Yii::app()->createUrl('admin/pluginhelper',array('plugin' => get_class($this),'sa'=>'sidebody','method' => 'actionSelect','surveyId' => $iSurveyId)),
Chenu Denis's avatar
Chenu Denis committed
342 343
                    'label'=>'Update the survey according to an old answer table',
                    'help'=>'Attention, you lost actual settings',
344
                    'class'=>array('btn-link','delphi-link'),
Chenu Denis's avatar
Chenu Denis committed
345
                );
346
            } else {
Chenu Denis's avatar
Chenu Denis committed
347 348
                $aSettings['check']=array(
                    'type'=>'link',
349
                    'link'=>Yii::app()->createUrl('admin/pluginhelper',array('plugin' => get_class($this),'sa'=>'sidebody','method' => 'actionCheck','surveyId' => $iSurveyId,'function' => 'check')),
Chenu Denis's avatar
Chenu Denis committed
350 351
                    'label'=>'Update the survey to add needed question',
                    'help'=>'Attention, you lost actual settings',
352
                    'class'=>array('btn-link','delphi-link'),
Chenu Denis's avatar
Chenu Denis committed
353 354
                );
            }
Chenu Denis's avatar
Chenu Denis committed
355 356 357 358

            // Add the string for each language
            $oEvent->set("surveysettings.{$this->id}", array('name' => get_class($this),'settings'=>$aSettings));
        }
359 360 361 362
        elseif( $oSurvey && $oSurvey->assessments!='Y' )
        {
            $aSettings['info']=array(
                'type'=>'info',
363
                'content'=>"<div class='alert'><strong>".gT("Assessments mode not activated")."</strong> <br />".sprintf(gT("Assessment mode for this survey is not activated. You can activate it in the %s survey settings %s (tab 'Notification & data management')."),'<a href="'.Yii::app()->createUrl('admin/assessments/',array('sa'=>'index','surveyid'=>$iSurveyId)).'">','</a>')."</div>",
364 365 366 367
            );
            $oEvent->set("surveysettings.{$this->id}", array('name' => get_class($this),'settings'=>$aSettings));
        }
        $assetUrl = Yii::app()->assetManager->publish(dirname(__FILE__) . '/assets');
Chenu Denis's avatar
Chenu Denis committed
368 369 370 371
    }
    public function newSurveySettings()
    {
        $event = $this->event;
372 373
        foreach ($event->get('settings') as $name => $value) {
            $default=$event->get($name,null,null,isset($this->settings[$name]['default']) ? $this->settings[$name]['default'] : NULL);
Chenu Denis's avatar
Chenu Denis committed
374 375 376 377
            $this->set($name, $value, 'Survey', $event->get('survey'),$default);
        }
    }

378 379
    public function setBaseLanguage()
    {
380 381 382 383
        $oSurvey = Survey::model()->findByPk($this->iSurveyId);
        $aAllLanguage = $oSurvey->getAllLanguages();
        if(in_array(App()->session['adminlang'],$aAllLanguage))
            $this->sLanguage = App()->session['adminlang'];
384
        else
385
            $this->sLanguage = $oSurvey->language;
386 387 388
    }
    public function actionSettings()
    {
389
        /* Not used */
390
    }
Chenu Denis's avatar
Chenu Denis committed
391 392
    public function actionCheck()
    {
393 394 395
        $this->iSurveyId = $this->api->getRequest()->getParam('surveyId');
        $this->_checkAccess();
        $this->setBaseLanguage();
Chenu Denis's avatar
Chenu Denis committed
396
        $oRequest = $this->api->getRequest();
397
        if($oRequest->getPost('cancel')) {
Chenu Denis's avatar
Chenu Denis committed
398 399
            App()->controller->redirect(array('admin/survey','sa'=>'view','surveyid'=>$this->iSurveyId));
        }
400
        if($oRequest->getIsPostRequest() && $oRequest->getPost('confirm')) {
Chenu Denis's avatar
Chenu Denis committed
401
            $aQuestionsValidations=$oRequest->getPost('q',array());
402 403 404
            foreach($aQuestionsValidations as $iQid=>$aQuestionValidations) {
                foreach($aQuestionValidations as $sType=>$aQuestionActions) {
                    foreach($aQuestionActions as $sAction=>$sDo) {
405
                        if($sDo) {
Chenu Denis's avatar
Chenu Denis committed
406
                            $this->doQuestion($iQid,$sType,$sAction);
407
                        }
Chenu Denis's avatar
Chenu Denis committed
408 409 410
                    }
                }
            }
411
            Yii::app()->setFlashMessage($this->gT("Survey updated"));
Chenu Denis's avatar
Chenu Denis committed
412 413 414 415
        }
        $oQuestions=$this->getDelphiQuestion();
        $aQuestionsSettings=array();
        $aQuestionsInfo=array();
416 417 418
        $aSettings = array();
        foreach($oQuestions as $oQuestion) {
            $aQuestionSetting = array();
Chenu Denis's avatar
Chenu Denis committed
419 420 421 422
            $sFieldName=$oQuestion->sid."X".$oQuestion->gid."X".$oQuestion->qid;
            $aQuestionsInfo[$oQuestion->qid]=array();
            // Test if question is hidden (already validated)
            $oAttributeHidden=QuestionAttribute::model()->find("qid=:qid AND attribute='hidden'",array(":qid"=>$oQuestion->qid));
423
            $sQuestionTextTitle=FlattenText($oQuestion->question);
Chenu Denis's avatar
Chenu Denis committed
424
            $sQuestionText=ellipsize($sQuestionTextTitle,80);
425 426 427 428 429 430 431 432 433
            if($oQuestion->title!==preg_replace("/[^_a-zA-Z0-9]/", "", $oQuestion->title)) {
                $aQuestionSetting["q_{$oQuestion->qid}"]['type']='info';
                $aQuestionSetting["q_{$oQuestion->qid}"]['content']=CHtml::tag('div',array('class'=>'questiontitle','title'=>$sQuestionTextTitle),"<strong>Invalid title : {$oQuestion->title}</strong> : LimeSurvey 2.05 title allow only alphanumeric (no space, no dot ..)");
            } elseif($oAttributeHidden && $oAttributeHidden->value) {
                $aQuestionSetting["q_{$oQuestion->qid}"]['type']='info';
                $aQuestionSetting["q_{$oQuestion->qid}"]['content']=CHtml::tag('div',array('class'=>'questiontitle','title'=>$sQuestionTextTitle),"<strong>Validated question {$oQuestion->title}</strong> : {$sQuestionText}");
            } else {
                foreach($this->aDelphiCodes as $sDelphiCode=>$aSettings) {
                    $aQuestionSetting=array_merge($aQuestionSetting,$this->getCheckQuestionSettings($oQuestion->qid,$oQuestion->title,$sDelphiCode));
Chenu Denis's avatar
Chenu Denis committed
434 435
                }
            }
436
            $aQuestionsSettings["<strong>{$oQuestion->title}</strong> : {$sQuestionText}"] = $aQuestionSetting;
Chenu Denis's avatar
Chenu Denis committed
437 438
        }
        $aData['aSettings']=$aQuestionsSettings;
439
        $aData['title']=$this->gT("Check survey");
440
        $aData['aResult']=$this->aResult;
441 442
        $aData['updateUrl']=$this->api->createUrl('admin/pluginhelper', array('sa'=>'sidebody','plugin' => get_class($this), 'method' => 'actionUpdate','surveyId'=>$this->iSurveyId));
        return $this->_renderPartial($aData,array("validate"));
Chenu Denis's avatar
Chenu Denis committed
443 444 445
    }
    /**
    * Show the form
446
    *
Chenu Denis's avatar
Chenu Denis committed
447
    **/
448
    public function actionSelect()
Chenu Denis's avatar
Chenu Denis committed
449
    {
450 451
        $this->iSurveyId = $this->api->getRequest()->getParam('surveyId');
        $this->_checkAccess();
Chenu Denis's avatar
Chenu Denis committed
452 453
        //$baseSchema = SurveyDynamic::model($this->iSurveyId)->getTableSchema();
        $aTables = App()->getApi()->getOldResponseTables($this->iSurveyId);
454
        if(count($aTables)) {
Chenu Denis's avatar
Chenu Denis committed
455
            rsort ($aTables);
456
        }
Chenu Denis's avatar
Chenu Denis committed
457 458 459
        $list=array();
        foreach ($aTables as $table)
        {
460 461 462
            $criteria= New CDbCriteria;
            $criteria->condition="submitdate IS NOT NULL";
            $count = PluginDynamic::model($table)->count($criteria);
Chenu Denis's avatar
Chenu Denis committed
463
            $timestamp = date_format(new DateTime(substr($table, -14)), 'Y-m-d H:i:s');
464
            if($count>0)
Chenu Denis's avatar
Chenu Denis committed
465 466
                $list[$table]  = "$timestamp ($count responses)";
        }
467 468 469 470 471 472
        if(!empty($list))
        {
            $aData['settings']['oldsurveytable'] = array(
                'label' => gT('Source table'),
                'type' => 'select',
                'options' => $list,
473 474 475 476
                'htmlOptions' => array(
                    'empty'=>gT("Please choose …"),
                    'required'=>true,
                ),
477
            );
Chenu Denis's avatar
Chenu Denis committed
478 479 480 481
            $aData['settings']['withuncompleted'] = array(
                'label' => gT('Not completed'),
                'type' => 'checkbox',
            );
482
            $aData['buttons'] = array(
483 484
                'validate'=> $this->gT('Validate question before import'),
                'cancel' => gT('Cancel'),
485 486 487 488 489 490 491
            );
        }else{
            $aData['settings']['oldsurveytable'] = array(
                'type' => 'info',
                'content' => CHtml::tag('div',array('class'=>'alert'),'You have old survey table, but no answer inside'),
            );
            $aData['buttons'] = array(
492
                'validate'=> null,
493
                'cancel' => $this->gT('Cancel'),
494 495
            );
        }
496 497 498
        $aData['title'] = $this->gT("Survey selection");
        $aData['updateUrl']=$this->api->createUrl('admin/pluginhelper', array('sa'=>'sidebody','plugin' => get_class($this), 'method' => 'actionValidate','surveyId'=>$this->iSurveyId));
        return $this->_renderPartial($aData,array("select"));
Chenu Denis's avatar
Chenu Denis committed
499 500 501
    }
    /**
    * Validate survey before updating
502
    *
Chenu Denis's avatar
Chenu Denis committed
503 504 505
    **/
    public function actionValidate()
    {
506 507 508
        $this->iSurveyId = $this->api->getRequest()->getParam('surveyId');
        $this->_checkAccess();
        $this->setBaseLanguage();
509
        if(Yii::app()->request->getPost('oldsurveytable')) {
510
            $this->bUpdateHistory=($this->get("updatequestion", 'Survey', $this->iSurveyId,"Y")=="Y");
Chenu Denis's avatar
Chenu Denis committed
511 512 513
            $sTableName=$this->sTableName=Yii::app()->request->getPost('oldsurveytable');
            $aTables = App()->getApi()->getOldResponseTables($this->iSurveyId);
            if(!in_array($sTableName,$aTables)){
514 515 516 517 518 519
                Yii::app()->setFlashMessage($this->gT("Bad table name."),'error');
                App()->controller->redirect(
                    $this->api->createUrl('admin/pluginhelper',
                        array('plugin' => get_class($this),'sa'=>'sidebody','surveyId'=>$this->iSurveyId, 'methode' => 'actionSelect')
                    )
                );
Chenu Denis's avatar
Chenu Denis committed
520
            }
521
            if(Yii::app()->request->getPost('confirm')) {
Chenu Denis's avatar
Chenu Denis committed
522
                $this->actionUpdate();
523
            }
Chenu Denis's avatar
Chenu Denis committed
524
            $oldTable = PluginDynamic::model($sTableName);
Chenu Denis's avatar
Chenu Denis committed
525
            $this->oldSchema = $oldSchema = $oldTable->getTableSchema();
Chenu Denis's avatar
Chenu Denis committed
526 527

            // Ok get the information ...
528
            $oQuestions=$this->getAllQuestion();
Chenu Denis's avatar
Chenu Denis committed
529 530 531 532 533
            $aQuestions=array();
            $aQuestionsSettings=array();
            $aQuestionsInfo=array();

            foreach($oQuestions as $oQuestion){
534 535 536 537 538 539 540
                $legend = $aQuestionsSetting = null;
                if(in_array($oQuestion->type,self::$aValidQuestion)) {
                    $aQuestionsSetting=$this->getValidateQuestionSettings($oQuestion);
                    $legend = "<span class='label label-info'>{$oQuestion->title}</span> : ".ellipsize(flattenText($oQuestion->question),50);
                } elseif(in_array($oQuestion->type,self::$aTextQuestion)) {
                    $aQuestionsSetting=$this->getCommentQuestionSettings($oQuestion);
                    $legend = "<span class='label label-info'>{$oQuestion->title}</span> : ".ellipsize(flattenText($oQuestion->question),50);
541
                }
542 543
                if($legend){
                    $aQuestionsSettings[$legend] = $aQuestionsSetting;
Chenu Denis's avatar
Chenu Denis committed
544 545
                }
            }
546
            $aSurveySettings[$this->gT("Previous responses")]['oldsurveytable']=array(
Chenu Denis's avatar
Chenu Denis committed
547 548 549 550
                'label' => gT('Source table'),
                'type' => 'select',
                'options' => array($sTableName=>$sTableName),
                'current' => $sTableName,
Chenu Denis's avatar
Chenu Denis committed
551 552 553
                'htmlOptions'=>array(
                    'readonly'=>true,
                ),
Chenu Denis's avatar
Chenu Denis committed
554
            );
555
            $aSurveySettings[$this->gT("Previous responses")]['withuncompleted'] = array(
Chenu Denis's avatar
Chenu Denis committed
556 557 558 559
                'label' => gT('Not completed'),
                'type' => 'checkbox',
                'current' => App()->request->getPost('withuncompleted'),
            );
Chenu Denis's avatar
Chenu Denis committed
560
            $aData['aSettings']=array_merge($aQuestionsSettings,$aSurveySettings);
561 562 563 564 565
            $aData['buttons'] = array(
                'confirm' => $this->gT("Confirm update of survey"),
                'cancel' => $this->gT("Cancel"),
            );
            $aData['updateUrl']=$this->api->createUrl('admin/pluginhelper', array('sa'=>'sidebody','plugin' => get_class($this), 'method' => 'actionValidate','surveyId'=>$this->iSurveyId));
566
            LimeExpressionManager::SetDirtyFlag();
567
            return $this->_renderPartial($aData,array("validate"));
568
        } else {
Chenu Denis's avatar
Chenu Denis committed
569 570 571 572 573
            App()->controller->redirect(array('/admin/survey/sa/view','surveyid'=>$this->iSurveyId));
        }
    }
    /**
    * Update survey with old survey
574
    *
Chenu Denis's avatar
Chenu Denis committed
575 576 577
    **/
    public function actionUpdate()
    {
578 579 580
        $this->iSurveyId = $this->api->getRequest()->getParam('surveyId');
        $this->_checkAccess();
        $this->setBaseLanguage();
Chenu Denis's avatar
Chenu Denis committed
581
        $oRequest = $this->api->getRequest();
582
        if($oRequest->getPost('cancel')) {
Chenu Denis's avatar
Chenu Denis committed
583 584 585 586
            App()->controller->redirect(array('admin/survey','sa'=>'view','surveyid'=>$this->iSurveyId));
        }
        if($oRequest->getIsPostRequest() && $oRequest->getPost('confirm'))
        {
587
            if(!$this->oldSchema) {
Chenu Denis's avatar
Chenu Denis committed
588 589 590 591
                $sTableName=$this->sTableName=Yii::app()->request->getPost('oldsurveytable');
                $aTables = App()->getApi()->getOldResponseTables($this->iSurveyId);
                if(!in_array($sTableName,$aTables)){
                    Yii::app()->setFlashMessage("Bad table name.",'error');
592
                    App()->controller->redirect($this->api->createUrl('plugins/direct', array('plugin' => 'autoCommentIterativeQuestionnaire','surveyid'=>$this->iSurveyId, 'function' => 'view')));
Chenu Denis's avatar
Chenu Denis committed
593 594
                }
                $oldTable = PluginDynamic::model($sTableName);
595 596
                $this->oldSchema = $oldSchema = $oldTable->getTableSchema();
            }else {
Chenu Denis's avatar
Chenu Denis committed
597 598
                $oldSchema=$this->oldSchema;
            }
Chenu Denis's avatar
Chenu Denis committed
599 600 601
            $aQuestionsValidations=$oRequest->getPost('validate',array());
            foreach($aQuestionsValidations as $iQid=>$sValue)
            {
Chenu Denis's avatar
Chenu Denis committed
602 603 604
                $bHidden=QuestionAttribute::model()->find("qid=:qid AND attribute='hidden'",array(":qid"=>$iQid));
                $oQuestion=Question::model()->find("sid=:sid AND qid=:qid",array(":sid"=>$this->iSurveyId,":qid"=>"{$iQid}"));
                if($oQuestion && !$bHidden && $sValue=='hide')
Chenu Denis's avatar
Chenu Denis committed
605
                {
606
                    if($this->setQuestionHidden($oQuestion->qid)) {
Chenu Denis's avatar
Chenu Denis committed
607
                        $this->aResult['success'][]="{$oQuestion->title} was hide to respondant";
608
                    } else {
Chenu Denis's avatar
Chenu Denis committed
609
                        $this->aResult['warning'][]="{$oQuestion->title} unable to hide to respondant";
610
                    }
Chenu Denis's avatar
Chenu Denis committed
611
                    // Hide comment question
612
                    if($oQuestion && in_array($oQuestion->type,$this->aDelphiCodes))
Chenu Denis's avatar
Chenu Denis committed
613 614 615 616 617 618 619 620 621 622 623
                    {
                        foreach($this->aDelphiCodes as $sDelphiKey=>$aDelphiCode)
                        {
                            if(isset($aDelphiCode['hidevalidate']) && $aDelphiCode['hidevalidate'])
                            {
                                $oCommentQuestion=Question::model()->find("sid=:sid AND title=:title",array(":sid"=>$this->iSurveyId,":title"=>"{$oQuestion->title}{$sDelphiKey}"));
                                if($oCommentQuestion)
                                    $this->setQuestionHidden($oCommentQuestion->qid);
                            }
                        }
                    }
624

Chenu Denis's avatar
Chenu Denis committed
625
                }
Chenu Denis's avatar
Chenu Denis committed
626 627
                elseif($oQuestion && $bHidden && $sValue=='show')
                {
628
                    if($this->setQuestionShown($iQid)) {
Chenu Denis's avatar
Chenu Denis committed
629
                        $this->aResult['success'][]="{$oQuestion->title} was shown to respondant";
630
                    }
Chenu Denis's avatar
Chenu Denis committed
631
                }
Chenu Denis's avatar
Chenu Denis committed
632 633 634 635 636 637 638 639
            }
            $aQuestionsValidations=$oRequest->getPost('q',array());
            foreach($aQuestionsValidations as $iQid=>$aQuestionValidations)
            {
                foreach($aQuestionValidations as $sType=>$aQuestionActions)
                {
                    foreach($aQuestionActions as $sAction=>$sDo)
                    {
640
                        if($sAction=='select') {
Chenu Denis's avatar
Chenu Denis committed
641
                            $this->doQuestion($iQid,$sType,$sAction,$oldSchema,$sDo);
642
                        } elseif($sDo) {
Chenu Denis's avatar
Chenu Denis committed
643
                            $this->doQuestion($iQid,$sType,$sAction,$oldSchema);
644
                        }
Chenu Denis's avatar
Chenu Denis committed
645 646 647
                    }
                }
            }
648 649 650 651 652
            $aQuestionsValidations=$oRequest->getPost('commhist',array());
            foreach($aQuestionsValidations as $iQid=>$aQuestionAction)
            {
                $this->doCommentQuestion($iQid,$aQuestionAction);
            }
Chenu Denis's avatar
Chenu Denis committed
653
        }
654
        LimeExpressionManager::SetDirtyFlag();
Chenu Denis's avatar
Chenu Denis committed
655 656
        //~ $aData=array();
        //~ $this->displayContent($aData,array("result"));
Chenu Denis's avatar
Chenu Denis committed
657
    }
658 659 660 661 662

    /**
     * @deprecated
     */
    private function _renderPartial($aData=false,$views=false)
Chenu Denis's avatar
Chenu Denis committed
663
    {
664 665 666
        if(!$aData){
            $aData=array();
        }
667 668 669 670 671 672 673 674 675 676 677 678 679
        $aData['lang'] = array(
            "This survey is activated. You can not create question" => $this->gT("This survey is activated. You can not create question"),
            "No Delphi questions found. Are you sure to activate %s and set some value different of 0 for some question." => sprintf(
                $this->gT("No Delphi questions found. Are you sure to activate %s and set some value different of 0 for some question."),
                    "<a href='//manual.limesurvey.org/Assessments' rel='external' title='LimeSurvey manual'>".$this->gT("assessment")."</a>"
            ),
            "Success on :" => $this->gT("Success on :"),
            "Warning on :" => $this->gT("Warning on :"),
            "Error on :" => $this->gT("Error on :"),
            "Success" => $this->gT("Success"),
            "Warning" => $this->gT("Warning"),
            "Error" => $this->gT("Error"),
        );
Chenu Denis's avatar
Chenu Denis committed
680 681
        $aData['surveyid']=$aData['iSurveyID']=$aData['iSurveyId'] = $this->iSurveyId;
        $aData['bSurveyActivated']=$this->bSurveyActivated;
682
        $aData['title'] = !empty($aData['title'] ) ? $aData['title']  : $this->gT("Iterative questionnaire");
Chenu Denis's avatar
Chenu Denis committed
683
        $aData['aResult']=$this->aResult;
684
        $content = "";
Chenu Denis's avatar
Chenu Denis committed
685
        foreach($views as $view){
686
            $content .= $this->renderPartial($view,$aData, true);
Chenu Denis's avatar
Chenu Denis committed
687
        }
688 689 690
        
        return $content;
        //~ Yii::app()->end();
Chenu Denis's avatar
Chenu Denis committed
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
    }

    private function getOldField(CDbTableSchema $oldSchema,$iQid)
    {
        foreach ($oldSchema->columns as $name => $column)
        {
            $pattern = '/([\d]+)X([\d]+)X([\d]+.*)/';
            $matches = array();
            if (preg_match($pattern, $name, $matches))
            {
                if ($matches[3] == $iQid)
                {
                    return $column;
                }
            }
        }
    }
    private function getOldAnswersInfo($iQid,$sType,$sField)
    {
        $aAnswers=array();
        switch ($sType)
        {
            case "Y":
                $aAnswers=array("Y"=>array('answer'=>gt("Yes"),'assessment_value'=>$this->scoreforyes),"N"=>array('answer'=>gt("No"),'assessment_value'=>$this->scoreforno));
                break;
            default:
                $oAnswersCode=Answer::model()->findAll(array('condition'=>"qid=:qid AND language=:language",'order'=>'sortorder','params'=>array(":qid"=>$iQid,":language"=>$this->sLanguage)));
                foreach($oAnswersCode as $oAnswerCode)
                {
                    $aAnswers[$oAnswerCode->code]=$oAnswerCode->attributes;
                }
Chenu Denis's avatar
Chenu Denis committed
722 723 724 725 726 727 728 729 730 731 732 733 734
                // Add other ??
                $oQuestion=Question::model()->find("qid=:qid",array(":qid"=>$iQid));
                if($oQuestion && $oQuestion->other=="Y")
                {
                    $aAnswers["-oth-"]=array(
                        "qid"=>$iQid,
                        "code"=>"-oth-",
                        "answer"=>gt("Other"),
                        "sortorder"=>"500",
                        "assessment_value"=>"0",
                        "language"=>$this->sLanguage,
                    );
                }
Chenu Denis's avatar
Chenu Denis committed
735 736 737 738 739 740
                break;
        }
        foreach($aAnswers as $sCode=>$aAnswer)
        {
            $aAnswers[$sCode]['count']=$this->countOldAnswers($sField,$sCode);
        }
Chenu Denis's avatar
Chenu Denis committed
741

Chenu Denis's avatar
Chenu Denis committed
742 743 744 745 746
        return $aAnswers;
    }
    private function countOldAnswers($sField,$sValue="")
    {
        $sQuotedField=Yii::app()->db->quoteColumnName($sField);
Chenu Denis's avatar
Chenu Denis committed
747 748 749 750
        if(App()->request->getPost('withuncompleted'))
            return PluginDynamic::model($this->sTableName)->count("{$sQuotedField}=:field{$sField}", array(":field{$sField}"=>$sValue));
        else
            return PluginDynamic::model($this->sTableName)->count("submitdate IS NOT NULL AND {$sQuotedField}=:field{$sField}", array(":field{$sField}"=>$sValue));
Chenu Denis's avatar
Chenu Denis committed
751 752 753 754 755 756
    }
    private function getOldAnswerText($sField)
    {
        $sQuotedField=Yii::app()->db->quoteColumnName($sField);
        //return Yii::app()->db->createCommand("SELECT {$sQuotedField} FROM {{{$this->sTableName}}} WHERE {$sQuotedField} IS NOT NULL AND  {$sQuotedField}!=''")->queryAll();
        //Problem on prefix
Chenu Denis's avatar
Chenu Denis committed
757 758 759 760
        if(App()->request->getPost('withuncompleted'))
            $aResult=Yii::app()->db->createCommand("SELECT {$sQuotedField} FROM {$this->sTableName} WHERE {$sQuotedField} IS NOT NULL AND {$sQuotedField}!=''")->queryAll();
        else
            $aResult=Yii::app()->db->createCommand("SELECT {$sQuotedField} FROM {$this->sTableName} WHERE submitdate IS NOT NULL AND {$sQuotedField} IS NOT NULL AND {$sQuotedField}!=''")->queryAll();
Chenu Denis's avatar
Chenu Denis committed
761 762
        return $this->htmlListFromQueryAll($aResult);
    }
Chenu Denis's avatar
Chenu Denis committed
763 764 765 766 767
    private function getOldAnswerTable($iQid,$sType,$sLang)
    {
        $htmlOldAnswersTable="";
        $oldSchema=$this->oldSchema;
        $oldField=$this->getOldField($oldSchema,$iQid);
768
        if($oldField && $oldField->name) {
Chenu Denis's avatar
Chenu Denis committed
769 770 771 772 773 774
            $aOldAnswers=$this->getOldAnswersInfo($iQid,$sType,$oldField->name);
            $iTotalValue=0;
            foreach ($aOldAnswers as $aOldAnswer) {
                if($aOldAnswer['assessment_value']!=0)
                    $iTotalValue += $aOldAnswer['count'];
            }
775 776 777
            if($iTotalValue>0) {
                $htmlOldAnswersTable = "<div class='table-responsive'><table class='aciq-table table table-striped table-bordered'><thead><tr><td></td>";
                $htmlOldAnswersTable.= CHtml::tag('th',array('class'=>"text-center"),$this->gT('Count','html',$sLang));
778
                $htmlOldAnswersTable.= CHtml::tag('th',array('class'=>"text-center"),'%');
Chenu Denis's avatar
Chenu Denis committed
779 780 781 782 783
                $htmlOldAnswersTable.= "</tr></thead><tbody>";
                foreach ($aOldAnswers as $aOldAnswer) {
                    if($aOldAnswer['assessment_value']!=0)
                    {
                        $htmlOldAnswersTable.= "<tr>";
784 785 786 787
                        $htmlOldAnswersTable.= CHtml::tag('th',array('class'=>"text-left"),$aOldAnswer['answer']);
                        $htmlOldAnswersTable.= CHtml::tag('td',array('class'=>"text-center"),$aOldAnswer['count']);
                        $sPercentage=($iTotalValue>0) ? str_pad(number_format($aOldAnswer['count']/$iTotalValue*100),3," ",STR_PAD_LEFT)."%" : "/";
                        $htmlOldAnswersTable.= CHtml::tag('td',array('class'=>"text-center"),$sPercentage);
Chenu Denis's avatar
Chenu Denis committed
788 789 790
                        $htmlOldAnswersTable.= "</tr>";
                    }
                }
Chenu Denis's avatar
Chenu Denis committed
791
                $htmlOldAnswersTable.= "<tr>";
Chenu Denis's avatar
Chenu Denis committed
792
                $htmlOldAnswersTable.= CHtml::tag('th',array(),gT('Total'));
793 794
                $htmlOldAnswersTable.= CHtml::tag('td',array('class'=>"text-center"),$iTotalValue);
                $htmlOldAnswersTable.= CHtml::tag('td',array('class'=>"text-center"),"100%");
Chenu Denis's avatar
Chenu Denis committed
795
                $htmlOldAnswersTable.= "</tr>";
796
                $htmlOldAnswersTable.= "</tbody></table></div>";
Chenu Denis's avatar
Chenu Denis committed
797
            }
Chenu Denis's avatar
Chenu Denis committed
798 799 800 801
        }
        return $htmlOldAnswersTable;

    }
Chenu Denis's avatar
Chenu Denis committed
802 803 804
    private function getDelphiQuestion()
    {
        static $aoQuestionsInfo;
805
        if(is_array($aoQuestionsInfo)) {
Chenu Denis's avatar
Chenu Denis committed
806
            return $aoQuestionsInfo;
807
        }
Chenu Denis's avatar
Chenu Denis committed
808 809 810 811 812 813 814 815 816
        $oCriteria = new CDbCriteria();
        $oCriteria->addCondition("t.sid=:sid AND t.language=:language");
        $oCriteria->params=array(":sid"=>$this->iSurveyId,":language"=>$this->sLanguage);
        $oCriteria->addInCondition("type",self::$aValidQuestion);
        $oCriteria->order="group_order asc, question_order asc";

        $oQuestions=Question::model()->with('groups')->findAll($oCriteria);
        $aoQuestionsInfo=array();
        foreach($oQuestions as $oQuestion){
817
            $key="G".str_pad($oQuestion->groups->group_order,5,"0",STR_PAD_LEFT)."Q".str_pad($oQuestion->question_order,5,"0",STR_PAD_LEFT);
Chenu Denis's avatar
Chenu Denis committed
818
            $oAnswer=Answer::model()->find("qid=:qid and assessment_value!=0",array(":qid"=>$oQuestion->qid));
819
            if($oAnswer) {
820
                $aoQuestionsInfo[$key]=$oQuestion;
821
            }
Chenu Denis's avatar
Chenu Denis committed
822 823
        }
        return $aoQuestionsInfo;
824 825 826
    }
    private function getCommentQuestion()
    {
827
        static $aoQuestionsInfo;
828
        if(is_array($aoQuestionsInfo)) {
829
            return $aoQuestionsInfo;
830
        }
831 832 833 834 835 836
        $oCriteria = new CDbCriteria();
        $oCriteria->addCondition("t.sid=:sid AND t.language=:language and parent_qid=0");
        $oCriteria->params=array(":sid"=>$this->iSurveyId,":language"=>$this->sLanguage);
        $oCriteria->addInCondition("type",self::$aTextQuestion);

        $oCriteria->order="group_order asc, question_order asc";
837

838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
        $oQuestions=Question::model()->with('groups')->findAll($oCriteria);
        $aoQuestionsInfo=array();
        foreach($oQuestions as $oQuestion){
            $key="G".str_pad($oQuestion->groups->group_order,5,"0",STR_PAD_LEFT)."Q".str_pad($oQuestion->question_order,5,"0",STR_PAD_LEFT);
            $aoQuestionsInfo[$key]=$oQuestion;
        }
        return $aoQuestionsInfo;
    }
    private  function getAllQuestion()
    {
        $oDelphiQuestions=$this->getDelphiQuestion();
        $oCommentQuestions=$this->getCommentQuestion();
        $oAllQuestions = array_merge($oDelphiQuestions, $oCommentQuestions);
        ksort ($oAllQuestions);
        return $oAllQuestions;
Chenu Denis's avatar
Chenu Denis committed
853
    }
Chenu Denis's avatar
Chenu Denis committed
854
    private function doQuestion($iQid,$sType,$sAction,$oldSchema=NULL,$sDo=null)
Chenu Denis's avatar
Chenu Denis committed
855 856
    {
        // Validate the delphi question
857
        $oQuestionBase=Question::model()->find("sid=:sid AND language=:language AND qid=:qid",array(":sid"=>$this->iSurveyId,":language"=>$this->sLanguage,":qid"=>$iQid));
858

Chenu Denis's avatar
Chenu Denis committed
859 860
        if(!$oQuestionBase)
        {
861
            $this->addResult("No question {$iQid} in survey : {$sDo} - {$this->sLanguage}",'error');
Chenu Denis's avatar
Chenu Denis committed
862 863
            return false;
        }
Chenu Denis's avatar
Chenu Denis committed
864 865 866 867
        if($sDo)
        {
            $sCode=$oQuestionBase->title;
            $oQuestion=Question::model()->find("sid=:sid AND language=:language AND title=:title",array(":sid"=>$this->iSurveyId,":language"=>$this->sLanguage,":title"=>"{$sCode}{$sType}"));
868 869 870 871
            if($oQuestion) {
                $oHidden = QuestionAttribute::model()->find("qid=:qid AND attribute='hidden'",array(":qid"=>$oQuestion->qid));
            }
            $bHidden=(isset($oHidden) && $oHidden->value);
Chenu Denis's avatar
Chenu Denis committed
872 873 874
            switch($sDo)
            {
                case 'none':
875
                    if($oQuestion) {
Chenu Denis's avatar
Chenu Denis committed
876
                        $this->addResult("{$oQuestion->title} exist in survey.",'warning');
877
                    }
Chenu Denis's avatar
Chenu Denis committed
878 879 880 881
                    return;
                case 'hide':
                    if($oQuestion && !$bHidden)
                    {
882
                        if($this->setQuestionHidden($oQuestion->qid)) {
Chenu Denis's avatar
Chenu Denis committed
883
                            $this->aResult['success'][]="{$oQuestion->title} was hide to respondant";
884
                        } else {
Chenu Denis's avatar
Chenu Denis committed
885
                            $this->aResult['warning'][]="{$oQuestion->title} unable to hide to respondant";
886
                        }
Chenu Denis's avatar
Chenu Denis committed
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
                    }
                    return;
                case 'create':
                    $sAction='createupdate';
                    break;
                case 'update':
                    if($bHidden)
                    {
                        if($this->setQuestionShown($oQuestion->qid))
                            $this->aResult['success'][]="{$oQuestion->title} was shown to respondant";
                        else
                            $this->aResult['warning'][]="{$oQuestion->title} unable to shown to respondant";
                    }
                    $sAction='update';
                    break;
                case 'show':
                    if($bHidden)
                    {
                        if($this->setQuestionShown($oQuestion->qid))
                            $this->aResult['success'][]="{$oQuestion->title} was shown to respondant";
                        else
                            $this->aResult['warning'][]="{$oQuestion->title} unable to shown to respondant";
                    }
                    return;
                default:
                    $this->addResult("Unknow action {$sDo} {$iQid} {$sType} {$sAction} in survey",'warning');
                    return false;
            }
        }
Chenu Denis's avatar
Chenu Denis committed
916 917 918 919 920 921
        $oRequest = $this->api->getRequest();
        $aScores = $oRequest->getPost('value');
        $sCode=$oQuestionBase->title;
        $iGid=$oQuestionBase->gid;
        $aDelphiKeys=array_keys($this->aDelphiCodes);
        $aDelphiCodes=$this->aDelphiCodes;
922

Chenu Denis's avatar
Chenu Denis committed
923 924 925 926 927 928
        if($sAction=='create' || $sAction=='createupdate')
        {
            //Existing question
            $oQuestion=Question::model()->find("sid=:sid AND language=:language AND title=:title",array(":sid"=>$this->iSurveyId,":language"=>$this->sLanguage,":title"=>"{$sCode}{$sType}"));
            if($oQuestion)
            {
929
                $this->addResult(sprintf($this->gT("A question with code %s already exist in your survey, can not create a new one"),$sCode.$sType),'error');
Chenu Denis's avatar
Chenu Denis committed
930 931 932 933 934 935 936 937
                return false;
            }
            //Validate if we can add question
            if(isset($aDelphiCodes[$sType]['need']))
            {
                $oQuestionExist=Question::model()->find("sid=:sid AND language=:language AND title=:title",array(":sid"=>$this->iSurveyId,":language"=>$this->sLanguage,":title"=>"{$sCode}{$aDelphiCodes[$sType]['need']}"));
                if(!$oQuestionExist)
                {
938
                    $this->addResult(sprintf($this->gT("Question %s need a %s"),$sCode.$sType,$sCode.$aDelphiCodes[$sType]['need']));
Chenu Denis's avatar
Chenu Denis committed
939 940 941 942
                    return false;
                }
            }
            $iOrder=$oQuestionBase->question_order;
943
            if($sType=="comm") {
Chenu Denis's avatar
Chenu Denis committed
944
                $iOrder++;
945
            }
Chenu Denis's avatar
Chenu Denis committed
946 947 948 949 950 951 952 953 954 955 956 957 958 959
            if($iNewQid=$this->createQuestion($sCode,$sType,$iGid,$iOrder))
            {
                $oSurvey=Survey::model()->findByPk($this->iSurveyId);
                $aLangs=$oSurvey->getAllLanguages();
                if(isset($aDelphiCodes[$sType]['hidden']))
                    $this->setQuestionHidden($iNewQid);
                if(isset($aDelphiCodes[$sType]['condition']))
                    $this->setQuestionCondition($iNewQid,$sType,$sCode);
            }
        }
        if($sAction=='update' || $sAction=='createupdate')
        {
            $oQuestion=Question::model()->find("sid=:sid AND language=:language AND title=:title",array(":sid"=>$this->iSurveyId,":language"=>$this->sLanguage,":title"=>"{$sCode}{$sType}"));

960 961
            if(!$oQuestion) {
                $this->addResult(sprintf($this->gT("Question with code %s don't exist in your survey"),$sCode.$sType),'error');
Chenu Denis's avatar
Chenu Denis committed
962 963 964 965 966 967 968 969
                return false;
            }
            $oSurvey=Survey::model()->findByPk($this->iSurveyId);
            $aLangs=$oSurvey->getAllLanguages();
            // We have the id
            switch ($sType)
            {
                case 'res':
970
                    if(isset($aScores[$iQid]['score'])){
Chenu Denis's avatar
Chenu Denis committed
971
                        $iCount=Question::model()->updateAll(array('question'=>$aScores[$iQid]['score']),"sid=:sid AND qid=:qid",array(":sid"=>$this->iSurveyId,":qid"=>$oQuestion->qid));
972 973
                        $this->addResult(sprintf($this->gT("%s updated width %s"),$oQuestion->title,$aScores[$iQid]['score']),'success');
                    } else {
Chenu Denis's avatar
Chenu Denis committed
974
                        $iCount=Question::model()->updateAll(array('question'=>""),"sid=:sid AND qid=:qid",array(":sid"=>$this->iSurveyId,":qid"=>$oQuestion->qid));
975
                        $this->addResult(sprintf($this->gT("%s not updated width score : unable to find score"),$oQuestion->title),'warning');
Chenu Denis's avatar
Chenu Denis committed
976 977 978
                    }
                    break;
                case 'hist':
979
                    foreach($aLangs as $sLang) {
Chenu Denis's avatar
Chenu Denis committed
980 981
                        $oQuestionBase=Question::model()->find("sid=:sid AND qid=:qid AND language=:language",array(":sid"=>$this->iSurveyId,":qid"=>$iQid,":language"=>$sLang));
                        if($oQuestionBase){
Chenu Denis's avatar
Chenu Denis committed
982
                            $newQuestionHelp = $oQuestionBase->question;
983
                            if($oldAnswerTable=$this->getOldAnswerTable($oQuestionBase->qid,$oQuestionBase->type,$sLang)) {
984
                                $newQuestionHelp .= "<hr>";
Chenu Denis's avatar
Chenu Denis committed
985 986
                                $newQuestionHelp .= $oldAnswerTable;
                            }
987
                            $newQuestionHelp = "<div class='aciq-content'>".$newQuestionHelp."</div>";
Chenu Denis's avatar
Chenu Denis committed
988
                            Question::model()->updateAll(array('help'=>$newQuestionHelp),"sid=:sid AND title=:title AND language=:language",array(":sid"=>$this->iSurveyId,":title"=>$oQuestionBase->title.$sType,":language"=>$sLang));
989 990 991
                            $oQuestionDelphi = Question::model()->find('sid=:sid AND title=:title',array(":sid"=>$this->iSurveyId,":title"=>$oQuestionBase->title.$sType));
                            if($oQuestion) {
                                $this->setQuestionDelphi($oQuestionDelphi->qid);
992
                                $this->addResult(sprintf($this->gT("%s (%s) - question help updated with list of answers."),$oQuestionBase->title.$sType,$sLang),'success');
993
                            } else {
994
                                $this->addResult(sprintf($this->gT("%s question help was not updated: unable to find question."),$oQuestionBase->title.$sType),'warning');
995
                            }
Chenu Denis's avatar
Chenu Denis committed
996
                        }else{
997
                            $this->addResult(sprintf($this->gT("Unable to find %s to update history for language %s."),$iQid,$sLang),'error');
Chenu Denis's avatar
Chenu Denis committed
998 999
                        }
                    }
1000
                     break;
Chenu Denis's avatar
Chenu Denis committed
1001 1002 1003 1004 1005
                case 'comm':
                    break;
                case 'comh':
                    // Find the old comm value
                    $oQuestionExist=Question::model()->find("sid=:sid AND language=:language AND title=:title",array(":sid"=>$this->iSurveyId,":language"=>$this->sLanguage,":title"=>"{$sCode}comm"));
Chenu Denis's avatar
Chenu Denis committed
1006
                    if($oQuestionExist && $this->oldSchema)
Chenu Denis's avatar
Chenu Denis committed
1007
                    {
Chenu Denis's avatar
Chenu Denis committed
1008
                        $sColumnName=$this->getOldField($this->oldSchema,$oQuestionExist->qid);
Chenu Denis's avatar
Chenu Denis committed
1009 1010 1011
                        if($sColumnName)
                        {
                            $baseQuestionText =$this->getOldAnswerText($sColumnName->name);
1012
                            foreach($aLangs as $sLang) {
1013
                                $newQuestionHelp="<div class='aciq-content'>".$baseQuestionText."</div>";
Chenu Denis's avatar
Chenu Denis committed
1014
                                Question::model()->updateAll(array('help'=>$newQuestionHelp),"sid=:sid AND title=:title AND language=:language",array(":sid"=>$this->iSurveyId,":title"=>$oQuestionBase->title.$sType,":language"=>$sLang));
Chenu Denis's avatar
Chenu Denis committed
1015
                            }
1016 1017 1018
                            $oQuestionDelphi = Question::model()->find('sid=:sid AND title=:title',array(":sid"=>$this->iSurveyId,":title"=>$oQuestionBase->title.$sType));
                            if($oQuestion) {
                                $this->setQuestionDelphi($oQuestionDelphi->qid);
1019
                                $this->addResult(sprintf($this->gT("%s (%s) - question help updated with list of answers."),$oQuestionBase->title.$sType,join(",",$aLangs)),'success');
1020
                            } else {
1021
                                $this->addResult(sprintf($this->gT("%s question help was not updated: unable to find question."),$oQuestionBase->title.$sType),'warning');
1022
                            }
Chenu Denis's avatar
Chenu Denis committed
1023 1024 1025
                        }
                        else
                        {
Chenu Denis's avatar
Chenu Denis committed
1026 1027
                            $newQuestionHelp="";
                            Question::model()->updateAll(array('help'=>$newQuestionText),"sid=:sid AND title=:title",array(":sid"=>$this->iSurveyId,":title"=>$oQuestionBase->title.$sType));
1028
                            $this->addResult(sprintf($this->gT("%s question help cleared: question was not found in old survey."),$oQuestionBase->title.$sType),'warning');
Chenu Denis's avatar
Chenu Denis committed
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
                        }

                    }
                    break;
                case 'cgd':
                    break;
                case 'cgdh':
                    // Find the old cgd value
                    $oQuestionExist=Question::model()->find("sid=:sid AND language=:language AND title=:title",array(":sid"=>$this->iSurveyId,":language"=>$this->sLanguage,":title"=>"{$sCode}cgd"));
                    if($oQuestionExist)
                    {
                        $sColumnName=$this->getOldField($oldSchema,$oQuestionExist->qid);
                        if($sColumnName)
                        {
                            $baseQuestionText =$this->getOldAnswerText($sColumnName->name);
                            foreach($aLangs as $sLang)
                            {
1046 1047 1048
                                $newQuestionText = "<div class='aciq-accordion'>";
                                $newQuestionText .= "<p class='aciq-title comment-title'>".$this->get("commenthist_{$sLang}", 'Survey', $this->iSurveyId,$this->gT('Previous comments.','html',$sLang)).$sLang."</p>";
                                $newQuestionText .= "<div class='aciq-content'>".$baseQuestionText."</div>";
1049
                                $newQuestionText .= "</div>";
Chenu Denis's avatar
Chenu Denis committed
1050 1051
                                Question::model()->updateAll(array('question'=>$newQuestionText),"sid=:sid AND title=:title AND language=:language",array(":sid"=>$this->iSurveyId,":title"=>$oQuestionBase->title.$sType,":language"=>$sLang));
                            }
1052 1053 1054
                            $oQuestionDelphi = Question::model()->find('sid=:sid AND title=:title',array(":sid"=>$this->iSurveyId,":title"=>$oQuestionBase->title.$sType));
                            if($oQuestion) {
                                $this->setQuestionDelphi($oQuestionDelphi->qid);
1055
                                $this->addResult(sprintf($this->gT("%s (%s) - question help updated with list of answers."),$oQuestionBase->title.$sType,join(",",$aLangs)),'success');
1056
                            } else {
1057
                                $this->addResult(sprintf($this->gT("%s question help was not updated: unable to find question."),$oQuestionBase->title.$sType),'warning');
1058
                            }
Chenu Denis's avatar
Chenu Denis committed
1059 1060 1061 1062 1063
                        }
                        else
                        {
                            $newQuestionText="";
                            Question::model()->updateAll(array('question'=>$newQuestionText),"sid=:sid AND title=:title",array(":sid"=>$this->iSurveyId,":title"=>$oQuestionBase->title.$sType));
1064
                            $this->addResult(sprintf($this->gT("%s question help cleared: question was not found in old survey."),$oQuestionBase->title.$sType),'warning');
Chenu Denis's avatar
Chenu Denis committed
1065 1066 1067 1068 1069 1070 1071 1072
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }
1073 1074 1075 1076 1077 1078 1079

    /**
     * Create commant question
     * @param integer $iQid
     * @param string action
     * @return
     */
1080 1081 1082 1083
    private function doCommentQuestion($iQid,$sAction)
    {
        $oSurvey=Survey::model()->findByPk($this->iSurveyId);
        $aLangs=$oSurvey->getAllLanguages();
1084
        $oQuestionBase=Question::model()->find("sid=:sid AND language=:language AND qid=:qid",array(":sid"=>$this->iSurveyId,":language"=>$this->sLanguage,":qid"=>$iQid));
1085 1086
        if(!$oQuestionBase)
        {
1087
            $this->addResult(sprintf($this->gT("No question %s in survey"),$iQid),'error');
1088 1089 1090 1091
            return false;
        }
        $sCode=$oQuestionBase->title;
        $oQuestion=Question::model()->find("sid=:sid AND language=:language AND title=:title",array(":sid"=>$this->iSurveyId,":language"=>$this->sLanguage,":title"=>"{$sCode}h"));
1092
        if($oQuestion) {
1093
            $oHidden=QuestionAttribute::model()->find("qid=:qid AND attribute='hidden'",array(":qid"=>$oQuestion->qid));
1094
        }
1095 1096 1097 1098
        $bHidden=( isset($oHidden) && $oHidden->value)? true : false;
        switch($sAction)
        {
            case 'none':
1099 1100 1101
                if($oQuestion) {
                    $this->addResult(sprintf($this->gT("%s exist in survey."),$oQuestion->title),'warning');
                }
1102 1103
                return;
            case 'hide':
1104 1105 1106 1107 1108 1109
                if($oQuestion && !$bHidden) {
                    if($this->setQuestionHidden($oQuestion->qid)) {
                        $this->aResult['success'][]=sprintf($this->gT("%s was hide to respondant"),$oQuestion->title);
                    } else {
                        $this->aResult['warning'][]=sprintf($this->gT("%s unable to hide to respondant"),$oQuestion->title);
                    }
1110 1111 1112 1113
                }
                return;
            case 'create':
                //Existing question
1114 1115
                if($oQuestion) {
                    $this->addResult(sprintf($this->gT("A question with code %s already exist in your survey, can not create a new one"),$sCode."h"),'error');
1116 1117 1118
                    return false;
                }
                $iOrder=$oQuestionBase->question_order;
1119
                if(strlen($oQuestionBase->title) > 4 && substr($oQuestionBase->title, -4) === "comm") {
Chenu Denis's avatar
Chenu Denis committed
1120 1121
                    //Try to find all question
                    $oQuestionDelphi=Question::model()->find("sid=:sid and title=:title",array(":sid"=>$this->iSurveyId,":title"=>substr($oQuestionBase->title,0, strlen($oQuestionBase->title)-4)));
1122
                    if($oQuestionDelphi) {
Chenu Denis's avatar
Chenu Denis committed
1123 1124 1125
                        $iOrder=$oQuestionDelphi->question_order;
                    }
                }
1126
                if($iNewQid=$this->createQuestion($oQuestionBase->title,"h",$oQuestionBase->gid,$iOrder)) {
1127
                    $oQuestion=Question::model()->find("sid=:sid AND language=:language AND qid=:qid",array(":sid"=>$this->iSurveyId,":language"=>$this->sLanguage,":qid"=>$iNewQid));
1128
                } else {
1129 1130 1131
                    break;
                }
            case 'update':
1132 1133 1134 1135 1136 1137 1138
                if($oQuestion) {
                    if($bHidden) {
                        if($this->setQuestionShown($oQuestion->qid)) {
                            $this->aResult['success'][]=sprintf($this->gT("%s was shown to respondant"),$oQuestion->title);
                        } else {
                            $this->aResult['warning'][]=sprintf($this->gT("%s unable to shown to respondant"),$oQuestion->title);
                        }
1139
                    }
1140
                    if($oQuestionBase && $this->oldSchema) {
1141
                        $sColumnName=$this->getOldField($this->oldSchema,$oQuestionBase->qid);
1142
                        if($sColumnName) {
1143
                            $baseQuestionText =$this->getOldAnswerText($sColumnName->name);
1144
                            foreach($aLangs as $sLang) {
1145
                                $oQuestionCommentLang = Question::model()->find("sid=:sid AND language=:language AND qid=:qid",array(":sid"=>$this->iSurveyId,":language"=>$sLang,":qid"=>$oQuestionBase->qid));
1146
                                if($oQuestionCommentLang) {
1147
                                    $newQuestionHelp = "<div class='aciq-content'><div class='aciq-question-comment'>".$oQuestionCommentLang->question."</div><hr>".$baseQuestionText."</div>";
1148
                                } else {
1149 1150 1151 1152 1153
                                    $newQuestionHelp = "<div class='aciq-content'>".$baseQuestionText."</div>";
                                }
                                $count = Question::model()->updateAll(array('help'=>$newQuestionHelp),"sid=:sid AND qid=:qid AND language=:language",array(":sid"=>$this->iSurveyId,":qid"=>$oQuestion->qid,":language"=>$sLang));
                                if($count) {
                                    $this->addResult(sprintf($this->gT("%s (%s) - question help updated with list of answers."),$oQuestionBase->title."h",$sLang),'success');
1154
                                }
1155
                            }
1156
                            /* @todo : verify of this part … */
1157 1158 1159 1160
                            $oQuestionDelphi = Question::model()->find('sid=:sid AND qid=:qid',array(":sid"=>$this->iSurveyId,":qid"=>$oQuestion->qid));
                            if($oQuestion) {
                                $this->setQuestionDelphi($oQuestionDelphi->qid);
                            } else {
1161
                                $this->addResult(sprintf($this->gT("%s question help was not updated: unable to find question."),$oQuestionBase->title."h"),'warning');
1162
                            }
1163
                        } else {
1164 1165
                            $newQuestionHelp="";
                            Question::model()->updateAll(array('help'=>$newQuestionText),"sid=:sid AND qid=:qid",array(":sid"=>$this->iSurveyId,":qid"=>$oQuestion->qid));
1166
                            $this->addResult(sprintf($this->gT("%s question help cleared: question was not found in old survey."),$oQuestionBase->title."h"),'warning');
1167 1168 1169 1170 1171 1172 1173 1174
                        }
                    }
                }
                break;
            case 'show':
                if($bHidden)
                {
                    if($this->setQuestionShown($oQuestion->qid))
1175
                        $this->aResult['success'][]=sprintf($this->gT("%s was shown to respondant"),$oQuestion->title);
1176
                    else
1177
                        $this->aResult['warning'][]=sprintf($this->gT("%s unable to shown to respondant"),$oQuestion->title);
1178 1179 1180 1181
                }
                return;
            default:
                $this->addResult("Unknow action {$sDo} {$iQid} {$sType} {$sAction} in survey",'warning');
1182
                $this->log("Unknow action {$sDo} {$iQid} {$sType} {$sAction} in survey",'error');
1183 1184 1185
                return false;
        }
    }
Chenu Denis's avatar
Chenu Denis committed
1186 1187 1188 1189 1190
    private function createQuestion($sCode,$sType,$iGid,$iOrder)
    {
        //Need to renumber all questions on or after this
        $sQuery = "UPDATE {{questions}} SET question_order=question_order+1 WHERE sid=:sid AND gid=:gid AND question_order >= :order";
        Yii::app()->db->createCommand($sQuery)->bindValues(array(':sid'=>$this->iSurveyId,':gid'=>$iGid, ':order'=>$iOrder))->query();
1191
        if($sType=="h") {
1192
            $sNewQuestionType="X";
1193
        } else {
1194
            $sNewQuestionType = $this->aDelphiCodes[$sType]['questiontype'];
1195
        }
1196
        switch ($sType) {
Chenu Denis's avatar
Chenu Denis committed
1197
            case 'hist':
1198 1199 1200 1201 1202
                $newQuestionText = $this->get("historytext_{$this->sLanguage}", 'Survey', $this->iSurveyId,"");
                if(trim($newQuestionText) == "") {
                    $newQuestionText = $this->gT('Previous proposal and result','html',$this->sLanguage);
                }
                $newQuestionText = "<p class='aciq-default'>".$newQuestionText."</p>";
Chenu Denis's avatar
Chenu Denis committed
1203 1204
                break;
            case 'comm':
1205 1206 1207 1208
                $newQuestionText = $this->get("commenttext_{$this->sLanguage}", 'Survey', $this->iSurveyId,"");
                if(trim($newQuestionText) == "") {
                    $newQuestionText = $this->gT('Can you explain why you disagree with this proposal.','html',$this->sLanguage);
                }
Chenu Denis's avatar
Chenu Denis committed
1209 1210 1211
                break;
            case 'comh':
                $oQuestionComment=Question::model()->find("sid=:sid and title=:title and language=:language",array(":sid"=>$this->iSurveyId,":title"=>$sCode."comm",":language"=>$this->sLanguage));
1212 1213 1214 1215 1216 1217 1218 1219
                $newQuestionText = $this->get("commenthist_{$this->sLanguage}", 'Survey', $this->iSurveyId,"");
                if(trim($newQuestionText) == "") {
                    $newQuestionText = $this->gT('Previous comments.','html',$this->sLanguage);
                }
                $newQuestionText = "<p class='aciq-default'>".$newQuestionText."</p>";
                if(!empty($oQuestionComment) && $oQuestionComment->question) {
                    $newQuestionText .= "<div class='aciq-historycomment'>".$oQuestionComment->question."</div>";
                }
1220 1221 1222
                break;
            case "h":
                $oQuestionComment=Question::model()->find("sid=:sid and title=:title and language=:language",array(":sid"=>$this->iSurveyId,":title"=>$sCode,":language"=>$this->sLanguage));
1223 1224 1225 1226
                $newQuestionText = $this->get("commenthist_{$this->sLanguage}", 'Survey', $this->iSurveyId,"");
                if(trim($newQuestionText) == "") {
                    $newQuestionText = $this->gT('Previous comments.','html',$this->sLanguage);
                }
Chenu Denis's avatar
Chenu Denis committed
1227
                //~ if(isset($oQuestionComment) && $oQuestionComment->question)
1228
                    //~ $newQuestionText .= "<div class='aciq-historycomment'>".$oQuestionComment->question."</div>";
Chenu Denis's avatar
Chenu Denis committed
1229 1230 1231 1232 1233
                break;
            default:
                $newQuestionText="";
                break;
        }
Chenu Denis's avatar
Chenu Denis committed
1234 1235 1236 1237
        $oQuestion= new Question;
        $oQuestion->sid = $this->iSurveyId;
        $oQuestion->gid = $iGid;
        $oQuestion->title = $sCode.$sType;
Chenu Denis's avatar
Chenu Denis committed
1238
        $oQuestion->question = $newQuestionText;
Chenu Denis's avatar
Chenu Denis committed
1239 1240 1241 1242
        $oQuestion->help = '';
        $oQuestion->preg = '';
        $oQuestion->other = 'N';
        $oQuestion->mandatory = 'N';
1243

1244
        $oQuestion->type=$sNewQuestionType;