Exemplo n.º 1
0
 /**
  * Initialises this controller, does some basic checks and setups
  *
  * @access protected
  * @return void
  */
 protected function _init()
 {
     parent::_init();
     App()->getComponent('bootstrap');
     $sUpdateLastCheck = getGlobalSetting('updatelastcheck');
     $this->_sessioncontrol();
     //if (Yii::app()->getConfig('buildnumber') != "" && Yii::app()->getConfig('updatecheckperiod') > 0 && $sUpdateLastCheck < dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", "-" . Yii::app()->getConfig('updatecheckperiod') . " days"))
     //    updateCheck();
     //        App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . "admin_core.js");
     //$this->pnl_id = Yii::app()->user->getId();
     $this->pnl_id = Yii::app()->session['plid'];
     if (!Yii::app()->getConfig("plid")) {
         Yii::app()->setConfig("plid", returnGlobal('plid'));
     }
     //Panel-list ID
     if (!Yii::app()->getConfig("action")) {
         Yii::app()->setConfig("action", returnGlobal('action'));
     }
     //Desired action
     if (!Yii::app()->getConfig("subaction")) {
         Yii::app()->setConfig("subaction", returnGlobal('subaction'));
     }
     //Desired subaction
     if (!Yii::app()->getConfig("editedaction")) {
         Yii::app()->setConfig("editedaction", returnGlobal('editedaction'));
     }
     // for html editor integration
 }
Exemplo n.º 2
0
 /**
  * questiongroup::import()
  * Function responsible to import a question group.
  *
  * @access public
  * @return void
  */
 function import()
 {
     $action = $_POST['action'];
     $iSurveyID = $surveyid = $aData['surveyid'] = (int) $_POST['sid'];
     if (!Permission::model()->hasSurveyPermission($surveyid, 'surveycontent', 'import')) {
         Yii::app()->user->setFlash('error', gT("Access denied"));
         $this->getController()->redirect(array('admin/survey/sa/listquestiongroups/surveyid/' . $surveyid));
     }
     if ($action == 'importgroup') {
         $importgroup = "\n";
         $importgroup .= "\n";
         $sFullFilepath = Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR . randomChars(20);
         $aPathInfo = pathinfo($_FILES['the_file']['name']);
         $sExtension = $aPathInfo['extension'];
         if ($_FILES['the_file']['error'] == 1 || $_FILES['the_file']['error'] == 2) {
             $fatalerror = sprintf(gT("Sorry, this file is too large. Only files up to %01.2f MB are allowed."), getMaximumFileUploadSize() / 1024 / 1024) . '<br>';
         } elseif (!@move_uploaded_file($_FILES['the_file']['tmp_name'], $sFullFilepath)) {
             $fatalerror = gT("An error occurred uploading your file. This may be caused by incorrect permissions for the application /tmp folder.");
         }
         // validate that we have a SID
         if (!returnGlobal('sid')) {
             $fatalerror .= gT("No SID (Survey) has been provided. Cannot import question.");
         }
         if (isset($fatalerror)) {
             @unlink($sFullFilepath);
             Yii::app()->user->setFlash('error', $fatalerror);
             $this->getController()->redirect(array('admin/questiongroups/sa/importview/surveyid/' . $surveyid));
         }
         Yii::app()->loadHelper('admin/import');
         // IF WE GOT THIS FAR, THEN THE FILE HAS BEEN UPLOADED SUCCESFULLY
         if (strtolower($sExtension) == 'lsg') {
             $aImportResults = XMLImportGroup($sFullFilepath, $iSurveyID);
         } else {
             Yii::app()->user->setFlash('error', gT("Unknown file extension"));
             $this->getController()->redirect(array('admin/questiongroups/sa/importview/surveyid/' . $surveyid));
         }
         LimeExpressionManager::SetDirtyFlag();
         // so refreshes syntax highlighting
         fixLanguageConsistency($iSurveyID);
         if (isset($aImportResults['fatalerror'])) {
             unlink($sFullFilepath);
             Yii::app()->user->setFlash('error', $aImportResults['fatalerror']);
             $this->getController()->redirect(array('admin/questiongroups/sa/importview/surveyid/' . $surveyid));
         }
         unlink($sFullFilepath);
         $aData['display'] = $importgroup;
         $aData['surveyid'] = $iSurveyID;
         $aData['aImportResults'] = $aImportResults;
         $aData['sExtension'] = $sExtension;
         //$aData['display']['menu_bars']['surveysummary'] = 'importgroup';
         $aData['sidemenu']['state'] = false;
         $surveyinfo = Survey::model()->findByPk($iSurveyID)->surveyinfo;
         $aData['title_bar']['title'] = $surveyinfo['surveyls_title'] . "(" . gT("ID") . ":" . $iSurveyID . ")";
         $this->_renderWrappedTemplate('survey/QuestionGroups', 'import_view', $aData);
     }
 }
Exemplo n.º 3
0
 /**
  * Initialises this controller, does some basic checks and setups
  *
  * @access protected
  * @return void
  */
 protected function _init()
 {
     parent::_init();
     App()->getComponent('bootstrap');
     $sUpdateLastCheck = getGlobalSetting('updatelastcheck');
     // echo "111111";
     $this->_sessioncontrol();
     if (Yii::app()->getConfig('buildnumber') != "" && Yii::app()->getConfig('updatecheckperiod') > 0 && $sUpdateLastCheck < dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", "-" . Yii::app()->getConfig('updatecheckperiod') . " days")) {
         updateCheck();
     }
     //unset(Yii::app()->session['FileManagerContext']);
     App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . "admin_core.js");
     $this->user_id = Yii::app()->user->getId();
     if (!Yii::app()->getConfig("surveyid")) {
         Yii::app()->setConfig("surveyid", returnGlobal('sid'));
     }
     //SurveyID
     if (!Yii::app()->getConfig("ugid")) {
         Yii::app()->setConfig("ugid", returnGlobal('ugid'));
     }
     //Usergroup-ID
     if (!Yii::app()->getConfig("gid")) {
         Yii::app()->setConfig("gid", returnGlobal('gid'));
     }
     //GroupID
     if (!Yii::app()->getConfig("qid")) {
         Yii::app()->setConfig("qid", returnGlobal('qid'));
     }
     //QuestionID
     if (!Yii::app()->getConfig("lid")) {
         Yii::app()->setConfig("lid", returnGlobal('lid'));
     }
     //LabelID
     if (!Yii::app()->getConfig("code")) {
         Yii::app()->setConfig("code", returnGlobal('code'));
     }
     // ??
     if (!Yii::app()->getConfig("action")) {
         Yii::app()->setConfig("action", returnGlobal('action'));
     }
     //Desired action
     if (!Yii::app()->getConfig("subaction")) {
         Yii::app()->setConfig("subaction", returnGlobal('subaction'));
     }
     //Desired subaction
     if (!Yii::app()->getConfig("editedaction")) {
         Yii::app()->setConfig("editedaction", returnGlobal('editedaction'));
     }
     // for html editor integration
 }
Exemplo n.º 4
0
 /**
  * Initialises this controller, does some basic checks and setups
  *
  * @access protected
  * @return void
  */
 protected function _init()
 {
     parent::_init();
     $updatelastcheck = '';
     $this->_sessioncontrol();
     if (Yii::app()->getConfig('buildnumber') != "" && Yii::app()->getConfig('updatecheckperiod') > 0 && $updatelastcheck < dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", "-" . Yii::app()->getConfig('updatecheckperiod') . " days")) {
         updateCheck();
     }
     //unset(Yii::app()->session['FileManagerContext']);
     $this->user_id = Yii::app()->user->getId();
     Yii::app()->setConfig('adminimageurl', Yii::app()->getConfig('styleurl') . Yii::app()->getConfig('admintheme') . '/images/');
     Yii::app()->setConfig('adminstyleurl', Yii::app()->getConfig('styleurl') . Yii::app()->getConfig('admintheme') . '/');
     if (!Yii::app()->getConfig("surveyid")) {
         Yii::app()->setConfig("surveyid", returnGlobal('sid'));
     }
     //SurveyID
     if (!Yii::app()->getConfig("ugid")) {
         Yii::app()->setConfig("ugid", returnGlobal('ugid'));
     }
     //Usergroup-ID
     if (!Yii::app()->getConfig("gid")) {
         Yii::app()->setConfig("gid", returnGlobal('gid'));
     }
     //GroupID
     if (!Yii::app()->getConfig("qid")) {
         Yii::app()->setConfig("qid", returnGlobal('qid'));
     }
     //QuestionID
     if (!Yii::app()->getConfig("lid")) {
         Yii::app()->setConfig("lid", returnGlobal('lid'));
     }
     //LabelID
     if (!Yii::app()->getConfig("code")) {
         Yii::app()->setConfig("code", returnGlobal('code'));
     }
     // ??
     if (!Yii::app()->getConfig("action")) {
         Yii::app()->setConfig("action", returnGlobal('action'));
     }
     //Desired action
     if (!Yii::app()->getConfig("subaction")) {
         Yii::app()->setConfig("subaction", returnGlobal('subaction'));
     }
     //Desired subaction
     if (!Yii::app()->getConfig("editedaction")) {
         Yii::app()->setConfig("editedaction", returnGlobal('editedaction'));
     }
     // for html editor integration
 }
Exemplo n.º 5
0
 /**
  * questiongroup::import()
  * Function responsible to import a question group.
  *
  * @access public
  * @return void
  */
 function import()
 {
     $action = $_POST['action'];
     $surveyid = $_POST['sid'];
     $clang = $this->getController()->lang;
     if ($action == 'importgroup') {
         $importgroup = "\n";
         $importgroup .= "\n";
         $sFullFilepath = Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR . randomChars(20);
         $aPathInfo = pathinfo($_FILES['the_file']['name']);
         $sExtension = $aPathInfo['extension'];
         if (!@move_uploaded_file($_FILES['the_file']['tmp_name'], $sFullFilepath)) {
             $fatalerror = sprintf($clang->gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."), $this->config->item('tempdir'));
         }
         // validate that we have a SID
         if (!returnGlobal('sid')) {
             $fatalerror .= $clang->gT("No SID (Survey) has been provided. Cannot import question.");
         }
         if (isset($fatalerror)) {
             @unlink($sFullFilepath);
             $this->getController()->error($fatalerror);
         }
         Yii::app()->loadHelper('admin/import');
         // IF WE GOT THIS FAR, THEN THE FILE HAS BEEN UPLOADED SUCCESFULLY
         if (strtolower($sExtension) == 'csv') {
             $aImportResults = CSVImportGroup($sFullFilepath, $surveyid);
         } elseif (strtolower($sExtension) == 'lsg') {
             $aImportResults = XMLImportGroup($sFullFilepath, $surveyid);
         } else {
             $this->getController()->error('Unknown file extension');
         }
         LimeExpressionManager::SetDirtyFlag();
         // so refreshes syntax highlighting
         fixLanguageConsistency($surveyid);
         if (isset($aImportResults['fatalerror'])) {
             unlink($sFullFilepath);
             $this->getController()->error($aImportResults['fatalerror']);
         }
         unlink($sFullFilepath);
         $aData['display'] = $importgroup;
         $aData['surveyid'] = $surveyid;
         $aData['aImportResults'] = $aImportResults;
         $aData['sExtension'] = $sExtension;
         //$aData['display']['menu_bars']['surveysummary'] = 'importgroup';
         $this->_renderWrappedTemplate('survey/QuestionGroups', 'import_view', $aData);
         // TMSW Condition->Relevance:  call LEM->ConvertConditionsToRelevance() after import
     }
 }
 /**
  * Initialises this controller, does some basic checks and setups
  *
  * @access protected
  * @return void
  */
 protected function _init()
 {
     parent::_init();
     App()->getComponent('bootstrap');
     $this->_sessioncontrol();
     define('ADMIN_SCRIPT_PATH', realpath(Yii::app()->basePath . '/../scripts/admin/') . '/');
     define('SCRIPT_PATH', realpath(Yii::app()->basePath . '/../scripts/') . '/');
     App()->getClientScript()->registerScriptFile(App()->getAssetManager()->publish(ADMIN_SCRIPT_PATH . '/admin_core.js'));
     $this->user_id = Yii::app()->user->getId();
     if (!Yii::app()->getConfig("surveyid")) {
         Yii::app()->setConfig("surveyid", returnGlobal('sid'));
     }
     //SurveyID
     if (!Yii::app()->getConfig("ugid")) {
         Yii::app()->setConfig("ugid", returnGlobal('ugid'));
     }
     //Usergroup-ID
     if (!Yii::app()->getConfig("gid")) {
         Yii::app()->setConfig("gid", returnGlobal('gid'));
     }
     //GroupID
     if (!Yii::app()->getConfig("qid")) {
         Yii::app()->setConfig("qid", returnGlobal('qid'));
     }
     //QuestionID
     if (!Yii::app()->getConfig("lid")) {
         Yii::app()->setConfig("lid", returnGlobal('lid'));
     }
     //LabelID
     if (!Yii::app()->getConfig("code")) {
         Yii::app()->setConfig("code", returnGlobal('code'));
     }
     // ??
     if (!Yii::app()->getConfig("action")) {
         Yii::app()->setConfig("action", returnGlobal('action'));
     }
     //Desired action
     if (!Yii::app()->getConfig("subaction")) {
         Yii::app()->setConfig("subaction", returnGlobal('subaction'));
     }
     //Desired subaction
     if (!Yii::app()->getConfig("editedaction")) {
         Yii::app()->setConfig("editedaction", returnGlobal('editedaction'));
     }
     // for html editor integration
     global $oTemplate;
     $oTemplate = Template::model()->getTemplateConfiguration(Yii::app()->getConfig("defaulttemplate"));
 }
Exemplo n.º 7
0
 /**
  * Initialises this controller, does some basic checks and setups
  *
  * @access protected
  * @return void
  */
 protected function _init()
 {
     parent::_init();
     App()->getComponent('bootstrap');
     $this->_sessioncontrol();
     $this->user_id = Yii::app()->user->getId();
     if (!Yii::app()->getConfig("surveyid")) {
         Yii::app()->setConfig("surveyid", returnGlobal('sid'));
     }
     //SurveyID
     if (!Yii::app()->getConfig("ugid")) {
         Yii::app()->setConfig("ugid", returnGlobal('ugid'));
     }
     //Usergroup-ID
     if (!Yii::app()->getConfig("gid")) {
         Yii::app()->setConfig("gid", returnGlobal('gid'));
     }
     //GroupID
     if (!Yii::app()->getConfig("qid")) {
         Yii::app()->setConfig("qid", returnGlobal('qid'));
     }
     //QuestionID
     if (!Yii::app()->getConfig("lid")) {
         Yii::app()->setConfig("lid", returnGlobal('lid'));
     }
     //LabelID
     if (!Yii::app()->getConfig("code")) {
         Yii::app()->setConfig("code", returnGlobal('code'));
     }
     // ??
     if (!Yii::app()->getConfig("action")) {
         Yii::app()->setConfig("action", returnGlobal('action'));
     }
     //Desired action
     if (!Yii::app()->getConfig("subaction")) {
         Yii::app()->setConfig("subaction", returnGlobal('subaction'));
     }
     //Desired subaction
     if (!Yii::app()->getConfig("editedaction")) {
         Yii::app()->setConfig("editedaction", returnGlobal('editedaction'));
     }
     // for html editor integration
     // Variable not used, but keep it here so the object is initialized at the right place.
     $oTemplate = Template::model()->getInstance(Yii::app()->getConfig("defaulttemplate"));
     $oAdminTheme = AdminTheme::getInstance();
     $oAdminTheme->registerScriptFile('ADMIN_SCRIPT_PATH', 'admin_core.js');
 }
Exemplo n.º 8
0
 /**
  * Initialises this controller, does some basic checks and setups
  *
  * @access protected
  * @return void
  */
 protected function _init()
 {
     parent::_init();
     App()->getComponent('bootstrap');
     $this->_sessioncontrol();
     $this->user_id = Yii::app()->user->getId();
     if (!Yii::app()->getConfig("surveyid")) {
         Yii::app()->setConfig("surveyid", returnGlobal('sid'));
     }
     //SurveyID
     if (!Yii::app()->getConfig("ugid")) {
         Yii::app()->setConfig("ugid", returnGlobal('ugid'));
     }
     //Usergroup-ID
     if (!Yii::app()->getConfig("gid")) {
         Yii::app()->setConfig("gid", returnGlobal('gid'));
     }
     //GroupID
     if (!Yii::app()->getConfig("qid")) {
         Yii::app()->setConfig("qid", returnGlobal('qid'));
     }
     //QuestionID
     if (!Yii::app()->getConfig("lid")) {
         Yii::app()->setConfig("lid", returnGlobal('lid'));
     }
     //LabelID
     if (!Yii::app()->getConfig("code")) {
         Yii::app()->setConfig("code", returnGlobal('code'));
     }
     // ??
     if (!Yii::app()->getConfig("action")) {
         Yii::app()->setConfig("action", returnGlobal('action'));
     }
     //Desired action
     if (!Yii::app()->getConfig("subaction")) {
         Yii::app()->setConfig("subaction", returnGlobal('subaction'));
     }
     //Desired subaction
     if (!Yii::app()->getConfig("editedaction")) {
         Yii::app()->setConfig("editedaction", returnGlobal('editedaction'));
     }
     // for html editor integration
     // This line is needed for template editor to work
     $oAdminTheme = AdminTheme::getInstance();
     AdminTheme::staticRegisterScriptFile('ADMIN_SCRIPT_PATH', 'admin_core.js');
     AdminTheme::staticRegisterScriptFile('ADMIN_SCRIPT_PATH', 'notifications.js');
 }
Exemplo n.º 9
0
 /**
  * Initialises this controller, does some basic checks and setups
  *
  * @access protected
  * @return void
  */
 protected function _init()
 {
     parent::_init();
     App()->getComponent('bootstrap');
     $this->_sessioncontrol();
     App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . "admin_core.js");
     $this->user_id = Yii::app()->user->getId();
     if (!Yii::app()->getConfig("surveyid")) {
         Yii::app()->setConfig("surveyid", returnGlobal('sid'));
     }
     //SurveyID
     if (!Yii::app()->getConfig("ugid")) {
         Yii::app()->setConfig("ugid", returnGlobal('ugid'));
     }
     //Usergroup-ID
     if (!Yii::app()->getConfig("gid")) {
         Yii::app()->setConfig("gid", returnGlobal('gid'));
     }
     //GroupID
     if (!Yii::app()->getConfig("qid")) {
         Yii::app()->setConfig("qid", returnGlobal('qid'));
     }
     //QuestionID
     if (!Yii::app()->getConfig("lid")) {
         Yii::app()->setConfig("lid", returnGlobal('lid'));
     }
     //LabelID
     if (!Yii::app()->getConfig("code")) {
         Yii::app()->setConfig("code", returnGlobal('code'));
     }
     // ??
     if (!Yii::app()->getConfig("action")) {
         Yii::app()->setConfig("action", returnGlobal('action'));
     }
     //Desired action
     if (!Yii::app()->getConfig("subaction")) {
         Yii::app()->setConfig("subaction", returnGlobal('subaction'));
     }
     //Desired subaction
     if (!Yii::app()->getConfig("editedaction")) {
         Yii::app()->setConfig("editedaction", returnGlobal('editedaction'));
     }
     // for html editor integration
 }
Exemplo n.º 10
0
 /**
  * Initialises this controller, does some basic checks and setups
  *
  * @access protected
  * @return void
  */
 protected function _init()
 {
     parent::_init();
     unset(Yii::app()->session['FileManagerContext']);
     if (!Yii::app()->getConfig("surveyid")) {
         Yii::app()->setConfig("surveyid", returnGlobal('sid'));
     }
     //SurveyID
     if (!Yii::app()->getConfig("ugid")) {
         Yii::app()->setConfig("ugid", returnGlobal('ugid'));
     }
     //Usergroup-ID
     if (!Yii::app()->getConfig("gid")) {
         Yii::app()->setConfig("gid", returnGlobal('gid'));
     }
     //GroupID
     if (!Yii::app()->getConfig("qid")) {
         Yii::app()->setConfig("qid", returnGlobal('qid'));
     }
     //QuestionID
     if (!Yii::app()->getConfig("lid")) {
         Yii::app()->setConfig("lid", returnGlobal('lid'));
     }
     //LabelID
     if (!Yii::app()->getConfig("code")) {
         Yii::app()->setConfig("code", returnGlobal('code'));
     }
     // ??
     if (!Yii::app()->getConfig("action")) {
         Yii::app()->setConfig("action", returnGlobal('action'));
     }
     //Desired action
     if (!Yii::app()->getConfig("subaction")) {
         Yii::app()->setConfig("subaction", returnGlobal('subaction'));
     }
     //Desired subaction
     if (!Yii::app()->getConfig("editedaction")) {
         Yii::app()->setConfig("editedaction", returnGlobal('editedaction'));
     }
     // for html editor integration
     Yii::app()->clientScript->registerPackage('decimal');
     // decimal
 }
Exemplo n.º 11
0
                        <?php 
echo CHtml::dropDownList('csvcharset', 'auto', $aEncodings, array('size' => '1', 'class' => 'form-control'));
?>
                    </div>
                </div>

                <!-- Separator used -->
                <div class="form-group">
                    <label class="col-sm-2 control-label" for='separator'><?php 
eT("Separator used:");
?>
 </label>
                    <div class="col-sm-3">
                        <?php 
$aSeparator = array('auto' => gT("(Autodetect)"), 'comma' => gT("Comma"), 'semicolon' => gT("Semicolon"));
echo CHtml::dropDownList('separator', returnGlobal('separator'), $aSeparator, array('size' => '1', 'class' => 'form-control'));
?>
                    </div>
                </div>

                <!-- Filter blank email addresses -->
                <div class="form-group">
                    <label class="col-sm-2 control-label" for='filterblankemail'><?php 
eT("Filter blank email addresses:");
?>
</label>
                    <div class="col-sm-10">
                        <?php 
echo CHtml::checkBox('filterblankemail', true);
?>
                    </div>
/**
* Shows the welcome page, used in group by group and question by question mode
*/
function display_first_page()
{
    global $token, $surveyid, $thissurvey, $navigator;
    $totalquestions = $_SESSION['survey_' . $surveyid]['totalquestions'];
    $clang = Yii::app()->lang;
    // Fill some necessary var for template
    $navigator = surveymover();
    $sitename = Yii::app()->getConfig('sitename');
    $languagechanger = makeLanguageChangerSurvey($clang->langcode);
    sendCacheHeaders();
    doHeader();
    LimeExpressionManager::StartProcessingPage();
    LimeExpressionManager::StartProcessingGroup(-1, false, $surveyid);
    // start on welcome page
    $redata = compact(array_keys(get_defined_vars()));
    $sTemplatePath = $_SESSION['survey_' . $surveyid]['templatepath'];
    echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'frontend_helper[2757]');
    echo CHtml::form(array("/survey/index"), 'post', array('id' => 'limesurvey', 'name' => 'limesurvey', 'autocomplete' => 'off'));
    echo "\n\n<!-- START THE SURVEY -->\n";
    echo templatereplace(file_get_contents($sTemplatePath . "welcome.pstpl"), array(), $redata, 'frontend_helper[2762]') . "\n";
    if ($thissurvey['anonymized'] == "Y") {
        echo templatereplace(file_get_contents($sTemplatePath . "/privacy.pstpl"), array(), $redata, 'frontend_helper[2765]') . "\n";
    }
    echo templatereplace(file_get_contents($sTemplatePath . "navigator.pstpl"), array(), $redata, 'frontend_helper[2767]');
    if ($thissurvey['active'] != "Y") {
        echo "<p style='text-align:center' class='error'>" . $clang->gT("This survey is currently not active. You will not be able to save your responses.") . "</p>\n";
    }
    echo "\n<input type='hidden' name='sid' value='{$surveyid}' id='sid' />\n";
    if (isset($token) && !empty($token)) {
        echo "\n<input type='hidden' name='token' value='{$token}' id='token' />\n";
    }
    echo "\n<input type='hidden' name='lastgroupname' value='_WELCOME_SCREEN_' id='lastgroupname' />\n";
    //This is to ensure consistency with mandatory checks, and new group test
    $loadsecurity = returnGlobal('loadsecurity', true);
    if (isset($loadsecurity)) {
        echo "\n<input type='hidden' name='loadsecurity' value='{$loadsecurity}' id='loadsecurity' />\n";
    }
    $_SESSION['survey_' . $surveyid]['LEMpostKey'] = mt_rand();
    echo "<input type='hidden' name='LEMpostKey' value='{$_SESSION['survey_' . $surveyid]['LEMpostKey']}' id='LEMpostKey' />\n";
    echo "<input type='hidden' name='thisstep' id='thisstep' value='0' />\n";
    echo "\n</form>\n";
    echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'frontend_helper[2782]');
    echo LimeExpressionManager::GetRelevanceAndTailoringJavaScript();
    LimeExpressionManager::FinishProcessingPage();
    doFooter();
}
Exemplo n.º 13
0
 /**
  * Function responsible for deleting a question.
  *
  * @access public
  * @param string $action
  * @param int $surveyid
  * @param int $gid
  * @param int $qid
  * @return void
  */
 public function delete($surveyid, $gid, $qid)
 {
     $clang = $this->getController()->lang;
     $surveyid = sanitize_int($surveyid);
     $gid = sanitize_int($gid);
     $qid = sanitize_int($qid);
     if (hasSurveyPermission($surveyid, 'surveycontent', 'delete')) {
         if (!isset($qid)) {
             $qid = returnGlobal('qid');
         }
         LimeExpressionManager::RevertUpgradeConditionsToRelevance(NULL, $qid);
         // Check if any other questions have conditions which rely on this question. Don't delete if there are.
         // TMSW Conditions->Relevance:  Allow such deletes - can warn about missing relevance separately.
         $ccresult = Conditions::model()->findAllByAttributes(array('cqid' => $qid));
         $cccount = count($ccresult);
         // There are conditions dependent on this question
         if ($cccount) {
             foreach ($ccresult as $ccr) {
                 $qidarray[] = $ccr->qid;
             }
             if (isset($qidarray)) {
                 $qidlist = implode(", ", $qidarray);
             }
             $message = $clang->gT("Question could not be deleted. There are conditions for other questions that rely on this question. You cannot delete this question until those conditions are removed.");
             $message .= "<br /><a href='" . $this->getController()->createUrl("admin/expressions/sa/survey_logic_file/sid/{$surveyid}") . "' >" . $clang->gT("Look at survey logic files") . "</a>.";
             $this->getController()->error($message, $this->getController()->createUrl("admin/survey/sa/view/surveyid/{$surveyid}/gid/{$gid}/qid/{$qid}"));
         } else {
             $row = Questions::model()->findByAttributes(array('qid' => $qid))->attributes;
             $gid = $row['gid'];
             // See if there are any conditions/attributes/answers/defaultvalues for this question,
             // and delete them now as well
             Conditions::model()->deleteAllByAttributes(array('qid' => $qid));
             Question_attributes::model()->deleteAllByAttributes(array('qid' => $qid));
             Answers::model()->deleteAllByAttributes(array('qid' => $qid));
             $criteria = new CDbCriteria();
             $criteria->addCondition('qid = :qid1 or parent_qid = :qid2');
             $criteria->params[':qid1'] = $qid;
             $criteria->params[':qid2'] = $qid;
             Questions::model()->deleteAll($criteria);
             Defaultvalues::model()->deleteAllByAttributes(array('qid' => $qid));
             Quota_members::model()->deleteAllByAttributes(array('qid' => $qid));
             Questions::model()->updateQuestionOrder($gid, $surveyid);
             $qid = "";
             $postqid = "";
             $_GET['qid'] = "";
         }
         Yii::app()->session['flashmessage'] = $clang->gT("Question was successfully deleted.");
         $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $surveyid . '/gid/' . $gid));
     } else {
         Yii::app()->session['flashmessage'] = $clang->gT("You are not authorized to delete questions.");
         $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $surveyid . '/gid/' . $gid));
     }
 }
Exemplo n.º 14
0
 /**
  * Constructor
  */
 public function run($surveyid = 0, $subaction = null)
 {
     $surveyid = sanitize_int($surveyid);
     //TODO: Convert question types to views
     $clang = $this->getController()->lang;
     $imageurl = Yii::app()->getConfig("imageurl");
     $aData = array('clang' => $clang, 'imageurl' => $imageurl);
     $aData['sql'] = '';
     /*
     * We need this later:
     *  1 - Array Dual Scale
     *  5 - 5 Point Choice
     *  A - Array (5 Point Choice)
     *  B - Array (10 Point Choice)
     *  C - Array (Yes/No/Uncertain)
     *  D - Date
     *  E - Array (Increase, Same, Decrease)
     *  F - Array (Flexible Labels)
     *  G - Gender
     *  H - Array (Flexible Labels) by Column
     *  I - Language Switch
     *  K - Multiple Numerical Input
     *  L - List (Radio)
     *  M - Multiple choice
     *  N - Numerical Input
     *  O - List With Comment
     *  P - Multiple choice with comments
     *  Q - Multiple Short Text
     *  R - Ranking
     *  S - Short Free Text
     *  T - Long Free Text
     *  U - Huge Free Text
     *  X - Boilerplate Question
     *  Y - Yes/No
     *  ! - List (Dropdown)
     *  : - Array (Flexible Labels) multiple drop down
     *  ; - Array (Flexible Labels) multiple texts
     *  | - File Upload
     
     
     Debugging help:
     echo '<script language="javascript" type="text/javascript">alert("HI");</script>';
     */
     //split up results to extend statistics -> NOT WORKING YET! DO NOT ENABLE THIS!
     $showcombinedresults = 0;
     /*
      * this variable is used in the function shortencode() which cuts off a question/answer title
      * after $maxchars and shows the rest as tooltip
      */
     $maxchars = 50;
     //we collect all the output within this variable
     $statisticsoutput = '';
     //output for chosing questions to cross query
     $cr_statisticsoutput = '';
     // This gets all the 'to be shown questions' from the POST and puts these into an array
     $summary = returnGlobal('summary');
     $statlang = returnGlobal('statlang');
     //if $summary isn't an array we create one
     if (isset($summary) && !is_array($summary)) {
         $summary = explode("+", $summary);
     }
     //no survey ID? -> come and get one
     if (!isset($surveyid)) {
         $surveyid = returnGlobal('sid');
     }
     //still no survey ID -> error
     $aData['surveyid'] = $surveyid;
     // Set language for questions and answers to base language of this survey
     $language = Survey::model()->findByPk($surveyid)->language;
     $aData['language'] = $language;
     //Call the javascript file
     App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'statistics.js');
     App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'json-js/json2.min.js');
     $aData['display']['menu_bars']['browse'] = $clang->gT("Quick statistics");
     //Select public language file
     $row = Survey::model()->find('sid = :sid', array(':sid' => $surveyid));
     /*
      * check if there is a datestamp available for this survey
      * yes -> $datestamp="Y"
      * no -> $datestamp="N"
      */
     $datestamp = $row->datestamp;
     // 1: Get list of questions from survey
     /*
      * We want to have the following data
      * a) "questions" -> all table namens, e.g.
      * qid
      * sid
      * gid
      * type
      * title
      * question
      * preg
      * help
      * other
      * mandatory
      * lid
      * lid1
      * question_order
      * language
      *
      * b) "groups" -> group_name + group_order *
      */
     //store all the data in $rows
     $rows = Question::model()->getQuestionList($surveyid, $language);
     //SORT IN NATURAL ORDER!
     usort($rows, 'groupOrderThenQuestionOrder');
     //put the question information into the filter array
     $filters = array();
     foreach ($rows as $row) {
         //store some column names in $filters array
         $filters[] = array($row['qid'], $row['gid'], $row['type'], $row['title'], $row['group_name'], flattenText($row['question']));
     }
     $aData['filters'] = $filters;
     //var_dump($filters);
     // SHOW ID FIELD
     $grapherror = false;
     $error = '';
     if (!function_exists("gd_info")) {
         $grapherror = true;
         $error .= '<br />' . $clang->gT('You do not have the GD Library installed. Showing charts requires the GD library to function properly.');
         $error .= '<br />' . $clang->gT('visit http://us2.php.net/manual/en/ref.image.php for more information') . '<br />';
     } elseif (!function_exists("imageftbbox")) {
         $grapherror = true;
         $error .= '<br />' . $clang->gT('You do not have the Freetype Library installed. Showing charts requires the Freetype library to function properly.');
         $error .= '<br />' . $clang->gT('visit http://us2.php.net/manual/en/ref.image.php for more information') . '<br />';
     }
     if ($grapherror) {
         unset($_POST['usegraph']);
     }
     //pre-selection of filter forms
     if (incompleteAnsFilterState() == "complete") {
         $selecthide = "selected='selected'";
         $selectshow = "";
         $selectinc = "";
     } elseif (incompleteAnsFilterState() == "incomplete") {
         $selecthide = "";
         $selectshow = "";
         $selectinc = "selected='selected'";
     } else {
         $selecthide = "";
         $selectshow = "selected='selected'";
         $selectinc = "";
     }
     $aData['selecthide'] = $selecthide;
     $aData['selectshow'] = $selectshow;
     $aData['selectinc'] = $selectinc;
     $aData['error'] = $error;
     $survlangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
     $survlangs[] = Survey::model()->findByPk($surveyid)->language;
     $aData['survlangs'] = $survlangs;
     $aData['datestamp'] = $datestamp;
     //if the survey contains timestamps you can filter by timestamp, too
     //Output selector
     //second row below options -> filter settings headline
     $filterchoice_state = returnGlobal('filterchoice_state');
     $aData['filterchoice_state'] = $filterchoice_state;
     /*
     * let's go through the filter array which contains
     * 	['qid'],
     ['gid'],
     ['type'],
     ['title'],
     ['group_name'],
     ['question'],
     ['lid'],
     ['lid1']);
     */
     $currentgroup = '';
     $counter = 0;
     foreach ($filters as $key1 => $flt) {
         //is there a previous question type set?
         /*
         * remember: $flt is structured like this
         *  ['qid'],
         ['gid'],
         ['type'],
         ['title'],
         ['group_name'],
         ['question'],
         ['lid'],
         ['lid1']);
         */
         //SGQ identifier
         //full question title
         /*
         * Check question type: This question types will be used (all others are separated in the if clause)
         *  5 - 5 Point Choice
         G - Gender
         I - Language Switch
         L - List (Radio)
         M - Multiple choice
         N - Numerical Input
         | - File Upload
         O - List With Comment
         P - Multiple choice with comments
         Y - Yes/No
         ! - List (Dropdown) )
         */
         /////////////////////////////////////////////////////////////////////////////////////////////////
         //This section presents the filter list, in various different ways depending on the question type
         /////////////////////////////////////////////////////////////////////////////////////////////////
         //let's switch through the question type for each question
         switch ($flt[2]) {
             case "K":
                 // Multiple Numerical
                 //get answers
                 $result = Question::model()->getQuestionsForStatistics('title as code, question as answer', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order');
                 $aData['result'][$key1]['key1'] = $result;
                 break;
             case "Q":
                 // Multiple Short Text
                 //get subqestions
                 $result = Question::model()->getQuestionsForStatistics('title as code, question as answer', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order');
                 $aData['result'][$key1] = $result;
                 break;
                 //----------------------- ARRAYS --------------------------
             //----------------------- ARRAYS --------------------------
             case "A":
                 // ARRAY OF 5 POINT CHOICE QUESTIONS
                 //get answers
                 $result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order');
                 $aData['result'][$key1] = $result;
                 break;
                 //just like above only a different loop
             //just like above only a different loop
             case "B":
                 // ARRAY OF 10 POINT CHOICE QUESTIONS
                 $result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order');
                 $aData['result'][$key1] = $result;
                 break;
             case "C":
                 // ARRAY OF YES\No\$clang->gT("Uncertain") QUESTIONS
                 //get answers
                 $result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order');
                 $aData['result'][$key1] = $result;
                 break;
                 //similiar to the above one
             //similiar to the above one
             case "E":
                 // ARRAY OF Increase/Same/Decrease QUESTIONS
                 $result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order');
                 $aData['result'][$key1] = $result;
                 break;
             case ";":
                 //ARRAY (Multi Flex) (Text)
                 $result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}' AND scale_id = 0", 'question_order');
                 $aData['result'][$key1] = $result;
                 foreach ($result as $key => $row) {
                     $fresult = Question::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}' AND scale_id = 1", 'question_order');
                     $aData['fresults'][$key1][$key] = $fresult;
                 }
                 break;
             case ":":
                 //ARRAY (Multi Flex) (Numbers)
                 $result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}' AND scale_id = 0", 'question_order');
                 $aData['result'][$key1] = $result;
                 foreach ($result as $row) {
                     $fresult = Question::model()->getQuestionsForStatistics('*', "parent_qid={$flt['0']} AND language = '{$language}' AND scale_id = 1", 'question_order, title');
                     $aData['fresults'][$key1] = $fresult;
                 }
                 break;
                 /*
                  * For question type "F" and "H" you can use labels.
                  * The only difference is that the labels are applied to column heading
                  * or rows respectively
                  */
             /*
              * For question type "F" and "H" you can use labels.
              * The only difference is that the labels are applied to column heading
              * or rows respectively
              */
             case "F":
                 // FlEXIBLE ARRAY
             // FlEXIBLE ARRAY
             case "H":
                 // ARRAY (By Column)
                 //Get answers. We always use the answer code because the label might be too long elsewise
                 $result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order');
                 $aData['result'][$key1] = $result;
                 //check all the answers
                 foreach ($result as $row) {
                     $fresult = Answer::model()->getQuestionsForStatistics('*', "qid={$flt['0']} AND language = '{$language}'", 'sortorder, code');
                     $aData['fresults'][$key1] = $fresult;
                 }
                 //$statisticsoutput .= "\t\t\t\t<td>\n";
                 $counter = 0;
                 break;
             case "R":
                 //RANKING
                 //get some answers
                 $result = Answer::model()->getQuestionsForStatistics('code, answer', "qid={$flt['0']} AND language = '{$language}'", 'sortorder, answer');
                 $aData['result'][$key1] = $result;
                 break;
             case "1":
                 // MULTI SCALE
                 //get answers
                 $result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order');
                 $aData['result'][$key1] = $result;
                 //loop through answers
                 foreach ($result as $key => $row) {
                     //check if there is a dualscale_headerA/B
                     $dshresult = QuestionAttribute::model()->getQuestionsForStatistics('value', "qid={$flt['0']} AND attribute = 'dualscale_headerA'", '');
                     $aData['dshresults'][$key1][$key] = $dshresult;
                     $fresult = Answer::model()->getQuestionsForStatistics('*', "qid={$flt['0']} AND language = '{$language}' AND scale_id = 0", 'sortorder, code');
                     $aData['fresults'][$key1][$key] = $fresult;
                     $dshresult2 = QuestionAttribute::model()->getQuestionsForStatistics('value', "qid={$flt['0']} AND attribute = 'dualscale_headerB'", '');
                     $aData['dshresults2'][$key1][$key] = $dshresult2;
                 }
                 break;
             case "P":
                 //P - Multiple choice with comments
             //P - Multiple choice with comments
             case "M":
                 //M - Multiple choice
                 //get answers
                 $result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid = {$flt['0']} AND language = '{$language}'", 'question_order');
                 $aData['result'][$key1] = $result;
                 break;
                 /*
                 * This question types use the default settings:
                 * 	L - List (Radio)
                 O - List With Comment
                 P - Multiple choice with comments
                 ! - List (Dropdown)
                 */
             /*
             * This question types use the default settings:
             * 	L - List (Radio)
             O - List With Comment
             P - Multiple choice with comments
             ! - List (Dropdown)
             */
             default:
                 //get answers
                 $result = Answer::model()->getQuestionsForStatistics('code, answer', "qid={$flt['0']} AND language = '{$language}'", 'sortorder, answer');
                 $aData['result'][$key1] = $result;
                 break;
         }
         //end switch -> check question types and create filter forms
         $currentgroup = $flt[1];
         $counter++;
         //temporary save the type of the previous question
         //used to adjust linebreaks
         $previousquestiontype = $flt[2];
     }
     // ----------------------------------- END FILTER FORM ---------------------------------------
     Yii::app()->loadHelper('admin/statistics');
     $showtextinline = isset($_POST['showtextinline']) ? 1 : 0;
     $aData['showtextinline'] = $showtextinline;
     //Show Summary results
     if (isset($summary) && $summary) {
         $usegraph = isset($_POST['usegraph']) ? 1 : 0;
         $aData['usegraph'] = $usegraph;
         $outputType = $_POST['outputtype'];
         $helper = new statistics_helper();
         switch ($outputType) {
             case 'html':
                 $statisticsoutput .= $helper->generate_statistics($surveyid, $summary, $summary, $usegraph, $outputType, 'DD', $statlang);
                 break;
             case 'pdf':
                 $helper->generate_statistics($surveyid, $summary, $summary, $usegraph, $outputType, 'I', $statlang);
                 exit;
                 break;
             case 'xls':
                 $helper->generate_statistics($surveyid, $summary, $summary, $usegraph, $outputType, 'DD', $statlang);
                 exit;
                 break;
             default:
                 break;
         }
     }
     //end if -> show summary results
     $aData['sStatisticsLanguage'] = $statlang;
     $aData['output'] = $statisticsoutput;
     $aData['summary'] = $summary;
     $this->_renderWrappedTemplate('export', 'statistics_view', $aData);
 }
Exemplo n.º 15
0
 /**
  * Function that initialises all data and call other functions to load default view.
  *
  * @access protected
  * @param string $templatename
  * @param string $screenname
  * @param string $editfile
  * @param bool $showsummary
  * @return
  */
 protected function _initialise($templatename, $screenname, $editfile, $showsummary = true)
 {
     App()->getClientScript()->reset();
     $clang = $this->getController()->lang;
     Yii::app()->loadHelper('surveytranslator');
     Yii::app()->loadHelper('admin/template');
     $files = $this->_initfiles($templatename);
     $cssfiles = $this->_initcssfiles();
     // Standard Support Files
     // These files may be edited or saved
     $supportfiles[] = array('name' => 'print_img_radio.png');
     $supportfiles[] = array('name' => 'print_img_checkbox.png');
     // Standard screens
     // Only these may be viewed
     $screens[] = array('name' => $clang->gT('Survey List Page'), 'id' => 'surveylist');
     $screens[] = array('name' => $clang->gT('Welcome Page'), 'id' => 'welcome');
     $screens[] = array('name' => $clang->gT('Question Page'), 'id' => 'question');
     $screens[] = array('name' => $clang->gT('Completed Page'), 'id' => 'completed');
     $screens[] = array('name' => $clang->gT('Clear All Page'), 'id' => 'clearall');
     $screens[] = array('name' => $clang->gT('Register Page'), 'id' => 'register');
     $screens[] = array('name' => $clang->gT('Load Page'), 'id' => 'load');
     $screens[] = array('name' => $clang->gT('Save Page'), 'id' => 'save');
     $screens[] = array('name' => $clang->gT('Print answers page'), 'id' => 'printanswers');
     $screens[] = array('name' => $clang->gT('Printable survey page'), 'id' => 'printablesurvey');
     // Page display blocks
     $SurveyList = array('startpage.pstpl', 'surveylist.pstpl', 'endpage.pstpl');
     $Welcome = array('startpage.pstpl', 'welcome.pstpl', 'privacy.pstpl', 'navigator.pstpl', 'endpage.pstpl');
     $Question = array('startpage.pstpl', 'survey.pstpl', 'startgroup.pstpl', 'groupdescription.pstpl', 'question.pstpl', 'endgroup.pstpl', 'navigator.pstpl', 'endpage.pstpl');
     $CompletedTemplate = array('startpage.pstpl', 'assessment.pstpl', 'completed.pstpl', 'endpage.pstpl');
     $Clearall = array('startpage.pstpl', 'clearall.pstpl', 'endpage.pstpl');
     $Register = array('startpage.pstpl', 'survey.pstpl', 'register.pstpl', 'endpage.pstpl');
     $Save = array('startpage.pstpl', 'save.pstpl', 'endpage.pstpl');
     $Load = array('startpage.pstpl', 'load.pstpl', 'endpage.pstpl');
     $printtemplate = array('startpage.pstpl', 'printanswers.pstpl', 'endpage.pstpl');
     $printablesurveytemplate = array('print_survey.pstpl', 'print_group.pstpl', 'print_question.pstpl');
     $file_version = "LimeSurvey template editor " . Yii::app()->getConfig('versionnumber');
     Yii::app()->session['s_lang'] = Yii::app()->session['adminlang'];
     $templatename = sanitize_dirname($templatename);
     $screenname = autoUnescape($screenname);
     // Checks if screen name is in the list of allowed screen names
     if (multiarray_search($screens, 'id', $screenname) === false) {
         $this->getController()->error('Invalid screen name');
     }
     if (!isset($action)) {
         $action = sanitize_paranoid_string(returnGlobal('action'));
     }
     if (!isset($subaction)) {
         $subaction = sanitize_paranoid_string(returnGlobal('subaction'));
     }
     if (!isset($newname)) {
         $newname = sanitize_dirname(returnGlobal('newname'));
     }
     if (!isset($copydir)) {
         $copydir = sanitize_dirname(returnGlobal('copydir'));
     }
     if (is_file(Yii::app()->getConfig('usertemplaterootdir') . '/' . $templatename . '/question_start.pstpl')) {
         $files[] = array('name' => 'question_start.pstpl');
         $Question[] = 'question_start.pstpl';
     }
     $availableeditorlanguages = array('bg', 'cs', 'de', 'dk', 'en', 'eo', 'es', 'fi', 'fr', 'hr', 'it', 'ja', 'mk', 'nl', 'pl', 'pt', 'ru', 'sk', 'zh');
     $extension = substr(strrchr($editfile, "."), 1);
     if ($extension == 'css' || $extension == 'js') {
         $highlighter = $extension;
     } else {
         $highlighter = 'html';
     }
     if (in_array(Yii::app()->session['adminlang'], $availableeditorlanguages)) {
         $codelanguage = Yii::app()->session['adminlang'];
     } else {
         $codelanguage = 'en';
     }
     $templates = getTemplateList();
     if (!isset($templates[$templatename])) {
         $templatename = Yii::app()->getConfig('defaulttemplate');
     }
     $normalfiles = array("DUMMYENTRY", ".", "..", "preview.png");
     foreach ($files as $fl) {
         $normalfiles[] = $fl["name"];
     }
     foreach ($cssfiles as $fl) {
         $normalfiles[] = $fl["name"];
     }
     // Some global data
     $aData['sitename'] = Yii::app()->getConfig('sitename');
     $siteadminname = Yii::app()->getConfig('siteadminname');
     $siteadminemail = Yii::app()->getConfig('siteadminemail');
     // Set this so common.php doesn't throw notices about undefined variables
     $thissurvey['active'] = 'N';
     // FAKE DATA FOR TEMPLATES
     $thissurvey['name'] = $clang->gT("Template Sample");
     $thissurvey['description'] = "<p>" . $clang->gT('This is a sample survey description. It could be quite long.') . "</p>" . "<p>" . $clang->gT("But this one isn't.") . "<p>";
     $thissurvey['welcome'] = "<p>" . $clang->gT('Welcome to this sample survey') . "<p>" . "<p>" . $clang->gT('You should have a great time doing this') . "<p>";
     $thissurvey['allowsave'] = "Y";
     $thissurvey['active'] = "Y";
     $thissurvey['tokenanswerspersistence'] = "Y";
     $thissurvey['templatedir'] = $templatename;
     $thissurvey['format'] = "G";
     $thissurvey['surveyls_url'] = "http://www.limesurvey.org/";
     $thissurvey['surveyls_urldescription'] = $clang->gT("Some URL description");
     $thissurvey['usecaptcha'] = "A";
     $percentcomplete = makegraph(6, 10);
     $groupname = $clang->gT("Group 1: The first lot of questions");
     $groupdescription = $clang->gT("This group description is fairly vacuous, but quite important.");
     $navigator = $this->getController()->render('/admin/templates/templateeditor_navigator_view', array('screenname' => $screenname, 'clang' => $clang), true);
     $completed = $this->getController()->render('/admin/templates/templateeditor_completed_view', array('clang' => $clang), true);
     $assessments = $this->getController()->render('/admin/templates/templateeditor_assessments_view', array('clang' => $clang), true);
     $printoutput = $this->getController()->render('/admin/templates/templateeditor_printoutput_view', array('clang' => $clang), true);
     $totalquestions = '10';
     $surveyformat = 'Format';
     $notanswered = '5';
     $privacy = '';
     $surveyid = '1295';
     $token = 1234567;
     $templatedir = getTemplatePath($templatename);
     $templateurl = getTemplateURL($templatename);
     // Save these variables in an array
     $aData['thissurvey'] = $thissurvey;
     $aData['percentcomplete'] = $percentcomplete;
     $aData['groupname'] = $groupname;
     $aData['groupdescription'] = $groupdescription;
     $aData['navigator'] = $navigator;
     $aData['help'] = $clang->gT("This is some help text.");
     $aData['surveyformat'] = $surveyformat;
     $aData['totalquestions'] = $totalquestions;
     $aData['completed'] = $completed;
     $aData['notanswered'] = $notanswered;
     $aData['privacy'] = $privacy;
     $aData['surveyid'] = $surveyid;
     $aData['sid'] = $surveyid;
     $aData['token'] = $token;
     $aData['assessments'] = $assessments;
     $aData['printoutput'] = $printoutput;
     $aData['templatedir'] = $templatedir;
     $aData['templateurl'] = $templateurl;
     $aData['templatename'] = $templatename;
     $aData['screenname'] = $screenname;
     $aData['editfile'] = $editfile;
     $myoutput[] = "";
     switch ($screenname) {
         case 'surveylist':
             unset($files);
             $surveylist = array("nosid" => $clang->gT("You have not provided a survey identification number"), "contact" => sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), Yii::app()->getConfig("siteadminname"), Yii::app()->getConfig("siteadminemail")), "listheading" => $clang->gT("The following surveys are available:"), "list" => $this->getController()->render('/admin/templates/templateeditor_surveylist_view', array(), true));
             $aData['surveylist'] = $surveylist;
             $myoutput[] = "";
             foreach ($SurveyList as $qs) {
                 $files[] = array("name" => $qs);
                 $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/{$qs}", $aData));
             }
             break;
         case 'question':
             unset($files);
             foreach ($Question as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = $this->getController()->render('/admin/templates/templateeditor_question_meta_view', array('clang' => $clang), true);
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/startpage.pstpl", $aData));
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/survey.pstpl", $aData));
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/startgroup.pstpl", $aData));
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/groupdescription.pstpl", $aData));
             $question = array('all' => $clang->gT("How many roads must a man walk down?"), 'text' => $clang->gT("How many roads must a man walk down?"), 'code' => '1a', 'help' => 'helpful text', 'mandatory' => $clang->gT("*"), 'man_class' => ' mandatory', 'man_message' => '', 'valid_message' => '', 'file_valid_message' => '', 'essentials' => 'id="question1"', 'class' => 'list-radio', 'input_error_class' => '', 'number' => '1', 'type' => 'L');
             $aData['question'] = $question;
             $answer = $this->getController()->render('/admin/templates/templateeditor_question_answer_view', array('clang' => $clang), true);
             $aData['answer'] = $answer;
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/question.pstpl", $aData));
             $answer = $this->getController()->render('/admin/templates/templateeditor_question_answer_view', array('alt' => true, 'clang' => $clang), true);
             $aData['answer'] = $answer;
             $question = array('all' => $clang->gT("Please explain something in detail:"), 'text' => $clang->gT('Please explain something in detail:'), 'code' => '2a', 'help' => '', 'mandatory' => '', 'man_message' => '', 'valid_message' => '', 'file_valid_message' => '', 'essentials' => 'id="question2"', 'class' => 'text-long', 'man_class' => 'mandatory', 'input_error_class' => '', 'number' => '2', 'type' => 'T');
             $aData['question'] = $question;
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/question.pstpl", $aData));
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/endgroup.pstpl", $aData));
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/navigator.pstpl", $aData));
             $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/endpage.pstpl", $aData));
             break;
         case 'welcome':
             unset($files);
             $myoutput[] = "";
             foreach ($Welcome as $qs) {
                 $files[] = array("name" => $qs);
                 $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/{$qs}", $aData));
             }
             break;
         case 'register':
             unset($files);
             foreach ($Register as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/survey.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/register.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData);
             $myoutput[] = "\n";
             break;
         case 'save':
             unset($files);
             foreach ($Save as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/save.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData);
             $myoutput[] = "\n";
             break;
         case 'load':
             unset($files);
             foreach ($Load as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/load.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData);
             $myoutput[] = "\n";
             break;
         case 'clearall':
             unset($files);
             foreach ($Clearall as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/clearall.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData);
             $myoutput[] = "\n";
             break;
         case 'completed':
             unset($files);
             $myoutput[] = "";
             foreach ($CompletedTemplate as $qs) {
                 $files[] = array("name" => $qs);
                 $myoutput = array_merge($myoutput, doreplacement(getTemplatePath($templatename) . "/{$qs}", $aData));
             }
             break;
         case 'printablesurvey':
             unset($files);
             foreach ($printablesurveytemplate as $qs) {
                 $files[] = array("name" => $qs);
             }
             $questionoutput = array();
             foreach (file("{$templatedir}/print_question.pstpl") as $op) {
                 $questionoutput[] = templatereplace($op, array('QUESTION_NUMBER' => '1', 'QUESTION_CODE' => 'Q1', 'QUESTION_MANDATORY' => $clang->gT('*'), 'QUESTION_SCENARIO' => 'Only answer this if certain conditions are met.', 'QUESTION_CLASS' => ' mandatory list-radio', 'QUESTION_TYPE_HELP' => $clang->gT('Please choose *only one* of the following:'), 'QUESTION_MAN_MESSAGE' => '', 'QUESTION_VALID_MESSAGE' => '', 'QUESTION_FILE_VALID_MESSAGE' => '', 'QUESTION_TEXT' => $clang->gT('This is a sample question text. The user was asked to pick an entry.'), 'QUESTIONHELP' => $clang->gT('This is some help text for this question.'), 'ANSWER' => $this->getController()->render('/admin/templates/templateeditor_printablesurvey_quesanswer_view', array('templateurl' => $templateurl, 'clang' => $clang), true)), $aData);
             }
             $groupoutput = array();
             $groupoutput[] = templatereplace(file_get_contents("{$templatedir}/print_group.pstpl"), array('QUESTIONS' => implode(' ', $questionoutput)), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/print_survey.pstpl"), array('GROUPS' => implode(' ', $groupoutput), 'FAX_TO' => $clang->gT("Please fax your completed survey to:") . " 000-000-000", 'SUBMIT_TEXT' => $clang->gT("Submit your survey."), 'HEADELEMENTS' => getPrintableHeader(), 'SUBMIT_BY' => sprintf($clang->gT("Please submit by %s"), date('d.m.y')), 'THANKS' => $clang->gT('Thank you for completing this survey.'), 'END' => $clang->gT('This is the survey end message.')), $aData);
             break;
         case 'printanswers':
             unset($files);
             foreach ($printtemplate as $qs) {
                 $files[] = array("name" => $qs);
             }
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/printanswers.pstpl"), array('ANSWERTABLE' => $printoutput), $aData);
             $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData);
             $myoutput[] = "\n";
             break;
     }
     $myoutput[] = "</html>";
     if (is_array($files)) {
         $match = 0;
         foreach ($files as $f) {
             if ($editfile == $f["name"]) {
                 $match = 1;
             }
         }
         foreach ($cssfiles as $f) {
             if ($editfile == $f["name"]) {
                 $match = 1;
             }
         }
         if ($match == 0) {
             if (count($files) > 0) {
                 $editfile = $files[0]["name"];
             } else {
                 $editfile = "";
             }
         }
     }
     // Get list of 'otherfiles'
     $otherfiles = array();
     if ($handle = opendir($templatedir)) {
         while (false !== ($file = readdir($handle))) {
             if (!array_search($file, $normalfiles)) {
                 if (!is_dir($templatedir . DIRECTORY_SEPARATOR . $file)) {
                     $otherfiles[] = array("name" => $file);
                 }
             }
         }
         closedir($handle);
     }
     $aData['clang'] = $this->getController()->lang;
     $aData['codelanguage'] = $codelanguage;
     $aData['highlighter'] = $highlighter;
     $aData['screens'] = $screens;
     $aData['templatename'] = $templatename;
     $aData['templates'] = $templates;
     $aData['editfile'] = $editfile;
     $aData['screenname'] = $screenname;
     $aData['tempdir'] = Yii::app()->getConfig('tempdir');
     $aData['usertemplaterootdir'] = Yii::app()->getConfig('usertemplaterootdir');
     $aViewUrls['templateeditorbar_view'][] = $aData;
     if ($showsummary) {
         $aViewUrls = array_merge($aViewUrls, $this->_templatesummary($templatename, $screenname, $editfile, $templates, $files, $cssfiles, $otherfiles, $myoutput));
     }
     App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'admin_core.js');
     return $aViewUrls;
 }
Exemplo n.º 16
0
 /**
  * Show dialogs and create a new tokens table
  */
 function _newtokentable($iSurveyId)
 {
     $clang = $this->getController()->lang;
     $aSurveyInfo = getSurveyInfo($iSurveyId);
     if (!Permission::model()->hasSurveyPermission($iSurveyId, 'surveysettings', 'update') && !Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'create')) {
         Yii::app()->session['flashmessage'] = $clang->gT("Tokens have not been initialised for this survey.");
         $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}"));
     }
     $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}');
     if ($bTokenExists) {
         Yii::app()->session['flashmessage'] = $clang->gT("Tokens already exist for this survey.");
         $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}"));
     }
     // The user have rigth to create token, then don't test right after
     Yii::import('application.helpers.admin.token_helper', true);
     if (Yii::app()->request->getQuery('createtable') == "Y") {
         createTokenTable($iSurveyId);
         LimeExpressionManager::SetDirtyFlag();
         // LimeExpressionManager needs to know about the new token table
         $this->_renderWrappedTemplate('token', array('message' => array('title' => $clang->gT("Token control"), 'message' => $clang->gT("A token table has been created for this survey.") . " (\"" . Yii::app()->db->tablePrefix . "tokens_{$iSurveyId}\")<br /><br />\n" . "<input type='submit' value='" . $clang->gT("Continue") . "' onclick=\"window.open('" . $this->getController()->createUrl("admin/tokens/sa/index/surveyid/{$iSurveyId}") . "', '_top')\" />\n")));
     } elseif (returnGlobal('restoretable') == "Y" && Yii::app()->request->getPost('oldtable')) {
         //Rebuild attributedescription value for the surveys table
         $table = Yii::app()->db->schema->getTable(Yii::app()->request->getPost('oldtable'));
         $fields = array_filter(array_keys($table->columns), 'filterForAttributes');
         $fieldcontents = $aSurveyInfo['attributedescriptions'];
         if (!is_array($fieldcontents)) {
             $fieldcontents = array();
         }
         foreach ($fields as $fieldname) {
             $name = $fieldname;
             if ($fieldname[10] == 'c') {
                 //This belongs to a cpdb attribute
                 $cpdbattid = substr($fieldname, 15);
                 $data = ParticipantAttributeName::model()->getAttributeName($cpdbattid, Yii::app()->session['adminlang']);
                 $name = $data['attribute_name'];
             }
             if (!isset($fieldcontents[$fieldname])) {
                 $fieldcontents[$fieldname] = array('description' => $name, 'mandatory' => 'N', 'show_register' => 'N');
             }
         }
         Survey::model()->updateByPk($iSurveyId, array('attributedescriptions' => serialize($fieldcontents)));
         Yii::app()->db->createCommand()->renameTable(Yii::app()->request->getPost('oldtable'), Yii::app()->db->tablePrefix . "tokens_" . intval($iSurveyId));
         Yii::app()->db->schema->getTable(Yii::app()->db->tablePrefix . "tokens_" . intval($iSurveyId), true);
         // Refresh schema cache just in case the table existed in the past
         //Check that the tokens table has the required fields
         TokenDynamic::model($iSurveyId)->checkColumns();
         //Add any survey_links from the renamed table
         SurveyLink::model()->rebuildLinksFromTokenTable($iSurveyId);
         $this->_renderWrappedTemplate('token', array('message' => array('title' => $clang->gT("Import old tokens"), 'message' => $clang->gT("A token table has been created for this survey and the old tokens were imported.") . " (\"" . Yii::app()->db->tablePrefix . "tokens_{$iSurveyId}" . "\")<br /><br />\n" . "<input type='submit' value='" . $clang->gT("Continue") . "' onclick=\"window.open('" . $this->getController()->createUrl("admin/tokens/sa/index/surveyid/{$iSurveyId}") . "', '_top')\" />\n")));
         LimeExpressionManager::SetDirtyFlag();
         // so that knows that token tables have changed
     } else {
         $this->getController()->loadHelper('database');
         $result = Yii::app()->db->createCommand(dbSelectTablesLike("{{old_tokens_" . intval($iSurveyId) . "_%}}"))->queryAll();
         $tcount = count($result);
         if ($tcount > 0) {
             foreach ($result as $rows) {
                 $oldlist[] = reset($rows);
             }
             $aData['oldlist'] = $oldlist;
         }
         $thissurvey = getSurveyInfo($iSurveyId);
         $aData['thissurvey'] = $thissurvey;
         $aData['surveyid'] = $iSurveyId;
         $aData['tcount'] = $tcount;
         $aData['databasetype'] = Yii::app()->db->getDriverName();
         $this->_renderWrappedTemplate('token', 'tokenwarning', $aData);
     }
 }
Exemplo n.º 17
0
 private function _saveSettings()
 {
     if ($_POST['action'] !== "globalsettingssave") {
         return;
     }
     if (!Permission::model()->hasGlobalPermission('settings', 'update')) {
         $this->getController()->redirect(array('/admin'));
     }
     Yii::app()->loadHelper('surveytranslator');
     $iPDFFontSize = sanitize_int($_POST['pdffontsize']);
     if ($iPDFFontSize < 1) {
         $iPDFFontSize = 9;
     }
     $iPDFLogoWidth = sanitize_int($_POST['pdflogowidth']);
     if ($iPDFLogoWidth < 1) {
         $iPDFLogoWidth = 50;
     }
     $maxemails = $_POST['maxemails'];
     if (sanitize_int($_POST['maxemails']) < 1) {
         $maxemails = 1;
     }
     $defaultlang = sanitize_languagecode($_POST['defaultlang']);
     $aRestrictToLanguages = explode(' ', sanitize_languagecodeS($_POST['restrictToLanguages']));
     if (!in_array($defaultlang, $aRestrictToLanguages)) {
         // Force default language in restrictToLanguages
         $aRestrictToLanguages[] = $defaultlang;
     }
     if (count(array_diff(array_keys(getLanguageData(false, Yii::app()->session['adminlang'])), $aRestrictToLanguages)) == 0) {
         $aRestrictToLanguages = '';
     } else {
         $aRestrictToLanguages = implode(' ', $aRestrictToLanguages);
     }
     setGlobalSetting('defaultlang', $defaultlang);
     setGlobalSetting('restrictToLanguages', trim($aRestrictToLanguages));
     setGlobalSetting('sitename', strip_tags($_POST['sitename']));
     setGlobalSetting('defaulthtmleditormode', sanitize_paranoid_string($_POST['defaulthtmleditormode']));
     setGlobalSetting('defaultquestionselectormode', sanitize_paranoid_string($_POST['defaultquestionselectormode']));
     setGlobalSetting('defaulttemplateeditormode', sanitize_paranoid_string($_POST['defaulttemplateeditormode']));
     if (!Yii::app()->getConfig('demoMode')) {
         $sTemplate = Yii::app()->getRequest()->getPost("defaulttemplate");
         if (array_key_exists($sTemplate, getTemplateList())) {
             setGlobalSetting('defaulttemplate', $sTemplate);
         }
     }
     setGlobalSetting('admintheme', sanitize_paranoid_string($_POST['admintheme']));
     setGlobalSetting('adminthemeiconsize', trim(file_get_contents(Yii::app()->getConfig("styledir") . DIRECTORY_SEPARATOR . sanitize_paranoid_string($_POST['admintheme']) . DIRECTORY_SEPARATOR . 'iconsize')));
     setGlobalSetting('emailmethod', strip_tags($_POST['emailmethod']));
     setGlobalSetting('emailsmtphost', strip_tags(returnGlobal('emailsmtphost')));
     if (returnGlobal('emailsmtppassword') != 'somepassword') {
         setGlobalSetting('emailsmtppassword', strip_tags(returnGlobal('emailsmtppassword')));
     }
     setGlobalSetting('bounceaccounthost', strip_tags(returnGlobal('bounceaccounthost')));
     setGlobalSetting('bounceaccounttype', strip_tags(returnGlobal('bounceaccounttype')));
     setGlobalSetting('bounceencryption', strip_tags(returnGlobal('bounceencryption')));
     setGlobalSetting('bounceaccountuser', strip_tags(returnGlobal('bounceaccountuser')));
     if (returnGlobal('bounceaccountpass') != 'enteredpassword') {
         setGlobalSetting('bounceaccountpass', strip_tags(returnGlobal('bounceaccountpass')));
     }
     setGlobalSetting('emailsmtpssl', sanitize_paranoid_string(Yii::app()->request->getPost('emailsmtpssl', '')));
     setGlobalSetting('emailsmtpdebug', sanitize_int(Yii::app()->request->getPost('emailsmtpdebug', '0')));
     setGlobalSetting('emailsmtpuser', strip_tags(returnGlobal('emailsmtpuser')));
     setGlobalSetting('filterxsshtml', strip_tags($_POST['filterxsshtml']));
     $warning = '';
     // make sure emails are valid before saving them
     if (Yii::app()->request->getPost('siteadminbounce', '') == '' || validateEmailAddress(Yii::app()->request->getPost('siteadminbounce'))) {
         setGlobalSetting('siteadminbounce', strip_tags(Yii::app()->request->getPost('siteadminbounce')));
     } else {
         $warning .= gT("Warning! Admin bounce email was not saved because it was not valid.") . '<br/>';
     }
     if (Yii::app()->request->getPost('siteadminemail', '') == '' || validateEmailAddress(Yii::app()->request->getPost('siteadminemail'))) {
         setGlobalSetting('siteadminemail', strip_tags(Yii::app()->request->getPost('siteadminemail')));
     } else {
         $warning .= gT("Warning! Admin email was not saved because it was not valid.") . '<br/>';
     }
     setGlobalSetting('siteadminname', strip_tags($_POST['siteadminname']));
     setGlobalSetting('shownoanswer', sanitize_int($_POST['shownoanswer']));
     setGlobalSetting('showxquestions', $_POST['showxquestions']);
     setGlobalSetting('showgroupinfo', $_POST['showgroupinfo']);
     setGlobalSetting('showqnumcode', $_POST['showqnumcode']);
     $repeatheadingstemp = (int) $_POST['repeatheadings'];
     if ($repeatheadingstemp == 0) {
         $repeatheadingstemp = 25;
     }
     setGlobalSetting('repeatheadings', $repeatheadingstemp);
     setGlobalSetting('maxemails', sanitize_int($maxemails));
     $iSessionExpirationTime = (int) $_POST['iSessionExpirationTime'];
     if ($iSessionExpirationTime == 0) {
         $iSessionExpirationTime = 7200;
     }
     setGlobalSetting('iSessionExpirationTime', $iSessionExpirationTime);
     setGlobalSetting('ipInfoDbAPIKey', $_POST['ipInfoDbAPIKey']);
     setGlobalSetting('pdffontsize', $iPDFFontSize);
     setGlobalSetting('pdfshowheader', $_POST['pdfshowheader']);
     setGlobalSetting('pdflogowidth', $iPDFLogoWidth);
     setGlobalSetting('pdfheadertitle', $_POST['pdfheadertitle']);
     setGlobalSetting('pdfheaderstring', $_POST['pdfheaderstring']);
     setGlobalSetting('googleMapsAPIKey', $_POST['googleMapsAPIKey']);
     setGlobalSetting('googleanalyticsapikey', $_POST['googleanalyticsapikey']);
     setGlobalSetting('googletranslateapikey', $_POST['googletranslateapikey']);
     setGlobalSetting('force_ssl', $_POST['force_ssl']);
     setGlobalSetting('surveyPreview_require_Auth', $_POST['surveyPreview_require_Auth']);
     setGlobalSetting('RPCInterface', $_POST['RPCInterface']);
     setGlobalSetting('rpc_publish_api', (bool) $_POST['rpc_publish_api']);
     $savetime = (double) $_POST['timeadjust'] * 60 . ' minutes';
     //makes sure it is a number, at least 0
     if (substr($savetime, 0, 1) != '-' && substr($savetime, 0, 1) != '+') {
         $savetime = '+' . $savetime;
     }
     setGlobalSetting('timeadjust', $savetime);
     setGlobalSetting('usercontrolSameGroupPolicy', strip_tags($_POST['usercontrolSameGroupPolicy']));
     Yii::app()->session['flashmessage'] = $warning . gT("Global settings were saved.");
     $url = htmlspecialchars_decode(Yii::app()->session['refurl']);
     if ($url) {
         Yii::app()->getController()->redirect($url);
     }
 }
Exemplo n.º 18
0
 /**
  * Process labels form data depending on $action.
  *
  * @access public
  * @return void
  */
 public function process()
 {
     if (Yii::app()->session['USER_RIGHT_SUPERADMIN'] == 1 || Yii::app()->session['USER_RIGHT_MANAGE_LABEL'] == 1) {
         if (isset($_POST['method']) && get_magic_quotes_gpc()) {
             $_POST['method'] = stripslashes($_POST['method']);
         }
         $action = returnGlobal('action');
         Yii::app()->loadHelper('admin/label');
         $lid = returnGlobal('lid');
         if ($action == "updateset") {
             updateset($lid);
             Yii::app()->session['flashmessage'] = Yii::app()->lang->gT("Label set properties sucessfully updated.");
         }
         if ($action == "insertlabelset") {
             $lid = insertlabelset();
         }
         if ($action == "modlabelsetanswers" || $action == "ajaxmodlabelsetanswers") {
             modlabelsetanswers($lid);
         }
         if ($action == "deletelabelset") {
             if (deletelabelset($lid)) {
                 Yii::app()->session['flashmessage'] = Yii::app()->lang->gT("Label set sucessfully deleted.");
                 $lid = 0;
             }
         }
         if ($lid) {
             $this->getController()->redirect($this->getController()->createUrl("admin/labels/sa/view/lid/" . $lid));
         } else {
             $this->getController()->redirect($this->getController()->createUrl("admin/labels/sa/view"));
         }
     }
 }
Exemplo n.º 19
0
 /**
  * Database::index()
  *
  * @param mixed $sa
  * @return
  */
 function index($sa = null)
 {
     $sAction = Yii::app()->request->getPost('action');
     $iSurveyID = isset($_POST['sid']) ? $_POST['sid'] : returnGlobal('sid');
     $iQuestionGroupID = returnGlobal('gid');
     $iQuestionID = returnGlobal('qid');
     // TODO: This variable seems to be never set or used in any function call?
     $sDBOutput = '';
     $oFixCKeditor = new LSYii_Validators();
     $oFixCKeditor->fixCKeditor = true;
     $oFixCKeditor->xssfilter = false;
     if ($sAction == "updatedefaultvalues" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'update')) {
         $aSurveyLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
         array_unshift($aSurveyLanguages, $sBaseLanguage);
         Question::model()->updateAll(array('same_default' => Yii::app()->request->getPost('samedefault') ? 1 : 0), 'sid=:sid ANd qid=:qid', array(':sid' => $iSurveyID, ':qid' => $iQuestionID));
         $arQuestion = Question::model()->findByAttributes(array('qid' => $iQuestionID));
         $sQuestionType = $arQuestion['type'];
         $aQuestionTypeList = getQuestionTypeList('', 'array');
         if ($aQuestionTypeList[$sQuestionType]['answerscales'] > 0 && $aQuestionTypeList[$sQuestionType]['subquestions'] == 0) {
             for ($iScaleID = 0; $iScaleID < $aQuestionTypeList[$sQuestionType]['answerscales']; $iScaleID++) {
                 foreach ($aSurveyLanguages as $sLanguage) {
                     if (!is_null(Yii::app()->request->getPost('defaultanswerscale_' . $iScaleID . '_' . $sLanguage))) {
                         $this->_updateDefaultValues($iQuestionID, 0, $iScaleID, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_' . $iScaleID . '_' . $sLanguage), true);
                     }
                     if (!is_null(Yii::app()->request->getPost('other_' . $iScaleID . '_' . $sLanguage))) {
                         $this->_updateDefaultValues($iQuestionID, 0, $iScaleID, 'other', $sLanguage, Yii::app()->request->getPost('other_' . $iScaleID . '_' . $sLanguage), true);
                     }
                 }
             }
         }
         if ($aQuestionTypeList[$sQuestionType]['subquestions'] > 0) {
             foreach ($aSurveyLanguages as $sLanguage) {
                 $arQuestions = Question::model()->findAllByAttributes(array('sid' => $iSurveyID, 'gid' => $iQuestionGroupID, 'parent_qid' => $iQuestionID, 'language' => $sLanguage, 'scale_id' => 0));
                 for ($iScaleID = 0; $iScaleID < $aQuestionTypeList[$sQuestionType]['subquestions']; $iScaleID++) {
                     foreach ($arQuestions as $aSubquestionrow) {
                         if (!is_null(Yii::app()->request->getPost('defaultanswerscale_' . $iScaleID . '_' . $sLanguage . '_' . $aSubquestionrow['qid']))) {
                             $this->_updateDefaultValues($iQuestionID, $aSubquestionrow['qid'], $iScaleID, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_' . $iScaleID . '_' . $sLanguage . '_' . $aSubquestionrow['qid']), true);
                         }
                     }
                 }
             }
         }
         if ($aQuestionTypeList[$sQuestionType]['answerscales'] == 0 && $aQuestionTypeList[$sQuestionType]['subquestions'] == 0) {
             foreach ($aSurveyLanguages as $sLanguage) {
                 // Qick and dirty insert for yes/no defaul value
                 // write the the selectbox option, or if "EM" is slected, this value to table
                 if ($sQuestionType == 'Y') {
                     /// value for all langs
                     if (Yii::app()->request->getPost('samedefault') == 1) {
                         $sLanguage = $aSurveyLanguages[0];
                         // turn
                     } else {
                         $sCurrentLang = $sLanguage;
                         // edit the next lines
                     }
                     if (Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage) == 'EM') {
                         // Case EM, write expression to database
                         $this->_updateDefaultValues($iQuestionID, 0, 0, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage . '_EM'), true);
                     } else {
                         // Case "other", write list value to database
                         $this->_updateDefaultValues($iQuestionID, 0, 0, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage), true);
                     }
                     ///// end yes/no
                 } else {
                     if (!is_null(Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage . '_0'))) {
                         $this->_updateDefaultValues($iQuestionID, 0, 0, '', $sLanguage, Yii::app()->request->getPost('defaultanswerscale_0_' . $sLanguage . '_0'), true);
                     }
                 }
             }
         }
         Yii::app()->session['flashmessage'] = gT("Default value settings were successfully saved.");
         LimeExpressionManager::SetDirtyFlag();
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             if (Yii::app()->request->getPost('close-after-save') === 'true') {
                 $this->getController()->redirect(array('admin/questions/sa/view/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
             }
             $this->getController()->redirect(array('admin/questions/sa/editdefaultvalues/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
         }
     }
     if ($sAction == "updateansweroptions" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'update')) {
         Yii::app()->loadHelper('database');
         $aSurveyLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
         array_unshift($aSurveyLanguages, $sBaseLanguage);
         $arQuestion = Question::model()->findByAttributes(array('qid' => $iQuestionID));
         $sQuestionType = $arQuestion['type'];
         // Checked)
         $aQuestionTypeList = getQuestionTypeList('', 'array');
         $iScaleCount = $aQuestionTypeList[$sQuestionType]['answerscales'];
         //First delete all answers
         Answer::model()->deleteAllByAttributes(array('qid' => $iQuestionID));
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
         for ($iScaleID = 0; $iScaleID < $iScaleCount; $iScaleID++) {
             $iMaxCount = (int) Yii::app()->request->getPost('answercount_' . $iScaleID);
             for ($iSortOrderID = 1; $iSortOrderID < $iMaxCount; $iSortOrderID++) {
                 $sCode = sanitize_paranoid_string(Yii::app()->request->getPost('code_' . $iSortOrderID . '_' . $iScaleID));
                 $iAssessmentValue = (int) Yii::app()->request->getPost('assessment_' . $iSortOrderID . '_' . $iScaleID);
                 foreach ($aSurveyLanguages as $sLanguage) {
                     $sAnswerText = Yii::app()->request->getPost('answer_' . $sLanguage . '_' . $iSortOrderID . '_' . $iScaleID);
                     // Fix bug with FCKEditor saving strange BR types
                     $sAnswerText = $oFixCKeditor->fixCKeditor($sAnswerText);
                     // Now we insert the answers
                     $iInsertCount = Answer::model()->insertRecords(array('code' => $sCode, 'answer' => $sAnswerText, 'qid' => $iQuestionID, 'sortorder' => $iSortOrderID, 'language' => $sLanguage, 'assessment_value' => $iAssessmentValue, 'scale_id' => $iScaleID));
                     if (!$iInsertCount) {
                         Yii::app()->setFlashMessage(gT("Failed to update answers"), 'error');
                     }
                 }
                 // Updating code (oldcode!==null) => update condition with the new code
                 $sOldCode = Yii::app()->request->getPost('oldcode_' . $iSortOrderID . '_' . $iScaleID);
                 if (isset($sOldCode) && $sCode !== $sOldCode) {
                     Condition::model()->updateAll(array('value' => $sCode), 'cqid=:cqid AND value=:value', array(':cqid' => $iQuestionID, ':value' => $sOldCode));
                 }
             }
             // for ($sortorderid=0;$sortorderid<$maxcount;$sortorderid++)
         }
         //  for ($scale_id=0;
         LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
         if (!Yii::app()->request->getPost('bFullPOST')) {
             Yii::app()->setFlashMessage(gT("Not all answer options were saved. This usually happens due to server limitations ( PHP setting max_input_vars) - please contact your system administrator."));
         } else {
             Yii::app()->session['flashmessage'] = gT("Answer options were successfully saved.");
         }
         LimeExpressionManager::SetDirtyFlag();
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             if (Yii::app()->request->getPost('close-after-save') === 'true') {
                 $this->getController()->redirect(array('admin/questions/sa/view/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
             }
             $this->getController()->redirect(array('/admin/questions/sa/answeroptions/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
         }
     }
     if ($sAction == "updatesubquestions" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'update')) {
         Yii::app()->loadHelper('database');
         $aSurveyLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
         array_unshift($aSurveyLanguages, $sBaseLanguage);
         $arQuestion = Question::model()->findByAttributes(array('qid' => $iQuestionID));
         $sQuestionType = $arQuestion['type'];
         // Checked
         $aQuestionTypeList = getQuestionTypeList('', 'array');
         $iScaleCount = $aQuestionTypeList[$sQuestionType]['subquestions'];
         // First delete any deleted ids
         $aDeletedQIDs = explode(' ', trim(Yii::app()->request->getPost('deletedqids')));
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
         $aDeletedQIDs = array_unique($aDeletedQIDs, SORT_NUMERIC);
         foreach ($aDeletedQIDs as $iDeletedQID) {
             $iDeletedQID = (int) $iDeletedQID;
             if ($iDeletedQID > 0) {
                 // don't remove undefined
                 $iInsertCount = Question::model()->deleteAllByAttributes(array('qid' => $iDeletedQID));
                 if (!$iInsertCount) {
                     Yii::app()->setFlashMessage(gT("Failed to delete answer"), 'error');
                 }
             }
         }
         //Determine ids by evaluating the hidden field
         $aRows = array();
         $aCodes = array();
         $aOldCodes = array();
         $aRelevance = array();
         foreach ($_POST as $sPOSTKey => $sPOSTValue) {
             $sPOSTKey = explode('_', $sPOSTKey);
             if ($sPOSTKey[0] == 'answer') {
                 $aRows[$sPOSTKey[3]][$sPOSTKey[1]][$sPOSTKey[2]] = $sPOSTValue;
             }
             if ($sPOSTKey[0] == 'code') {
                 $aCodes[$sPOSTKey[2]][] = $sPOSTValue;
             }
             if ($sPOSTKey[0] == 'oldcode') {
                 $aOldCodes[$sPOSTKey[2]][] = $sPOSTValue;
             }
             if ($sPOSTKey[0] == 'relevance') {
                 $aRelevance[$sPOSTKey[2]][] = $sPOSTValue;
             }
         }
         $aInsertQID = array();
         for ($iScaleID = 0; $iScaleID < $iScaleCount; $iScaleID++) {
             foreach ($aSurveyLanguages as $sLanguage) {
                 $iPosition = 0;
                 foreach ($aRows[$iScaleID][$sLanguage] as $subquestionkey => $subquestionvalue) {
                     if (substr($subquestionkey, 0, 3) != 'new') {
                         $oSubQuestion = Question::model()->find("qid=:qid AND language=:language", array(":qid" => $subquestionkey, ':language' => $sLanguage));
                         if (!is_object($oSubQuestion)) {
                             throw new CHttpException(502, "could not find subquestion {$subquestionkey} !");
                         }
                         $oSubQuestion->question_order = $iPosition + 1;
                         $oSubQuestion->title = $aCodes[$iScaleID][$iPosition];
                         $oSubQuestion->question = $subquestionvalue;
                         $oSubQuestion->scale_id = $iScaleID;
                         $oSubQuestion->relevance = isset($aRelevance[$iScaleID][$iPosition]) ? $aRelevance[$iScaleID][$iPosition] : "";
                     } else {
                         if (!isset($aInsertQID[$iScaleID][$iPosition])) {
                             $oSubQuestion = new Question();
                             $oSubQuestion->sid = $iSurveyID;
                             $oSubQuestion->gid = $iQuestionGroupID;
                             $oSubQuestion->question_order = $iPosition + 1;
                             $oSubQuestion->title = $aCodes[$iScaleID][$iPosition];
                             $oSubQuestion->question = $subquestionvalue;
                             $oSubQuestion->parent_qid = $iQuestionID;
                             $oSubQuestion->language = $sLanguage;
                             $oSubQuestion->scale_id = $iScaleID;
                             $oSubQuestion->relevance = isset($aRelevance[$iScaleID][$iPosition]) ? $aRelevance[$iScaleID][$iPosition] : "";
                         } else {
                             $oSubQuestion = Question::model()->find("qid=:qid AND language=:language", array(":qid" => $aInsertQID[$iScaleID][$iPosition], ':language' => $sLanguage));
                             if (!$oSubQuestion) {
                                 $oSubQuestion = new Question();
                             }
                             $oSubQuestion->sid = $iSurveyID;
                             $oSubQuestion->qid = $aInsertQID[$iScaleID][$iPosition];
                             $oSubQuestion->gid = $iQuestionGroupID;
                             $oSubQuestion->question_order = $iPosition + 1;
                             $oSubQuestion->title = $aCodes[$iScaleID][$iPosition];
                             $oSubQuestion->question = $subquestionvalue;
                             $oSubQuestion->parent_qid = $iQuestionID;
                             $oSubQuestion->language = $sLanguage;
                             $oSubQuestion->scale_id = $iScaleID;
                             $oSubQuestion->relevance = isset($aRelevance[$iScaleID][$iPosition]) ? $aRelevance[$iScaleID][$iPosition] : "";
                         }
                     }
                     if ($oSubQuestion->qid) {
                         switchMSSQLIdentityInsert('questions', true);
                         $bSubQuestionResult = $oSubQuestion->save();
                         switchMSSQLIdentityInsert('questions', false);
                     } else {
                         $bSubQuestionResult = $oSubQuestion->save();
                     }
                     if ($bSubQuestionResult) {
                         if (substr($subquestionkey, 0, 3) != 'new' && isset($aOldCodes[$iScaleID][$iPosition]) && $aCodes[$iScaleID][$iPosition] !== $aOldCodes[$iScaleID][$iPosition]) {
                             Condition::model()->updateAll(array('cfieldname' => '+' . $iSurveyID . 'X' . $iQuestionGroupID . 'X' . $iQuestionID . $aCodes[$iScaleID][$iPosition], 'value' => $aCodes[$iScaleID][$iPosition]), 'cqid=:cqid AND cfieldname=:cfieldname AND value=:value', array(':cqid' => $iQuestionID, ':cfieldname' => $iSurveyID . 'X' . $iQuestionGroupID . 'X' . $iQuestionID, ':value' => $aOldCodes[$iScaleID][$iPosition]));
                         }
                         if (!isset($aInsertQID[$iScaleID][$iPosition])) {
                             $aInsertQID[$iScaleID][$iPosition] = $oSubQuestion->qid;
                         }
                     } else {
                         $aErrors = $oSubQuestion->getErrors();
                         if (count($aErrors)) {
                             //$sErrorMessage=gT("Question could not be updated with this errors:");
                             foreach ($aErrors as $sAttribute => $aStringErrors) {
                                 foreach ($aStringErrors as $sStringErrors) {
                                     Yii::app()->setFlashMessage(sprintf(gT("Error on %s for subquestion %s: %s"), $sAttribute, $aCodes[$iScaleID][$iPosition], $sStringErrors), 'error');
                                 }
                             }
                         } else {
                             Yii::app()->setFlashMessage(sprintf(gT("Subquestions %s could not be updated."), $aCodes[$iScaleID][$iPosition]), 'error');
                         }
                     }
                     $iPosition++;
                 }
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
         // Do it only if there are no error ?
         if (!isset($aErrors) || !count($aErrors)) {
             if (!Yii::app()->request->getPost('bFullPOST')) {
                 Yii::app()->session['flashmessage'] = gT("Not all subquestions were saved. This usually happens due to server limitations ( PHP setting max_input_vars) - please contact your system administrator.");
             } else {
                 Yii::app()->session['flashmessage'] = gT("Subquestions were successfully saved.");
             }
         }
         //$action='editsubquestions';
         LimeExpressionManager::SetDirtyFlag();
         if ($sDBOutput != '') {
             echo 'Problem in database controller: ' . $sDBOutput;
         } else {
             if (Yii::app()->request->getPost('close-after-save') === 'true') {
                 $this->getController()->redirect(array('/admin/questions/sa/view/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
             }
             $this->getController()->redirect(array('/admin/questions/sa/subquestions/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
         }
     }
     /**
      * Insert / Copy question
      */
     if (in_array($sAction, array('insertquestion', 'copyquestion')) && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'create')) {
         $survey = Survey::model()->findByPk($iSurveyID);
         $sBaseLanguage = $survey->language;
         // Abort if survey is active
         if ($survey->active !== 'N') {
             Yii::app()->setFlashMessage(gT("You can't insert a new question when the survey is active."), 'error');
             $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/" . $survey->sid), "refresh");
         }
         if (strlen(Yii::app()->request->getPost('title')) < 1) {
             Yii::app()->setFlashMessage(gT("The question could not be added. You must enter at least a question code."), 'error');
         } else {
             // For Bootstrap Version usin YiiWheels switch :
             $_POST['mandatory'] = Yii::app()->request->getPost('mandatory') == '1' ? 'Y' : 'N';
             $_POST['other'] = Yii::app()->request->getPost('other') == '1' ? 'Y' : 'N';
             if (Yii::app()->request->getPost('questionposition', "") != "") {
                 $iQuestionOrder = intval(Yii::app()->request->getPost('questionposition'));
                 //Need to renumber all questions on or after this
                 $sQuery = "UPDATE {{questions}} SET question_order=question_order+1 WHERE gid=:gid AND question_order >= :order";
                 Yii::app()->db->createCommand($sQuery)->bindValues(array(':gid' => $iQuestionGroupID, ':order' => $iQuestionOrder))->query();
             } else {
                 $iQuestionOrder = getMaxQuestionOrder($iQuestionGroupID, $iSurveyID);
                 $iQuestionOrder++;
             }
             $sQuestionText = Yii::app()->request->getPost('question_' . $sBaseLanguage, '');
             $sQuestionHelp = Yii::app()->request->getPost('help_' . $sBaseLanguage, '');
             // Fix bug with FCKEditor saving strange BR types : in rules ?
             $sQuestionText = $oFixCKeditor->fixCKeditor($sQuestionText);
             $sQuestionHelp = $oFixCKeditor->fixCKeditor($sQuestionHelp);
             $iQuestionID = 0;
             $oQuestion = new Question();
             $oQuestion->sid = $iSurveyID;
             $oQuestion->gid = $iQuestionGroupID;
             $oQuestion->type = Yii::app()->request->getPost('type');
             $oQuestion->title = Yii::app()->request->getPost('title');
             $oQuestion->question = $sQuestionText;
             $oQuestion->preg = Yii::app()->request->getPost('preg');
             $oQuestion->help = $sQuestionHelp;
             $oQuestion->other = Yii::app()->request->getPost('other');
             // For Bootstrap Version usin YiiWheels switch :
             $oQuestion->mandatory = Yii::app()->request->getPost('mandatory');
             $oQuestion->other = Yii::app()->request->getPost('other');
             $oQuestion->relevance = Yii::app()->request->getPost('relevance');
             $oQuestion->question_order = $iQuestionOrder;
             $oQuestion->language = $sBaseLanguage;
             $oQuestion->save();
             if ($oQuestion) {
                 $iQuestionID = $oQuestion->qid;
             }
             $aErrors = $oQuestion->getErrors();
             if (count($aErrors)) {
                 foreach ($aErrors as $sAttribute => $aStringErrors) {
                     foreach ($aStringErrors as $sStringErrors) {
                         Yii::app()->setFlashMessage(sprintf(gT("Question could not be created with error on %s: %s"), $sAttribute, $sStringErrors), 'error');
                     }
                 }
             }
             // Add other languages
             if ($iQuestionID) {
                 $addlangs = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
                 foreach ($addlangs as $alang) {
                     if ($alang != "") {
                         $langqid = 0;
                         $oQuestion = new Question();
                         $oQuestion->qid = $iQuestionID;
                         $oQuestion->sid = $iSurveyID;
                         $oQuestion->gid = $iQuestionGroupID;
                         $oQuestion->type = Yii::app()->request->getPost('type');
                         $oQuestion->title = Yii::app()->request->getPost('title');
                         $oQuestion->question = Yii::app()->request->getPost('question_' . $alang);
                         $oQuestion->preg = Yii::app()->request->getPost('preg');
                         $oQuestion->help = Yii::app()->request->getPost('help_' . $alang);
                         $oQuestion->other = Yii::app()->request->getPost('other');
                         $oQuestion->mandatory = Yii::app()->request->getPost('mandatory');
                         $oQuestion->relevance = Yii::app()->request->getPost('relevance');
                         $oQuestion->question_order = $iQuestionOrder;
                         $oQuestion->language = $alang;
                         switchMSSQLIdentityInsert('questions', true);
                         // Not sure for this one ?
                         $oQuestion->save();
                         switchMSSQLIdentityInsert('questions', false);
                         if ($oQuestion) {
                             $langqid = $oQuestion->qid;
                         }
                         $aErrors = $oQuestion->getErrors();
                         if (count($aErrors)) {
                             foreach ($aErrors as $sAttribute => $aStringErrors) {
                                 foreach ($aStringErrors as $sStringErrors) {
                                     Yii::app()->setFlashMessage(sprintf(gT("Question in language %s could not be created with error on %s: %s"), $alang, $sAttribute, $sStringErrors), 'error');
                                 }
                             }
                         }
                         #                            if (!$langqid)
                         #                            {
                         #                                Yii::app()->setFlashMessage(gT("Question in language %s could not be created."),'error');
                         #                            }
                     }
                 }
             }
             if (!$iQuestionID) {
                 Yii::app()->setFlashMessage(gT("Question could not be created."), 'error');
             } else {
                 /**
                  *
                  * Copy Question
                  *
                  */
                 if ($sAction == 'copyquestion') {
                     if (returnGlobal('copysubquestions') == "Y") {
                         $aSQIDMappings = array();
                         $r1 = Question::model()->getSubQuestions(returnGlobal('oldqid'));
                         $aSubQuestions = $r1->readAll();
                         foreach ($aSubQuestions as $qr1) {
                             $qr1['parent_qid'] = $iQuestionID;
                             if (isset($aSQIDMappings[$qr1['qid']])) {
                                 $qr1['qid'] = $aSQIDMappings[$qr1['qid']];
                             } else {
                                 $oldqid = $qr1['qid'];
                                 unset($qr1['qid']);
                             }
                             $qr1['gid'] = $iQuestionGroupID;
                             $iInsertID = Question::model()->insertRecords($qr1);
                             if (!isset($qr1['qid'])) {
                                 $aSQIDMappings[$oldqid] = $iInsertID;
                             }
                         }
                     }
                     if (returnGlobal('copyanswers') == "Y") {
                         $r1 = Answer::model()->getAnswers(returnGlobal('oldqid'));
                         $aAnswerOptions = $r1->readAll();
                         foreach ($aAnswerOptions as $qr1) {
                             Answer::model()->insertRecords(array('qid' => $iQuestionID, 'code' => $qr1['code'], 'answer' => $qr1['answer'], 'assessment_value' => $qr1['assessment_value'], 'sortorder' => $qr1['sortorder'], 'language' => $qr1['language'], 'scale_id' => $qr1['scale_id']));
                         }
                     }
                     /**
                      * Copy attribute
                      */
                     if (returnGlobal('copyattributes') == "Y") {
                         $oOldAttributes = QuestionAttribute::model()->findAll("qid=:qid", array("qid" => returnGlobal('oldqid')));
                         foreach ($oOldAttributes as $oOldAttribute) {
                             $attribute = new QuestionAttribute();
                             $attribute->qid = $iQuestionID;
                             $attribute->value = $oOldAttribute->value;
                             $attribute->attribute = $oOldAttribute->attribute;
                             $attribute->language = $oOldAttribute->language;
                             $attribute->save();
                         }
                     }
                     // Since 2.5, user can edit attribute while copying
                     $qattributes = questionAttributes();
                     $validAttributes = $qattributes[Yii::app()->request->getPost('type')];
                     $aLanguages = array_merge(array(Survey::model()->findByPk($iSurveyID)->language), Survey::model()->findByPk($iSurveyID)->additionalLanguages);
                     foreach ($validAttributes as $validAttribute) {
                         if ($validAttribute['i18n']) {
                             foreach ($aLanguages as $sLanguage) {
                                 $value = Yii::app()->request->getPost($validAttribute['name'] . '_' . $sLanguage);
                                 $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID, 'language' => $sLanguage));
                                 if (count($iInsertCount) > 0) {
                                     if ($value != '') {
                                         QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                                     } else {
                                         QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                                     }
                                 } elseif ($value != '') {
                                     $attribute = new QuestionAttribute();
                                     $attribute->qid = $iQuestionID;
                                     $attribute->value = $value;
                                     $attribute->attribute = $validAttribute['name'];
                                     $attribute->language = $sLanguage;
                                     $attribute->save();
                                 }
                             }
                         } else {
                             $value = Yii::app()->request->getPost($validAttribute['name']);
                             if ($validAttribute['name'] == 'multiflexible_step' && trim($value) != '') {
                                 $value = floatval($value);
                                 if ($value == 0) {
                                     $value = 1;
                                 }
                             }
                             $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID));
                             if (count($iInsertCount) > 0) {
                                 if ($value != $validAttribute['default'] && trim($value) != "") {
                                     QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                                 } else {
                                     QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                                 }
                             } elseif ($value != $validAttribute['default'] && trim($value) != "") {
                                 $attribute = new QuestionAttribute();
                                 $attribute->qid = $iQuestionID;
                                 $attribute->value = $value;
                                 $attribute->attribute = $validAttribute['name'];
                                 $attribute->save();
                             }
                         }
                     }
                 } else {
                     $qattributes = questionAttributes();
                     $validAttributes = $qattributes[Yii::app()->request->getPost('type')];
                     $aLanguages = array_merge(array(Survey::model()->findByPk($iSurveyID)->language), Survey::model()->findByPk($iSurveyID)->additionalLanguages);
                     foreach ($validAttributes as $validAttribute) {
                         if ($validAttribute['i18n']) {
                             foreach ($aLanguages as $sLanguage) {
                                 $value = Yii::app()->request->getPost($validAttribute['name'] . '_' . $sLanguage);
                                 $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID, 'language' => $sLanguage));
                                 if (count($iInsertCount) > 0) {
                                     if ($value != '') {
                                         QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                                     } else {
                                         QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                                     }
                                 } elseif ($value != '') {
                                     $attribute = new QuestionAttribute();
                                     $attribute->qid = $iQuestionID;
                                     $attribute->value = $value;
                                     $attribute->attribute = $validAttribute['name'];
                                     $attribute->language = $sLanguage;
                                     $attribute->save();
                                 }
                             }
                         } else {
                             $value = Yii::app()->request->getPost($validAttribute['name']);
                             if ($validAttribute['name'] == 'multiflexible_step' && trim($value) != '') {
                                 $value = floatval($value);
                                 if ($value == 0) {
                                     $value = 1;
                                 }
                             }
                             $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID));
                             if (count($iInsertCount) > 0) {
                                 if ($value != $validAttribute['default'] && trim($value) != "") {
                                     QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                                 } else {
                                     QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                                 }
                             } elseif ($value != $validAttribute['default'] && trim($value) != "") {
                                 $attribute = new QuestionAttribute();
                                 $attribute->qid = $iQuestionID;
                                 $attribute->value = $value;
                                 $attribute->attribute = $validAttribute['name'];
                                 $attribute->save();
                             }
                         }
                     }
                 }
                 Question::model()->updateQuestionOrder($iQuestionGroupID, $iSurveyID);
                 Yii::app()->session['flashmessage'] = gT("Question was successfully added.");
             }
         }
         LimeExpressionManager::SetDirtyFlag();
         // so refreshes syntax highlighting
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             //admin/survey/sa/view/surveyid/
             $this->getController()->redirect(array('admin/questions/sa/view/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
         }
     }
     /**
      * Update question
      */
     if ($sAction == "updatequestion" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'update')) {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
         $cqr = Question::model()->findByAttributes(array('qid' => $iQuestionID));
         $oldtype = $cqr['type'];
         $oldgid = $cqr['gid'];
         $survey = Survey::model()->findByPk($iSurveyID);
         // If the survey is activate the question type may not be changed
         if ($survey->active !== 'N') {
             $sQuestionType = $oldtype;
         } else {
             $sQuestionType = Yii::app()->request->getPost('type');
         }
         // Remove invalid question attributes on saving
         $qattributes = questionAttributes();
         $criteria = new CDbCriteria();
         $criteria->compare('qid', $iQuestionID);
         if (isset($qattributes[$sQuestionType])) {
             $validAttributes = $qattributes[$sQuestionType];
             foreach ($validAttributes as $validAttribute) {
                 $criteria->compare('attribute', '<>' . $validAttribute['name']);
             }
         }
         QuestionAttribute::model()->deleteAll($criteria);
         $aLanguages = array_merge(array(Survey::model()->findByPk($iSurveyID)->language), Survey::model()->findByPk($iSurveyID)->additionalLanguages);
         //now save all valid attributes
         $validAttributes = $qattributes[$sQuestionType];
         foreach ($validAttributes as $validAttribute) {
             if ($validAttribute['i18n']) {
                 foreach ($aLanguages as $sLanguage) {
                     // TODO sanitise XSS
                     $value = Yii::app()->request->getPost($validAttribute['name'] . '_' . $sLanguage);
                     $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID, 'language' => $sLanguage));
                     if (count($iInsertCount) > 0) {
                         if ($value != '') {
                             QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                         } else {
                             QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid AND language=:language', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID, ':language' => $sLanguage));
                         }
                     } elseif ($value != '') {
                         $attribute = new QuestionAttribute();
                         $attribute->qid = $iQuestionID;
                         $attribute->value = $value;
                         $attribute->attribute = $validAttribute['name'];
                         $attribute->language = $sLanguage;
                         $attribute->save();
                     }
                 }
             } else {
                 $value = Yii::app()->request->getPost($validAttribute['name']);
                 if ($validAttribute['name'] == 'multiflexible_step' && trim($value) != '') {
                     $value = floatval($value);
                     if ($value == 0) {
                         $value = 1;
                     }
                 }
                 $iInsertCount = QuestionAttribute::model()->findAllByAttributes(array('attribute' => $validAttribute['name'], 'qid' => $iQuestionID));
                 if (count($iInsertCount) > 0) {
                     if ($value != $validAttribute['default'] && trim($value) != "") {
                         QuestionAttribute::model()->updateAll(array('value' => $value), 'attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                     } else {
                         QuestionAttribute::model()->deleteAll('attribute=:attribute AND qid=:qid', array(':attribute' => $validAttribute['name'], ':qid' => $iQuestionID));
                     }
                 } elseif ($value != $validAttribute['default'] && trim($value) != "") {
                     $attribute = new QuestionAttribute();
                     $attribute->qid = $iQuestionID;
                     $attribute->value = $value;
                     $attribute->attribute = $validAttribute['name'];
                     $attribute->save();
                 }
             }
         }
         $aQuestionTypeList = getQuestionTypeList('', 'array');
         // These are the questions types that have no answers and therefore we delete the answer in that case
         $iAnswerScales = $aQuestionTypeList[$sQuestionType]['answerscales'];
         $iSubquestionScales = $aQuestionTypeList[$sQuestionType]['subquestions'];
         // These are the questions types that have the other option therefore we set everything else to 'No Other'
         if ($sQuestionType != "L" && $sQuestionType != "!" && $sQuestionType != "P" && $sQuestionType != "M") {
             $_POST['other'] = 'N';
         }
         // These are the questions types that have no validation - so zap it accordingly
         if ($sQuestionType == "!" || $sQuestionType == "L" || $sQuestionType == "M" || $sQuestionType == "P" || $sQuestionType == "F" || $sQuestionType == "H" || $sQuestionType == "X" || $sQuestionType == "") {
             $_POST['preg'] = '';
         }
         // For Bootstrap Version usin YiiWheels switch :
         $_POST['mandatory'] = Yii::app()->request->getPost('mandatory') == '1' ? 'Y' : 'N';
         $_POST['other'] = Yii::app()->request->getPost('other') == '1' ? 'Y' : 'N';
         // These are the questions types that have no mandatory property - so zap it accordingly
         if ($sQuestionType == "X" || $sQuestionType == "|") {
             $_POST['mandatory'] = 'N';
         }
         if ($oldtype != $sQuestionType) {
             // TMSW Condition->Relevance:  Do similar check via EM, but do allow such a change since will be easier to modify relevance
             //Make sure there are no conditions based on this question, since we are changing the type
             $ccresult = Condition::model()->findAllByAttributes(array('cqid' => $iQuestionID));
             $cccount = count($ccresult);
             foreach ($ccresult as $ccr) {
                 $qidarray[] = $ccr['qid'];
             }
             if (isset($qidarray) && $qidarray) {
                 $qidlist = implode(", ", $qidarray);
             }
         }
         if (isset($cccount) && $cccount) {
             Yii::app()->setFlashMessage(gT("Question could not be updated. There are conditions for other questions that rely on the answers to this question and changing the type will cause problems. You must delete these conditions  before you can change the type of this question."), 'error');
         } else {
             if (isset($iQuestionGroupID) && $iQuestionGroupID != "") {
                 //                    $array_result=checkMoveQuestionConstraintsForConditions(sanitize_int($surveyid),sanitize_int($qid), sanitize_int($gid));
                 //                    // If there is no blocking conditions that could prevent this move
                 //
                 //                    if (is_null($array_result['notAbove']) && is_null($array_result['notBelow']))
                 //                    {
                 $aSurveyLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
                 $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
                 array_push($aSurveyLanguages, $sBaseLanguage);
                 foreach ($aSurveyLanguages as $qlang) {
                     if (isset($qlang) && $qlang != "") {
                         // &eacute; to é and &amp; to & : really needed ? Why not for answers ? (130307)
                         $sQuestionText = Yii::app()->request->getPost('question_' . $qlang, '');
                         $sQuestionHelp = Yii::app()->request->getPost('help_' . $qlang, '');
                         // Fix bug with FCKEditor saving strange BR types : in rules ?
                         $sQuestionText = $oFixCKeditor->fixCKeditor($sQuestionText);
                         $sQuestionHelp = $oFixCKeditor->fixCKeditor($sQuestionHelp);
                         $udata = array('type' => $sQuestionType, 'title' => Yii::app()->request->getPost('title'), 'question' => $sQuestionText, 'preg' => Yii::app()->request->getPost('preg'), 'help' => $sQuestionHelp, 'gid' => $iQuestionGroupID, 'other' => Yii::app()->request->getPost('other'), 'mandatory' => Yii::app()->request->getPost('mandatory'), 'relevance' => Yii::app()->request->getPost('relevance'));
                         // Update question module
                         if (Yii::app()->request->getPost('module_name') != '') {
                             // The question module is not empty. So it's an external question module.
                             $udata['modulename'] = Yii::app()->request->getPost('module_name');
                         } else {
                             // If it was a module before, we must
                             $udata['modulename'] = '';
                         }
                         if ($oldgid != $iQuestionGroupID) {
                             if (getGroupOrder($iSurveyID, $oldgid) > getGroupOrder($iSurveyID, $iQuestionGroupID)) {
                                 // TMSW Condition->Relevance:  What is needed here?
                                 // Moving question to a 'upper' group
                                 // insert question at the end of the destination group
                                 // this prevent breaking conditions if the target qid is in the dest group
                                 $insertorder = getMaxQuestionOrder($iQuestionGroupID, $iSurveyID) + 1;
                                 $udata = array_merge($udata, array('question_order' => $insertorder));
                             } else {
                                 // Moving question to a 'lower' group
                                 // insert question at the beginning of the destination group
                                 shiftOrderQuestions($iSurveyID, $iQuestionGroupID, 1);
                                 // makes 1 spare room for new question at top of dest group
                                 $udata = array_merge($udata, array('question_order' => 0));
                             }
                         }
                         //$condn = array('sid' => $surveyid, 'qid' => $qid, 'language' => $qlang);
                         $oQuestion = Question::model()->findByPk(array("qid" => $iQuestionID, 'language' => $qlang));
                         foreach ($udata as $k => $v) {
                             $oQuestion->{$k} = $v;
                         }
                         $uqresult = $oQuestion->save();
                         //($uqquery); // or safeDie ("Error Update Question: ".$uqquery."<br />");  // Checked)
                         if (!$uqresult) {
                             $bOnError = true;
                             $aErrors = $oQuestion->getErrors();
                             if (count($aErrors)) {
                                 foreach ($aErrors as $sAttribute => $aStringErrors) {
                                     foreach ($aStringErrors as $sStringErrors) {
                                         Yii::app()->setFlashMessage(sprintf(gT("Question could not be updated with error on %s: %s"), $sAttribute, $sStringErrors), 'error');
                                     }
                                 }
                             } else {
                                 Yii::app()->setFlashMessage(gT("Question could not be updated."), 'error');
                             }
                         }
                     }
                 }
                 // Update the group ID on subquestions, too
                 if ($oldgid != $iQuestionGroupID) {
                     Question::model()->updateAll(array('gid' => $iQuestionGroupID), 'qid=:qid and parent_qid>0', array(':qid' => $iQuestionID));
                     // if the group has changed then fix the sortorder of old and new group
                     Question::model()->updateQuestionOrder($oldgid, $iSurveyID);
                     Question::model()->updateQuestionOrder($iQuestionGroupID, $iSurveyID);
                     // If some questions have conditions set on this question's answers
                     // then change the cfieldname accordingly
                     fixMovedQuestionConditions($iQuestionID, $oldgid, $iQuestionGroupID);
                 }
                 // Update subquestions
                 if ($oldtype != $sQuestionType) {
                     Question::model()->updateAll(array('type' => $sQuestionType), 'parent_qid=:qid', array(':qid' => $iQuestionID));
                 }
                 // Update subquestions if question module
                 if (Yii::app()->request->getPost('module_name') != '') {
                     // The question module is not empty. So it's an external question module.
                     Question::model()->updateAll(array('modulename' => Yii::app()->request->getPost('module_name')), 'parent_qid=:qid', array(':qid' => $iQuestionID));
                 } else {
                     // If it was a module before, we must
                     Question::model()->updateAll(array('modulename' => ''), 'parent_qid=:qid', array(':qid' => $iQuestionID));
                 }
                 Answer::model()->deleteAllByAttributes(array('qid' => $iQuestionID), 'scale_id >= :scale_id', array(':scale_id' => $iAnswerScales));
                 // Remove old subquestion scales
                 Question::model()->deleteAllByAttributes(array('parent_qid' => $iQuestionID), 'scale_id >= :scale_id', array(':scale_id' => $iSubquestionScales));
                 if (!isset($bOnError) || !$bOnError) {
                     // This really a quick hack and need a better system
                     Yii::app()->setFlashMessage(gT("Question was successfully saved."));
                 }
                 //                    }
                 //                    else
                 //                    {
                 //
                 //                        // There are conditions constraints: alert the user
                 //                        $errormsg="";
                 //                        if (!is_null($array_result['notAbove']))
                 //                        {
                 //                            $errormsg.=gT("This question relies on other question's answers and can't be moved above groupId:","js")
                 //                            . " " . $array_result['notAbove'][0][0] . " " . gT("in position","js")." ".$array_result['notAbove'][0][1]."\\n"
                 //                            . gT("See conditions:")."\\n";
                 //
                 //                            foreach ($array_result['notAbove'] as $notAboveCond)
                 //                            {
                 //                                $errormsg.="- cid:". $notAboveCond[3]."\\n";
                 //                            }
                 //
                 //                        }
                 //                        if (!is_null($array_result['notBelow']))
                 //                        {
                 //                            $errormsg.=gT("Some questions rely on this question's answers. You can't move this question below groupId:","js")
                 //                            . " " . $array_result['notBelow'][0][0] . " " . gT("in position","js")." ".$array_result['notBelow'][0][1]."\\n"
                 //                            . gT("See conditions:")."\\n";
                 //
                 //                            foreach ($array_result['notBelow'] as $notBelowCond)
                 //                            {
                 //                                $errormsg.="- cid:". $notBelowCond[3]."\\n";
                 //                            }
                 //                        }
                 //
                 //                        $databaseoutput .= "<script type=\"text/javascript\">\n<!--\n alert(\"$errormsg\")\n //-->\n</script>\n";
                 //                        $gid= $oldgid; // group move impossible ==> keep display on oldgid
                 //                    }
             } else {
                 Yii::app()->setFlashMessage(gT("Question could not be updated"), 'error');
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             $closeAfterSave = Yii::app()->request->getPost('close-after-save') === 'true';
             if ($closeAfterSave) {
                 // Redirect to summary
                 $this->getController()->redirect(array('admin/questions/sa/view/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
             } else {
                 // Redirect to edit
                 $this->getController()->redirect(array('admin/questions/sa/editquestion/surveyid/' . $iSurveyID . '/gid/' . $iQuestionGroupID . '/qid/' . $iQuestionID));
                 // This works too: $this->getController()->redirect(Yii::app()->request->urlReferrer);
             }
         }
     }
     /**
      * updatesurveylocalesettings
      */
     if ($sAction == "updatesurveylocalesettings" && Permission::model()->hasSurveyPermission($iSurveyID, 'surveylocale', 'update')) {
         $languagelist = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
         $languagelist[] = Survey::model()->findByPk($iSurveyID)->language;
         Yii::app()->loadHelper('database');
         foreach ($languagelist as $langname) {
             if ($langname) {
                 $url = Yii::app()->request->getPost('url_' . $langname);
                 if ($url == 'http://') {
                     $url = "";
                 }
                 $sURLDescription = html_entity_decode(Yii::app()->request->getPost('urldescrip_' . $langname), ENT_QUOTES, "UTF-8");
                 $sURL = html_entity_decode(Yii::app()->request->getPost('url_' . $langname), ENT_QUOTES, "UTF-8");
                 // Fix bug with FCKEditor saving strange BR types
                 $short_title = Yii::app()->request->getPost('short_title_' . $langname);
                 $description = Yii::app()->request->getPost('description_' . $langname);
                 $welcome = Yii::app()->request->getPost('welcome_' . $langname);
                 $endtext = Yii::app()->request->getPost('endtext_' . $langname);
                 $short_title = $oFixCKeditor->fixCKeditor($short_title);
                 $description = $oFixCKeditor->fixCKeditor($description);
                 $welcome = $oFixCKeditor->fixCKeditor($welcome);
                 $endtext = $oFixCKeditor->fixCKeditor($endtext);
                 $data = array('surveyls_title' => $short_title, 'surveyls_description' => $description, 'surveyls_welcometext' => $welcome, 'surveyls_endtext' => $endtext, 'surveyls_url' => $sURL, 'surveyls_urldescription' => $sURLDescription, 'surveyls_dateformat' => Yii::app()->request->getPost('dateformat_' . $langname), 'surveyls_numberformat' => Yii::app()->request->getPost('numberformat_' . $langname));
                 $SurveyLanguageSetting = SurveyLanguageSetting::model()->findByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $langname));
                 $SurveyLanguageSetting->attributes = $data;
                 $SurveyLanguageSetting->save();
                 // save the change to database
             }
         }
         //Yii::app()->session['flashmessage'] = gT("Survey text elements successfully saved.");
         ////////////////////////////////////////////////////////////////////////////////////
         // General settings (copy / paste from surveyadmin::update)
         // Preload survey
         $oSurvey = Survey::model()->findByPk($iSurveyID);
         // Save plugin settings.
         $pluginSettings = App()->request->getPost('plugin', array());
         foreach ($pluginSettings as $plugin => $settings) {
             $settingsEvent = new PluginEvent('newSurveySettings');
             $settingsEvent->set('settings', $settings);
             $settingsEvent->set('survey', $iSurveyID);
             App()->getPluginManager()->dispatchEvent($settingsEvent, $plugin);
         }
         /* Start to fix some param before save (TODO : use models directly ?) */
         /* Date management */
         Yii::app()->loadHelper('surveytranslator');
         $formatdata = getDateFormatData(Yii::app()->session['dateformat']);
         Yii::app()->loadLibrary('Date_Time_Converter');
         $startdate = App()->request->getPost('startdate');
         if (trim($startdate) == "") {
             $startdate = null;
         } else {
             Yii::app()->loadLibrary('Date_Time_Converter');
             $datetimeobj = new date_time_converter($startdate, $formatdata['phpdate'] . ' H:i');
             //new Date_Time_Converter($startdate,$formatdata['phpdate'].' H:i');
             $startdate = $datetimeobj->convert("Y-m-d H:i:s");
         }
         $expires = App()->request->getPost('expires');
         if (trim($expires) == "") {
             $expires = null;
         } else {
             $datetimeobj = new date_time_converter($expires, $formatdata['phpdate'] . ' H:i');
             //new Date_Time_Converter($expires, $formatdata['phpdate'].' H:i');
             $expires = $datetimeobj->convert("Y-m-d H:i:s");
         }
         // We have $oSurvey : update and save it
         $oSurvey->owner_id = Yii::app()->request->getPost('owner_id');
         $oSurvey->admin = Yii::app()->request->getPost('admin');
         $oSurvey->expires = $expires;
         $oSurvey->startdate = $startdate;
         $oSurvey->faxto = App()->request->getPost('faxto');
         $oSurvey->format = App()->request->getPost('format');
         $oSurvey->template = Yii::app()->request->getPost('template');
         $oSurvey->assessments = App()->request->getPost('assessments');
         $oSurvey->additional_languages = Yii::app()->request->getPost('languageids');
         if ($oSurvey->active != 'Y') {
             $oSurvey->anonymized = App()->request->getPost('anonymized');
             $oSurvey->savetimings = App()->request->getPost('savetimings');
             $oSurvey->datestamp = App()->request->getPost('datestamp');
             $oSurvey->ipaddr = App()->request->getPost('ipaddr');
             $oSurvey->refurl = App()->request->getPost('refurl');
         }
         $oSurvey->publicgraphs = App()->request->getPost('publicgraphs');
         $oSurvey->usecookie = App()->request->getPost('usecookie');
         $oSurvey->allowregister = App()->request->getPost('allowregister');
         $oSurvey->allowsave = App()->request->getPost('allowsave');
         $oSurvey->navigationdelay = App()->request->getPost('navigationdelay');
         $oSurvey->printanswers = App()->request->getPost('printanswers');
         $oSurvey->publicstatistics = App()->request->getPost('publicstatistics');
         $oSurvey->autoredirect = App()->request->getPost('autoredirect');
         $oSurvey->showxquestions = App()->request->getPost('showxquestions');
         $oSurvey->showgroupinfo = App()->request->getPost('showgroupinfo');
         $oSurvey->showqnumcode = App()->request->getPost('showqnumcode');
         $oSurvey->shownoanswer = App()->request->getPost('shownoanswer');
         $oSurvey->showwelcome = App()->request->getPost('showwelcome');
         $oSurvey->allowprev = App()->request->getPost('allowprev');
         $oSurvey->questionindex = App()->request->getPost('questionindex');
         $oSurvey->nokeyboard = App()->request->getPost('nokeyboard');
         $oSurvey->showprogress = App()->request->getPost('showprogress');
         $oSurvey->listpublic = App()->request->getPost('public');
         $oSurvey->htmlemail = App()->request->getPost('htmlemail');
         $oSurvey->sendconfirmation = App()->request->getPost('sendconfirmation');
         $oSurvey->tokenanswerspersistence = App()->request->getPost('tokenanswerspersistence');
         $oSurvey->alloweditaftercompletion = App()->request->getPost('alloweditaftercompletion');
         $oSurvey->usecaptcha = Survey::transcribeCaptchaOptions();
         $oSurvey->emailresponseto = App()->request->getPost('emailresponseto');
         $oSurvey->emailnotificationto = App()->request->getPost('emailnotificationto');
         $oSurvey->googleanalyticsapikey = App()->request->getPost('googleanalyticsapikey');
         $oSurvey->googleanalyticsstyle = App()->request->getPost('googleanalyticsstyle');
         $oSurvey->tokenlength = App()->request->getPost('tokenlength');
         $oSurvey->adminemail = App()->request->getPost('adminemail');
         $oSurvey->bounce_email = App()->request->getPost('bounce_email');
         if ($oSurvey->save()) {
             Yii::app()->setFlashMessage(gT("Survey settings were successfully saved."));
         } else {
             Yii::app()->setFlashMessage(gT("Survey could not be updated."), "error");
             tracevar($oSurvey->getErrors());
         }
         /* Reload $oSurvey (language are fixed : need it ?) */
         $oSurvey = Survey::model()->findByPk($iSurveyID);
         /* Delete removed language cleanLanguagesFromSurvey do it already why redo it (cleanLanguagesFromSurvey must be moved to model) ?*/
         $aAvailableLanguage = $oSurvey->getAllLanguages();
         $oCriteria = new CDbCriteria();
         $oCriteria->compare('surveyls_survey_id', $iSurveyID);
         $oCriteria->addNotInCondition('surveyls_language', $aAvailableLanguage);
         SurveyLanguageSetting::model()->deleteAll($oCriteria);
         /* Add new language fixLanguageConsistency do it ?*/
         foreach ($oSurvey->additionalLanguages as $sLang) {
             if ($sLang) {
                 $oLanguageSettings = SurveyLanguageSetting::model()->find('surveyls_survey_id=:surveyid AND surveyls_language=:langname', array(':surveyid' => $iSurveyID, ':langname' => $sLang));
                 if (!$oLanguageSettings) {
                     $oLanguageSettings = new SurveyLanguageSetting();
                     $languagedetails = getLanguageDetails($sLang);
                     $oLanguageSettings->surveyls_survey_id = $iSurveyID;
                     $oLanguageSettings->surveyls_language = $sLang;
                     $oLanguageSettings->surveyls_title = '';
                     // Not in default model ?
                     $oLanguageSettings->surveyls_dateformat = $languagedetails['dateformat'];
                     if (!$oLanguageSettings->save()) {
                         Yii::app()->setFlashMessage(gT("Survey language could not be created."), "error");
                         tracevar($oLanguageSettings->getErrors());
                     }
                 }
             }
         }
         /* Language fix : remove and add question/group */
         cleanLanguagesFromSurvey($iSurveyID, implode(" ", $oSurvey->additionalLanguages));
         fixLanguageConsistency($iSurveyID, implode(" ", $oSurvey->additionalLanguages));
         // Url params in json
         $aURLParams = json_decode(Yii::app()->request->getPost('allurlparams'), true);
         SurveyURLParameter::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         if (isset($aURLParams)) {
             foreach ($aURLParams as $aURLParam) {
                 $aURLParam['parameter'] = trim($aURLParam['parameter']);
                 if ($aURLParam['parameter'] == '' || !preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $aURLParam['parameter']) || $aURLParam['parameter'] == 'sid' || $aURLParam['parameter'] == 'newtest' || $aURLParam['parameter'] == 'token' || $aURLParam['parameter'] == 'lang') {
                     continue;
                     // this parameter name seems to be invalid - just ignore it
                 }
                 unset($aURLParam['act']);
                 unset($aURLParam['title']);
                 unset($aURLParam['id']);
                 if ($aURLParam['targetqid'] == '') {
                     $aURLParam['targetqid'] = NULL;
                 }
                 if ($aURLParam['targetsqid'] == '') {
                     $aURLParam['targetsqid'] = NULL;
                 }
                 $aURLParam['sid'] = $iSurveyID;
                 $param = new SurveyURLParameter();
                 foreach ($aURLParam as $k => $v) {
                     $param->{$k} = $v;
                 }
                 $param->save();
             }
         }
         ////////////////////////////////////////
         if ($sDBOutput != '') {
             echo $sDBOutput;
         } else {
             if (Yii::app()->request->getPost('close-after-save') === 'true') {
                 $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $iSurveyID));
             }
             $this->getController()->redirect(array('/admin/survey/sa/editlocalsettings/surveyid/' . $iSurveyID));
         }
     }
     $this->getController()->redirect(array("/admin"), "refresh");
 }
Exemplo n.º 20
0
 function index($subaction, $iSurveyID = null, $gid = null, $qid = null)
 {
     $iSurveyID = sanitize_int($iSurveyID);
     $gid = sanitize_int($gid);
     $qid = sanitize_int($qid);
     $clang = $this->getController()->lang;
     $imageurl = Yii::app()->getConfig("adminimageurl");
     Yii::app()->loadHelper("database");
     if (!empty($_POST['subaction'])) {
         $subaction = Yii::app()->request->getPost('subaction');
     }
     //BEGIN Sanitizing POSTed data
     if (!isset($iSurveyID)) {
         $iSurveyID = returnGlobal('sid');
     }
     if (!isset($qid)) {
         $qid = returnGlobal('qid');
     }
     if (!isset($gid)) {
         $gid = returnGlobal('gid');
     }
     if (!isset($p_scenario)) {
         $p_scenario = returnGlobal('scenario');
     }
     if (!isset($p_cqid)) {
         $p_cqid = returnGlobal('cqid');
         if ($p_cqid == '') {
             $p_cqid = 0;
         }
         // we are not using another question as source of condition
     }
     if (!isset($p_cid)) {
         $p_cid = returnGlobal('cid');
     }
     if (!isset($p_subaction)) {
         if (isset($_POST['subaction'])) {
             $p_subaction = $_POST['subaction'];
         } else {
             $p_subaction = $subaction;
         }
     }
     if (!isset($p_cquestions)) {
         $p_cquestions = returnGlobal('cquestions');
     }
     if (!isset($p_csrctoken)) {
         $p_csrctoken = returnGlobal('csrctoken');
     }
     if (!isset($p_prevquestionsgqa)) {
         $p_prevquestionsgqa = returnGlobal('prevQuestionSGQA');
     }
     if (!isset($p_canswers)) {
         if (isset($_POST['canswers']) && is_array($_POST['canswers'])) {
             foreach ($_POST['canswers'] as $key => $val) {
                 $p_canswers[$key] = preg_replace("/[^_.a-zA-Z0-9]@/", "", $val);
             }
         }
     }
     // this array will be used soon,
     // to explain wich conditions is used to evaluate the question
     if (Yii::app()->getConfig('stringcomparizonoperators') == 1) {
         $method = array("<" => $clang->gT("Less than"), "<=" => $clang->gT("Less than or equal to"), "==" => $clang->gT("equals"), "!=" => $clang->gT("Not equal to"), ">=" => $clang->gT("Greater than or equal to"), ">" => $clang->gT("Greater than"), "RX" => $clang->gT("Regular expression"), "a<b" => $clang->gT("Less than (Strings)"), "a<=b" => $clang->gT("Less than or equal to (Strings)"), "a>=b" => $clang->gT("Greater than or equal to (Strings)"), "a>b" => $clang->gT("Greater than (Strings)"));
     } else {
         $method = array("<" => $clang->gT("Less than"), "<=" => $clang->gT("Less than or equal to"), "==" => $clang->gT("equals"), "!=" => $clang->gT("Not equal to"), ">=" => $clang->gT("Greater than or equal to"), ">" => $clang->gT("Greater than"), "RX" => $clang->gT("Regular expression"));
     }
     if (isset($_POST['method'])) {
         if (!in_array($_POST['method'], array_keys($method))) {
             $p_method = "==";
         } else {
             $p_method = trim($_POST['method']);
         }
     }
     if (isset($_POST['newscenarionum'])) {
         $p_newscenarionum = sanitize_int($_POST['newscenarionum']);
     }
     //END Sanitizing POSTed data
     //include_once("login_check.php");
     include_once "database.php";
     // Caution (lemeur): database.php uses autoUnescape on all entries in $_POST
     // Take care to not use autoUnescape on $_POST variables after this
     $br = CHtml::openTag('br /');
     //MAKE SURE THAT THERE IS A SID
     if (!isset($iSurveyID) || !$iSurveyID) {
         $conditionsoutput = $clang->gT("You have not selected a survey") . str_repeat($br, 2);
         $conditionsoutput .= CHtml::submitButton($clang->gT("Main admin screen"), array('onclick' => "window.open('" . $this->getController()->createUrl("admin/") . "', '_top')")) . $br;
         safeDie($conditionsoutput);
         return;
     }
     if (isset($p_subaction) && $p_subaction == "resetsurveylogic") {
         $clang = $this->getController()->lang;
         $resetsurveylogicoutput = $br;
         $resetsurveylogicoutput .= CHtml::openTag('table', array('class' => 'alertbox'));
         $resetsurveylogicoutput .= CHtml::openTag('tr') . CHtml::openTag('td', array('colspan' => '2'));
         $resetsurveylogicoutput .= CHtml::tag('font', array('size' => '1'), CHtml::tag('strong', array(), $clang->gT("Reset Survey Logic")));
         $resetsurveylogicoutput .= CHtml::closeTag('td') . CHtml::closeTag('tr');
         if (!isset($_GET['ok'])) {
             $button_yes = CHtml::submitButton($clang->gT("Yes"), array('onclick' => "window.open('" . $this->getController()->createUrl("admin/conditions/sa/index/subaction/resetsurveylogic/surveyid/{$iSurveyID}") . "?ok=Y" . "', '_top')"));
             $button_cancel = CHtml::submitButton($clang->gT("Cancel"), array('onclick' => "window.open('" . $this->getController()->createUrl("admin/survey/sa/view/surveyid/{$iSurveyID}") . "', '_top')"));
             $messagebox_content = $clang->gT("You are about to delete all conditions on this survey's questions") . "({$iSurveyID})" . $br . $clang->gT("We recommend that before you proceed, you export the entire survey from the main administration screen.") . $br . $clang->gT("Continue?") . $br . $button_yes . $button_cancel;
             $this->_renderWrappedTemplate('conditions', array('message' => array('title' => $clang->gT("Warning"), 'message' => $messagebox_content)));
             exit;
         } else {
             LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
             Conditions::model()->deleteRecords("qid in (select qid from {{questions}} where sid={$iSurveyID})");
             Yii::app()->session['flashmessage'] = $clang->gT("All conditions in this survey have been deleted.");
             $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $iSurveyID));
         }
     }
     // MAKE SURE THAT THERE IS A QID
     if (!isset($qid) || !$qid) {
         $conditionsoutput = $clang->gT("You have not selected a question") . str_repeat($br, 2);
         $conditionsoutput .= CHtml::submitButton($clang->gT("Main admin screen"), array('onclick' => "window.open('" . $this->getController()->createUrl("admin/") . "', '_top')")) . $br;
         safeDie($conditionsoutput);
         return;
     }
     // If we made it this far, then lets develop the menu items
     // add the conditions container table
     $extraGetParams = "";
     if (isset($qid) && isset($gid)) {
         $extraGetParams = "/gid/{$gid}/qid/{$qid}";
     }
     $conditionsoutput_action_error = "";
     // defined during the actions
     $markcidarray = array();
     if (isset($_GET['markcid'])) {
         $markcidarray = explode("-", $_GET['markcid']);
     }
     //BEGIN PROCESS ACTIONS
     // ADD NEW ENTRY IF THIS IS AN ADD
     if (isset($p_subaction) && $p_subaction == "insertcondition") {
         if (!isset($p_canswers) && !isset($_POST['ConditionConst']) && !isset($_POST['prevQuestionSGQA']) && !isset($_POST['tokenAttr']) && !isset($_POST['ConditionRegexp']) || !isset($p_cquestions) && !isset($p_csrctoken)) {
             $conditionsoutput_action_error .= CHtml::script("\n<!--\n alert(\"" . $clang->gT("Your condition could not be added! It did not include the question and/or answer upon which the condition was based. Please ensure you have selected a question and an answer.", "js") . "\")\n //-->\n");
         } else {
             if (isset($p_cquestions) && $p_cquestions != '') {
                 $conditionCfieldname = $p_cquestions;
             } elseif (isset($p_csrctoken) && $p_csrctoken != '') {
                 $conditionCfieldname = $p_csrctoken;
             }
             $condition_data = array('qid' => $qid, 'scenario' => $p_scenario, 'cqid' => $p_cqid, 'cfieldname' => $conditionCfieldname, 'method' => $p_method);
             if (isset($p_canswers)) {
                 foreach ($p_canswers as $ca) {
                     //First lets make sure there isn't already an exact replica of this condition
                     $condition_data['value'] = $ca;
                     $result = Conditions::model()->findAllByAttributes($condition_data);
                     $count_caseinsensitivedupes = count($result);
                     if ($count_caseinsensitivedupes == 0) {
                         $result = Conditions::model()->insertRecords($condition_data);
                     }
                 }
             }
             unset($posted_condition_value);
             // Please note that autoUnescape is already applied in database.php included above
             // so we only need to db_quote _POST variables
             if (isset($_POST['ConditionConst']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#CONST") {
                 $posted_condition_value = Yii::app()->request->getPost('ConditionConst');
             } elseif (isset($_POST['prevQuestionSGQA']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#PREVQUESTIONS") {
                 $posted_condition_value = Yii::app()->request->getPost('prevQuestionSGQA');
             } elseif (isset($_POST['tokenAttr']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#TOKENATTRS") {
                 $posted_condition_value = Yii::app()->request->getPost('tokenAttr');
             } elseif (isset($_POST['ConditionRegexp']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#REGEXP") {
                 $posted_condition_value = Yii::app()->request->getPost('ConditionRegexp');
             }
             if (isset($posted_condition_value)) {
                 $condition_data['value'] = $posted_condition_value;
                 $result = Conditions::model()->insertRecords($condition_data);
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // UPDATE ENTRY IF THIS IS AN EDIT
     if (isset($p_subaction) && $p_subaction == "updatecondition") {
         if (!isset($p_canswers) && !isset($_POST['ConditionConst']) && !isset($_POST['prevQuestionSGQA']) && !isset($_POST['tokenAttr']) && !isset($_POST['ConditionRegexp']) || !isset($p_cquestions) && !isset($p_csrctoken)) {
             $conditionsoutput_action_error .= CHtml::script("\n<!--\n alert(\"" . $clang->gT("Your condition could not be added! It did not include the question and/or answer upon which the condition was based. Please ensure you have selected a question and an answer.", "js") . "\")\n //-->\n");
         } else {
             if (isset($p_cquestions) && $p_cquestions != '') {
                 $conditionCfieldname = $p_cquestions;
             } elseif (isset($p_csrctoken) && $p_csrctoken != '') {
                 $conditionCfieldname = $p_csrctoken;
             }
             if (isset($p_canswers)) {
                 foreach ($p_canswers as $ca) {
                     // This is an Edit, there will only be ONE VALUE
                     $updated_data = array('qid' => $qid, 'scenario' => $p_scenario, 'cqid' => $p_cqid, 'cfieldname' => $conditionCfieldname, 'method' => $p_method, 'value' => $ca);
                     $result = Conditions::model()->insertRecords($updated_data, TRUE, array('cid' => $p_cid));
                 }
             }
             unset($posted_condition_value);
             // Please note that autoUnescape is already applied in database.php included above
             // so we only need to db_quote _POST variables
             if (isset($_POST['ConditionConst']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#CONST") {
                 $posted_condition_value = Yii::app()->request->getPost('ConditionConst');
             } elseif (isset($_POST['prevQuestionSGQA']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#PREVQUESTIONS") {
                 $posted_condition_value = Yii::app()->request->getPost('prevQuestionSGQA');
             } elseif (isset($_POST['tokenAttr']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#TOKENATTRS") {
                 $posted_condition_value = Yii::app()->request->getPost('tokenAttr');
             } elseif (isset($_POST['ConditionRegexp']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#REGEXP") {
                 $posted_condition_value = Yii::app()->request->getPost('ConditionRegexp');
             }
             if (isset($posted_condition_value)) {
                 $updated_data = array('qid' => $qid, 'scenario' => $p_scenario, 'cqid' => $p_cqid, 'cfieldname' => $conditionCfieldname, 'method' => $p_method, 'value' => $posted_condition_value);
                 $result = Conditions::model()->insertRecords($updated_data, TRUE, array('cid' => $p_cid));
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // DELETE ENTRY IF THIS IS DELETE
     if (isset($p_subaction) && $p_subaction == "delete") {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance(NULL, $qid);
         // in case deleted the last condition
         $result = Conditions::model()->deleteRecords(array('cid' => $p_cid));
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // DELETE ALL CONDITIONS IN THIS SCENARIO
     if (isset($p_subaction) && $p_subaction == "deletescenario") {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance(NULL, $qid);
         // in case deleted the last condition
         $result = Conditions::model()->deleteRecords(array('qid' => $qid, 'scenario' => $p_scenario));
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // UPDATE SCENARIO
     if (isset($p_subaction) && $p_subaction == "updatescenario" && isset($p_newscenarionum)) {
         $result = Conditions::model()->insertRecords(array('scenario' => $p_newscenarionum), TRUE, array('qid' => $qid, 'scenario' => $p_scenario));
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // DELETE ALL CONDITIONS FOR THIS QUESTION
     if (isset($p_subaction) && $p_subaction == "deleteallconditions") {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance(NULL, $qid);
         // in case deleted the last condition
         $result = Conditions::model()->deleteRecords(array('qid' => $qid));
     }
     // RENUMBER SCENARIOS
     if (isset($p_subaction) && $p_subaction == "renumberscenarios") {
         $query = "SELECT DISTINCT scenario FROM {{conditions}} WHERE qid=:qid ORDER BY scenario";
         $result = Yii::app()->db->createCommand($query)->bindParam(":qid", $qid, PDO::PARAM_INT)->query() or safeDie("Couldn't select scenario<br />{$query}<br />");
         $newindex = 1;
         foreach ($result->readAll() as $srow) {
             // new var $update_result == old var $result2
             $update_result = Conditions::model()->insertRecords(array('scenario' => $newindex), TRUE, array('qid' => $qid, 'scenario' => $srow['scenario']));
             $newindex++;
         }
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
         Yii::app()->session['flashmessage'] = $clang->gT("All conditions scenarios were renumbered.");
     }
     // COPY CONDITIONS IF THIS IS COPY
     if (isset($p_subaction) && $p_subaction == "copyconditions") {
         $qid = returnGlobal('qid');
         $copyconditionsfrom = returnGlobal('copyconditionsfrom');
         $copyconditionsto = returnGlobal('copyconditionsto');
         if (isset($copyconditionsto) && is_array($copyconditionsto) && isset($copyconditionsfrom) && is_array($copyconditionsfrom)) {
             //Get the conditions we are going to copy
             foreach ($copyconditionsfrom as &$entry) {
                 $entry = Yii::app()->db->quoteValue($entry);
             }
             $query = "SELECT * FROM {{conditions}}\n" . "WHERE cid in (";
             $query .= implode(", ", $copyconditionsfrom);
             $query .= ")";
             $result = Yii::app()->db->createCommand($query)->query() or safeDie("Couldn't get conditions for copy<br />{$query}<br />");
             foreach ($result->readAll() as $row) {
                 $proformaconditions[] = array("scenario" => $row['scenario'], "cqid" => $row['cqid'], "cfieldname" => $row['cfieldname'], "method" => $row['method'], "value" => $row['value']);
             }
             // while
             foreach ($copyconditionsto as $copyc) {
                 list($newsid, $newgid, $newqid) = explode("X", $copyc);
                 foreach ($proformaconditions as $pfc) {
                     //TIBO
                     //First lets make sure there isn't already an exact replica of this condition
                     $conditions_data = array('qid' => $newqid, 'scenario' => $pfc['scenario'], 'cqid' => $pfc['cqid'], 'cfieldname' => $pfc['cfieldname'], 'method' => $pfc['method'], 'value' => $pfc['value']);
                     $result = Conditions::model()->findAllByAttributes($conditions_data);
                     $count_caseinsensitivedupes = count($result);
                     $countduplicates = 0;
                     if ($count_caseinsensitivedupes != 0) {
                         foreach ($result as $ccrow) {
                             if ($ccrow['value'] == $pfc['value']) {
                                 $countduplicates++;
                             }
                         }
                     }
                     if ($countduplicates == 0) {
                         $result = Conditions::model()->insertRecords($conditions_data);
                         $conditionCopied = true;
                     } else {
                         $conditionDuplicated = true;
                     }
                 }
             }
             if (isset($conditionCopied) && $conditionCopied === true) {
                 if (isset($conditionDuplicated) && $conditionDuplicated == true) {
                     $CopyConditionsMessage = CHtml::tag('div', array('class' => 'partialheader'), '(' . $clang->gT("Conditions successfully copied (some were skipped because they were duplicates)") . ')');
                 } else {
                     $CopyConditionsMessage = CHtml::tag('div', array('class' => 'successheader'), '(' . $clang->gT("Conditions successfully copied") . ')');
                 }
             } else {
                 $CopyConditionsMessage = CHtml::tag('div', array('class' => 'warningheader'), '(' . $clang->gT("No conditions could be copied (due to duplicates)") . ')');
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
         // do for whole survey, since don't know which questions affected.
     }
     //END PROCESS ACTIONS
     $cquestions = array();
     $canswers = array();
     //BEGIN: GATHER INFORMATION
     // 1: Get information for this question
     if (!isset($qid)) {
         $qid = returnGlobal('qid');
     }
     if (!isset($iSurveyID)) {
         $iSurveyID = returnGlobal('sid');
     }
     $thissurvey = getSurveyInfo($iSurveyID);
     $qresult = Questions::model()->with('groups')->findByAttributes(array('qid' => $qid, 'parent_qid' => 0, 'language' => Survey::model()->findByPk($iSurveyID)->language));
     $questiongroupname = $qresult->groups->group_name;
     $questiontitle = $qresult['title'];
     $questiontext = $qresult['question'];
     $questiontype = $qresult['type'];
     // 2: Get all other questions that occur before this question that are pre-determined answer types
     // To avoid natural sort order issues,
     // first get all questions in natural sort order
     // , and find out which number in that order this question is
     $qresult = Questions::model()->with(array('groups' => array('condition' => 'groups.language = :lang', 'params' => array(':lang' => Survey::model()->findByPk($iSurveyID)->language))))->findAllByAttributes(array('parent_qid' => 0, 'sid' => $iSurveyID, 'language' => Survey::model()->findByPk($iSurveyID)->language));
     $qrows = array();
     foreach ($qresult as $k => $v) {
         $qrows[$k] = array_merge($v->attributes, $v->groups->attributes);
     }
     // Perform a case insensitive natural sort on group name then question title (known as "code" in the form) of a multidimensional array
     usort($qrows, 'groupOrderThenQuestionOrder');
     $position = "before";
     // Go through each question until we reach the current one
     foreach ($qrows as $qrow) {
         if ($qrow["qid"] != $qid && $position == "before") {
             // remember all previous questions
             // all question types are supported.
             $questionlist[] = $qrow["qid"];
         } elseif ($qrow["qid"] == $qid) {
             break;
         }
     }
     // Now, using the same array which is now properly sorted by group then question
     // Create an array of all the questions that appear AFTER the current one
     $position = "before";
     foreach ($qrows as $qrow) {
         if ($qrow["qid"] == $qid) {
             $position = "after";
             //break;
         } elseif ($qrow["qid"] != $qid && $position == "after") {
             $postquestionlist[] = $qrow['qid'];
         }
     }
     $theserows = array();
     $postrows = array();
     if (isset($questionlist) && is_array($questionlist)) {
         foreach ($questionlist as $ql) {
             $result = Questions::model()->with(array('groups' => array('condition' => 'groups.language = :lang', 'params' => array(':lang' => Survey::model()->findByPk($iSurveyID)->language))))->findAllByAttributes(array('qid' => $ql, 'parent_qid' => 0, 'sid' => $iSurveyID, 'language' => Survey::model()->findByPk($iSurveyID)->language));
             $thiscount = count($result);
             // And store again these questions in this array...
             foreach ($result as $myrows) {
                 //key => value
                 $theserows[] = array("qid" => $myrows['qid'], "sid" => $myrows['sid'], "gid" => $myrows['gid'], "question" => $myrows['question'], "type" => $myrows['type'], "mandatory" => $myrows['mandatory'], "other" => $myrows['other'], "title" => $myrows['title']);
             }
         }
     }
     if (isset($postquestionlist) && is_array($postquestionlist)) {
         foreach ($postquestionlist as $pq) {
             $result = Questions::model()->with(array('groups' => array('condition' => 'groups.language = :lang', 'params' => array(':lang' => Survey::model()->findByPk($iSurveyID)->language))))->findAllByAttributes(array('qid' => $pq, 'parent_qid' => 0, 'sid' => $iSurveyID, 'language' => Survey::model()->findByPk($iSurveyID)->language));
             $postcount = count($result);
             foreach ($result as $myrows) {
                 $postrows[] = array("qid" => $myrows['qid'], "sid" => $myrows['sid'], "gid" => $myrows['gid'], "question" => $myrows['question'], "type" => $myrows['type'], "mandatory" => $myrows['mandatory'], "other" => $myrows['other'], "title" => $myrows['title']);
             }
             // while
         }
         $postquestionscount = count($postrows);
     }
     $questionscount = count($theserows);
     if (isset($postquestionscount) && $postquestionscount > 0) {
         //Build the array used for the questionNav and copyTo select boxes
         foreach ($postrows as $pr) {
             $pquestions[] = array("text" => $pr['title'] . ": " . substr(strip_tags($pr['question']), 0, 80), "fieldname" => $pr['sid'] . "X" . $pr['gid'] . "X" . $pr['qid']);
         }
     }
     // Previous question parsing ==> building cquestions[] and canswers[]
     if ($questionscount > 0) {
         $X = "X";
         foreach ($theserows as $rows) {
             $shortquestion = $rows['title'] . ": " . strip_tags($rows['question']);
             if ($rows['type'] == "A" || $rows['type'] == "B" || $rows['type'] == "C" || $rows['type'] == "E" || $rows['type'] == "F" || $rows['type'] == "H") {
                 $aresult = Questions::model()->findAllByAttributes(array('parent_qid' => $rows['qid'], 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'question_order ASC'));
                 foreach ($aresult as $arows) {
                     $shortanswer = "{$arows['title']}: [" . flattenText($arows['question']) . "]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . flattenText($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title']);
                     switch ($rows['type']) {
                         case "A":
                             //Array 5 buttons
                             for ($i = 1; $i <= 5; $i++) {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], $i, $i);
                             }
                             break;
                         case "B":
                             //Array 10 buttons
                             for ($i = 1; $i <= 10; $i++) {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], $i, $i);
                             }
                             break;
                         case "C":
                             //Array Y/N/NA
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "Y", $clang->gT("Yes"));
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "U", $clang->gT("Uncertain"));
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "N", $clang->gT("No"));
                             break;
                         case "E":
                             //Array >/=/<
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "I", $clang->gT("Increase"));
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "S", $clang->gT("Same"));
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "D", $clang->gT("Decrease"));
                             break;
                         case "F":
                             //Array Flexible Row
                         //Array Flexible Row
                         case "H":
                             //Array Flexible Column
                             $fresult = Answers::model()->findAllByAttributes(array('qid' => $rows['qid'], "language" => Survey::model()->findByPk($iSurveyID)->language, 'scale_id' => 0), array('order' => 'sortorder, code'));
                             foreach ($fresult as $frow) {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], $frow['code'], $frow['answer']);
                             }
                             break;
                     }
                     // Only Show No-Answer if question is not mandatory
                     if ($rows['mandatory'] != 'Y') {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "", $clang->gT("No answer"));
                     }
                 }
                 //while
             } elseif ($rows['type'] == ":" || $rows['type'] == ";") {
                 // Multiflexi
                 //Get question attribute for $canswers
                 $qidattributes = getQuestionAttributeValues($rows['qid'], $rows['type']);
                 if (isset($qidattributes['multiflexible_max']) && trim($qidattributes['multiflexible_max']) != '') {
                     $maxvalue = floatval($qidattributes['multiflexible_max']);
                 } else {
                     $maxvalue = 10;
                 }
                 if (isset($qidattributes['multiflexible_min']) && trim($qidattributes['multiflexible_min']) != '') {
                     $minvalue = floatval($qidattributes['multiflexible_min']);
                 } else {
                     $minvalue = 1;
                 }
                 if (isset($qidattributes['multiflexible_step']) && trim($qidattributes['multiflexible_step']) != '') {
                     $stepvalue = floatval($qidattributes['multiflexible_step']);
                     if ($stepvalue == 0) {
                         $stepvalue = 1;
                     }
                 } else {
                     $stepvalue = 1;
                 }
                 if (isset($qidattributes['multiflexible_checkbox']) && $qidattributes['multiflexible_checkbox'] != 0) {
                     $minvalue = 0;
                     $maxvalue = 1;
                     $stepvalue = 1;
                 }
                 // Get the Y-Axis
                 $fquery = "SELECT sq.*, q.other" . " FROM {{questions sq}}, {{questions q}}" . " WHERE sq.sid={$iSurveyID} AND sq.parent_qid=q.qid " . "AND q.language=:lang" . " AND sq.language=:lang" . " AND q.qid=:qid\n                    AND sq.scale_id=0\n                    ORDER BY sq.question_order";
                 $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
                 $y_axis_db = Yii::app()->db->createCommand($fquery)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->bindParam(":qid", $rows['qid'], PDO::PARAM_INT)->query();
                 // Get the X-Axis
                 $aquery = "SELECT sq.*\n                    FROM {{questions q}}, {{questions sq}}\n                    WHERE q.sid={$iSurveyID}\n                    AND sq.parent_qid=q.qid\n                    AND q.language=:lang\n                    AND sq.language=:lang\n                    AND q.qid=:qid\n                    AND sq.scale_id=1\n                    ORDER BY sq.question_order";
                 $x_axis_db = Yii::app()->db->createCommand($aquery)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->bindParam(":qid", $rows['qid'], PDO::PARAM_INT)->query() or safeDie("Couldn't get answers to Array questions<br />{$aquery}<br />");
                 foreach ($x_axis_db->readAll() as $frow) {
                     $x_axis[$frow['title']] = $frow['question'];
                 }
                 foreach ($y_axis_db->readAll() as $yrow) {
                     foreach ($x_axis as $key => $val) {
                         $shortquestion = $rows['title'] . ":{$yrow['title']}:{$key}: [" . strip_tags($yrow['question']) . "][" . strip_tags($val) . "] " . flattenText($rows['question']);
                         $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $yrow['title'] . "_" . $key);
                         if ($rows['type'] == ":") {
                             for ($ii = $minvalue; $ii <= $maxvalue; $ii += $stepvalue) {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $yrow['title'] . "_" . $key, $ii, $ii);
                             }
                         }
                     }
                 }
                 unset($x_axis);
             } elseif ($rows['type'] == "1") {
                 $aresult = Questions::model()->findAllByAttributes(array('parent_qid' => $rows['qid'], 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'question_order desc'));
                 foreach ($aresult as $arows) {
                     $attr = getQuestionAttributeValues($rows['qid']);
                     $label1 = isset($attr['dualscale_headerA']) ? $attr['dualscale_headerA'] : 'Label1';
                     $label2 = isset($attr['dualscale_headerB']) ? $attr['dualscale_headerB'] : 'Label2';
                     $shortanswer = "{$arows['title']}: [" . strip_tags($arows['question']) . "][{$label1}]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#0");
                     $shortanswer = "{$arows['title']}: [" . strip_tags($arows['question']) . "][{$label2}]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#1");
                     // first label
                     $lresult = Answers::model()->findAllByAttributes(array('qid' => $rows['qid'], 'scale_id' => 0, 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'sortorder, answer'));
                     foreach ($lresult as $lrows) {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#0", "{$lrows['code']}", "{$lrows['code']}");
                     }
                     // second label
                     $lresult = Answers::model()->findAllByAttributes(array('qid' => $rows['qid'], 'scale_id' => 1, 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'sortorder, answer'));
                     foreach ($lresult as $lrows) {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#1", "{$lrows['code']}", "{$lrows['code']}");
                     }
                     // Only Show No-Answer if question is not mandatory
                     if ($rows['mandatory'] != 'Y') {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#0", "", $clang->gT("No answer"));
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#1", "", $clang->gT("No answer"));
                     }
                 }
                 //while
             } elseif ($rows['type'] == "K" || $rows['type'] == "Q") {
                 $aresult = Questions::model()->findAllByAttributes(array("parent_qid" => $rows['qid'], "language" => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'question_order desc'));
                 foreach ($aresult as $arows) {
                     $shortanswer = "{$arows['title']}: [" . strip_tags($arows['question']) . "]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title']);
                     // Only Show No-Answer if question is not mandatory
                     if ($rows['mandatory'] != 'Y') {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "", $clang->gT("No answer"));
                     }
                 }
                 //while
             } elseif ($rows['type'] == "R") {
                 $aresult = Answers::model()->findAllByAttributes(array("qid" => $rows['qid'], "scale_id" => 0, "language" => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'sortorder, answer'));
                 $acount = count($aresult);
                 foreach ($aresult as $arow) {
                     $theanswer = addcslashes($arow['answer'], "'");
                     $quicky[] = array($arow['code'], $theanswer);
                 }
                 for ($i = 1; $i <= $acount; $i++) {
                     $cquestions[] = array("{$rows['title']}: [RANK {$i}] " . strip_tags($rows['question']), $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $i);
                     foreach ($quicky as $qck) {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $i, $qck[0], $qck[1]);
                     }
                     // Only Show No-Answer if question is not mandatory
                     if ($rows['mandatory'] != 'Y') {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $i, " ", $clang->gT("No answer"));
                     }
                 }
                 unset($quicky);
             } elseif ($rows['type'] == "M" || $rows['type'] == "P") {
                 $shortanswer = " [" . $clang->gT("Group of checkboxes") . "]";
                 $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                 $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid']);
                 $aresult = Questions::model()->findAllByAttributes(array("parent_qid" => $rows['qid'], "language" => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'question_order desc'));
                 foreach ($aresult as $arows) {
                     $theanswer = addcslashes($arows['question'], "'");
                     $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], $arows['title'], $theanswer);
                     $shortanswer = "{$arows['title']}: [" . strip_tags($arows['question']) . "]";
                     $shortanswer .= "[" . $clang->gT("Single checkbox") . "]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], "+" . $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title']);
                     $canswers[] = array("+" . $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], 'Y', $clang->gT("checked"));
                     $canswers[] = array("+" . $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], '', $clang->gT("not checked"));
                 }
             } elseif ($rows['type'] == "X") {
                 //Just ignore this questiontype
             } else {
                 $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid']);
                 switch ($rows['type']) {
                     case "Y":
                         // Y/N/NA
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "Y", $clang->gT("Yes"));
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "N", $clang->gT("No"));
                         // Only Show No-Answer if question is not mandatory
                         if ($rows['mandatory'] != 'Y') {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                         }
                         break;
                     case "G":
                         //Gender
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "F", $clang->gT("Female"));
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "M", $clang->gT("Male"));
                         // Only Show No-Answer if question is not mandatory
                         if ($rows['mandatory'] != 'Y') {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                         }
                         break;
                     case "5":
                         // 5 choice
                         for ($i = 1; $i <= 5; $i++) {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], $i, $i);
                         }
                         // Only Show No-Answer if question is not mandatory
                         if ($rows['mandatory'] != 'Y') {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                         }
                         break;
                     case "N":
                         // Simple Numerical questions
                         // Only Show No-Answer if question is not mandatory
                         if ($rows['mandatory'] != 'Y') {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                         }
                         break;
                     default:
                         $aresult = Answers::model()->findAllByAttributes(array('qid' => $rows['qid'], 'scale_id' => 0, 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'sortorder, answer'));
                         foreach ($aresult as $arows) {
                             $theanswer = addcslashes($arows['answer'], "'");
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], $arows['code'], $theanswer);
                         }
                         if ($rows['type'] == "D") {
                             // Only Show No-Answer if question is not mandatory
                             if ($rows['mandatory'] != 'Y') {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                             }
                         } elseif ($rows['type'] != "M" && $rows['type'] != "P" && $rows['type'] != "J" && $rows['type'] != "I") {
                             // For dropdown questions
                             // optinnaly add the 'Other' answer
                             if (($rows['type'] == "L" || $rows['type'] == "!") && $rows['other'] == "Y") {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "-oth-", $clang->gT("Other"));
                             }
                             // Only Show No-Answer if question is not mandatory
                             if ($rows['mandatory'] != 'Y') {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                             }
                         }
                         break;
                 }
                 //switch row type
             }
             //else
         }
         //foreach theserows
     }
     //if questionscount > 0
     //END Gather Information for this question
     $questionNavOptions = CHtml::openTag('optgroup', array('class' => 'activesurveyselect', 'label' => $clang->gT("Before", "js")));
     foreach ($theserows as $row) {
         $question = $row['question'];
         $question = strip_tags($question);
         if (strlen($question) < 35) {
             $questionselecter = $question;
         } else {
             //$questionselecter = substr($question, 0, 35)."..";
             $questionselecter = htmlspecialchars(mb_strcut(html_entity_decode($question, ENT_QUOTES, 'UTF-8'), 0, 35, 'UTF-8')) . "...";
         }
         $questionNavOptions .= CHtml::tag('option', array('value' => $this->getController()->createUrl("/admin/conditions/sa/index/subaction/editconditionsform/surveyid/{$iSurveyID}/gid/{$row['gid']}/qid/{$row['qid']}")), $questionselecter);
     }
     $questionNavOptions .= CHtml::closeTag('optgroup');
     $questionNavOptions .= CHtml::openTag('optgroup', array('class' => 'activesurveyselect', 'label' => $clang->gT("Current", "js")));
     $question = strip_tags($questiontext);
     if (strlen($question) < 35) {
         $questiontextshort = $question;
     } else {
         //$questiontextshort = substr($question, 0, 35)."..";
         $questiontextshort = htmlspecialchars(mb_strcut(html_entity_decode($question, ENT_QUOTES, 'UTF-8'), 0, 35, 'UTF-8')) . "...";
     }
     $questionNavOptions .= CHtml::tag('option', array('value' => $this->getController()->createUrl("/admin/conditions/sa/index/subaction/editconditionsform/surveyid/{$iSurveyID}/gid/{$gid}/qid/{$qid}"), 'selected' => 'selected'), $questiontitle . ': ' . $questiontextshort);
     $questionNavOptions .= CHtml::closeTag('optgroup');
     $questionNavOptions .= CHtml::openTag('optgroup', array('class' => 'activesurveyselect', 'label' => $clang->gT("After", "js")));
     foreach ($postrows as $row) {
         $question = $row['question'];
         $question = strip_tags($question);
         if (strlen($question) < 35) {
             $questionselecter = $question;
         } else {
             //$questionselecter = substr($question, 0, 35)."..";
             $questionselecter = htmlspecialchars(mb_strcut(html_entity_decode($question, ENT_QUOTES, 'UTF-8'), 0, 35, 'UTF-8')) . "...";
         }
         $questionNavOptions .= CHtml::tag('option', array('value' => $this->getController()->createUrl("/admin/conditions/sa/index/subaction/editconditionsform/surveyid/{$iSurveyID}/gid/{$row['gid']}/qid/{$row['qid']}")), $row['title'] . ':' . $questionselecter);
     }
     $questionNavOptions .= CHtml::closeTag('optgroup');
     //Now display the information and forms
     //BEGIN: PREPARE JAVASCRIPT TO SHOW MATCHING ANSWERS TO SELECTED QUESTION
     $javascriptpre = CHtml::openTag('script', array('type' => 'text/javascript')) . "<!--\n" . "\tvar Fieldnames = new Array();\n" . "\tvar Codes = new Array();\n" . "\tvar Answers = new Array();\n" . "\tvar QFieldnames = new Array();\n" . "\tvar Qcqids = new Array();\n" . "\tvar Qtypes = new Array();\n";
     $jn = 0;
     if (isset($canswers)) {
         foreach ($canswers as $can) {
             $an = ls_json_encode(flattenText($can[2]));
             $javascriptpre .= "Fieldnames[{$jn}]='{$can['0']}';\n" . "Codes[{$jn}]='{$can['1']}';\n" . "Answers[{$jn}]={$an};\n";
             $jn++;
         }
     }
     $jn = 0;
     if (isset($cquestions)) {
         foreach ($cquestions as $cqn) {
             $javascriptpre .= "QFieldnames[{$jn}]='{$cqn['3']}';\n" . "Qcqids[{$jn}]='{$cqn['1']}';\n" . "Qtypes[{$jn}]='{$cqn['2']}';\n";
             $jn++;
         }
     }
     //  record a JS variable to let jQuery know if survey is Anonymous
     if ($thissurvey['anonymized'] == 'Y') {
         $javascriptpre .= "isAnonymousSurvey = true;";
     } else {
         $javascriptpre .= "isAnonymousSurvey = false;";
     }
     $javascriptpre .= "//-->\n" . CHtml::closeTag('script');
     //END: PREPARE JAVASCRIPT TO SHOW MATCHING ANSWERS TO SELECTED QUESTION
     $this->getController()->_css_admin_includes(Yii::app()->getConfig("publicstyleurl") . 'jquery.multiselect.css');
     $aViewUrls = array();
     $aData['clang'] = $clang;
     $aData['surveyid'] = $iSurveyID;
     $aData['qid'] = $qid;
     $aData['gid'] = $gid;
     $aData['imageurl'] = $imageurl;
     $aData['extraGetParams'] = $extraGetParams;
     $aData['quesitonNavOptions'] = $questionNavOptions;
     $aData['conditionsoutput_action_error'] = $conditionsoutput_action_error;
     $aData['javascriptpre'] = $javascriptpre;
     $aViewUrls['conditionshead_view'][] = $aData;
     //BEGIN DISPLAY CONDITIONS FOR THIS QUESTION
     if ($subaction == 'index' || $subaction == 'editconditionsform' || $subaction == 'insertcondition' || $subaction == "editthiscondition" || $subaction == "delete" || $subaction == "updatecondition" || $subaction == "deletescenario" || $subaction == "renumberscenarios" || $subaction == "deleteallconditions" || $subaction == "updatescenario" || $subaction == 'copyconditionsform' || $subaction == 'copyconditions' || $subaction == 'conditions') {
         //3: Get other conditions currently set for this question
         $conditionscount = 0;
         $s = 0;
         $criteria = new CDbCriteria();
         $criteria->select = 'scenario';
         // only select the 'scenario' column
         $criteria->condition = 'qid=:qid';
         $criteria->params = array(':qid' => $qid);
         $criteria->order = 'scenario';
         $criteria->group = 'scenario';
         $scenarioresult = Conditions::model()->findAll($criteria);
         $scenariocount = count($scenarioresult);
         $showreplace = "{$questiontitle}" . $this->_showSpeaker($questiontext);
         $onlyshow = sprintf($clang->gT("Only show question %s IF"), $showreplace);
         $aData['conditionsoutput'] = '';
         $aData['extraGetParams'] = $extraGetParams;
         $aData['quesitonNavOptions'] = $questionNavOptions;
         $aData['conditionsoutput_action_error'] = $conditionsoutput_action_error;
         $aData['javascriptpre'] = $javascriptpre;
         $aData['onlyshow'] = $onlyshow;
         $aData['subaction'] = $subaction;
         $aData['scenariocount'] = $scenariocount;
         $aViewUrls['conditionslist_view'][] = $aData;
         if ($scenariocount > 0) {
             //self::_js_admin_includes($this->config->item("generalscripts").'jquery/jquery.checkgroup.js');
             $this->getController()->_js_admin_includes(Yii::app()->getConfig("generalscripts") . 'jquery/jquery.checkgroup.js');
             foreach ($scenarioresult as $scenarionr) {
                 $scenariotext = "";
                 if ($s == 0 && $scenariocount > 1) {
                     $scenariotext = " -------- <i>Scenario {$scenarionr['scenario']}</i> --------";
                 }
                 if ($s > 0) {
                     $scenariotext = " -------- <i>" . $clang->gT("OR") . " Scenario {$scenarionr['scenario']}</i> --------";
                 }
                 if ($subaction == "copyconditionsform" || $subaction == "copyconditions") {
                     $initialCheckbox = "<td><input type='checkbox' id='scenarioCbx{$scenarionr['scenario']}' checked='checked'/>\n" . "<script type='text/javascript'>\$(document).ready(function () { \$('#scenarioCbx{$scenarionr['scenario']}').checkgroup({ groupName:'aConditionFromScenario{$scenarionr['scenario']}'}); });</script>" . "</td><td>&nbsp;</td>\n";
                 } else {
                     $initialCheckbox = "";
                 }
                 if ($scenariotext != "" && ($subaction == "editconditionsform" || $subaction == "insertcondition" || $subaction == "updatecondition" || $subaction == "editthiscondition" || $subaction == "renumberscenarios" || $subaction == "updatescenario" || $subaction == "deletescenario" || $subaction == "delete")) {
                     $img_tag = CHtml::image($imageurl . '/scenario_delete.png', $clang->gT("Delete this scenario"), array('name' => 'DeleteWholeGroup'));
                     $additional_main_content = CHtml::link($img_tag, '#', array('onclick' => "if ( confirm('" . $clang->gT("Are you sure you want to delete all conditions set in this scenario?", "js") . "')) { document.getElementById('deletescenario{$scenarionr['scenario']}').submit();}"));
                     $img_tag = CHtml::image($imageurl . '/scenario_edit.png', $clang->gT("Edit scenario"), array('name' => 'DeleteWholeGroup'));
                     $additional_main_content .= CHtml::link($img_tag, '#', array('id' => 'editscenariobtn' . $scenarionr['scenario'], 'onclick' => "\$('#editscenario{$scenarionr['scenario']}').toggle('slow');"));
                     $aData['additional_content'] = $additional_main_content;
                 }
                 $aData['initialCheckbox'] = $initialCheckbox;
                 $aData['scenariotext'] = $scenariotext;
                 $aData['scenarionr'] = $scenarionr;
                 if (!isset($aViewUrls['output'])) {
                     $aViewUrls['output'] = '';
                 }
                 $aViewUrls['output'] .= $this->getController()->render('/admin/conditions/includes/conditions_scenario', $aData, TRUE);
                 unset($currentfield);
                 $query = "SELECT count(*) as recordcount\n                    FROM {{conditions}} c, {{questions}} q, {{groups}} g\n                    WHERE c.cqid=q.qid " . "AND q.gid=g.gid " . "AND q.parent_qid=0 " . "AND q.language=:lang1 " . "AND g.language=:lang2 " . "AND c.qid=:qid " . "AND c.scenario=:scenario " . "AND c.cfieldname NOT LIKE '{%' ";
                 // avoid catching SRCtokenAttr conditions
                 $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
                 $result = Yii::app()->db->createCommand($query)->bindValue(":scenario", $scenarionr['scenario'])->bindValue(":qid", $qid, PDO::PARAM_INT)->bindValue(":lang1", $sLanguage, PDO::PARAM_STR)->bindValue(":lang2", $sLanguage, PDO::PARAM_STR)->queryRow();
                 $conditionscount = (int) $result['recordcount'];
                 $query = "SELECT c.cid, c.scenario, c.cqid, c.cfieldname, c.method, c.value, q.type\n                    FROM {{conditions}} c, {{questions}} q, {{groups}} g\n                    WHERE c.cqid=q.qid " . "AND q.gid=g.gid " . "AND q.parent_qid=0 " . "AND q.language=:lang1 " . "AND g.language=:lang2 " . "AND c.qid=:qid " . "AND c.scenario=:scenario " . "AND c.cfieldname NOT LIKE '{%' " . "ORDER BY g.group_order, q.question_order, c.cfieldname";
                 $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
                 $result = Yii::app()->db->createCommand($query)->bindValue(":scenario", $scenarionr['scenario'])->bindValue(":qid", $qid, PDO::PARAM_INT)->bindValue(":lang1", $sLanguage, PDO::PARAM_STR)->bindValue(":lang2", $sLanguage, PDO::PARAM_STR)->query() or safeDie("Couldn't get other conditions for question {$qid}<br />{$query}<br />");
                 $querytoken = "SELECT count(*) as recordcount " . "FROM {{conditions}} " . "WHERE " . " {{conditions}}.qid=:qid " . "AND {{conditions}}.scenario=:scenario " . "AND {{conditions}}.cfieldname LIKE '{%' ";
                 // only catching SRCtokenAttr conditions
                 $resulttoken = Yii::app()->db->createCommand($querytoken)->bindValue(":scenario", $scenarionr['scenario'], PDO::PARAM_INT)->bindValue(":qid", $qid, PDO::PARAM_INT)->queryRow() or safeDie("Couldn't get other conditions for question {$qid}<br />{$query}<br />");
                 $conditionscounttoken = (int) $resulttoken['recordcount'];
                 $querytoken = "SELECT {{conditions}}.cid, " . "{{conditions}}.scenario, " . "{{conditions}}.cqid, " . "{{conditions}}.cfieldname, " . "{{conditions}}.method, " . "{{conditions}}.value, " . "'' AS type " . "FROM {{conditions}} " . "WHERE " . " {{conditions}}.qid=:qid " . "AND {{conditions}}.scenario=:scenario " . "AND {{conditions}}.cfieldname LIKE '{%' " . "ORDER BY {{conditions}}.cfieldname";
                 $resulttoken = Yii::app()->db->createCommand($querytoken)->bindValue(":scenario", $scenarionr['scenario'], PDO::PARAM_INT)->bindValue(":qid", $qid, PDO::PARAM_INT)->query() or safeDie("Couldn't get other conditions for question {$qid}<br />{$query}<br />");
                 $conditionscount = $conditionscount + $conditionscounttoken;
                 if ($conditionscount > 0) {
                     $aConditionsMerged = array();
                     foreach ($resulttoken->readAll() as $arow) {
                         $aConditionsMerged[] = $arow;
                     }
                     foreach ($result->readAll() as $arow) {
                         $aConditionsMerged[] = $arow;
                     }
                     foreach ($aConditionsMerged as $rows) {
                         if ($rows['method'] == "") {
                             $rows['method'] = "==";
                         }
                         //Fill in the empty method from previous versions
                         $markcidstyle = "oddrow";
                         if (array_search($rows['cid'], $markcidarray) !== FALSE) {
                             // This is the style used when the condition editor is called
                             // in order to check which conditions prevent a question deletion
                             $markcidstyle = "markedrow";
                         }
                         if ($subaction == "editthiscondition" && isset($p_cid) && $rows['cid'] === $p_cid) {
                             // Style used when editing a condition
                             $markcidstyle = "editedrow";
                         }
                         if (isset($currentfield) && $currentfield != $rows['cfieldname']) {
                             $aViewUrls['output'] .= "<tr class='evenrow'>\n" . "\t<td colspan='2'>\n" . "<span><strong>" . $clang->gT("and") . "</strong></span></td></tr>";
                         } elseif (isset($currentfield)) {
                             $aViewUrls['output'] .= "<tr class='evenrow'>\n" . "\t<td colspan='2'>\n" . "<span><strong>" . $clang->gT("or") . "</strong></span></td></tr>";
                         }
                         $aViewUrls['output'] .= "\t<tr class='{$markcidstyle}'>\n" . "\t<td colspan='2'>" . CHtml::form(array("/admin/conditions/sa/index/subaction/{$subaction}/surveyid/{$iSurveyID}/gid/{$gid}/qid/{$qid}/"), 'post', array('id' => "conditionaction{$rows['cid']}", 'name' => "conditionaction{$rows['cid']}")) . "<table>\n" . "\t<tr>\n";
                         if ($subaction == "copyconditionsform" || $subaction == "copyconditions") {
                             $aViewUrls['output'] .= "<td>&nbsp;&nbsp;</td>" . "<td>\n" . "\t<input type='checkbox' name='aConditionFromScenario{$scenarionr['scenario']}' id='cbox{$rows['cid']}' value='{$rows['cid']}' checked='checked'/>\n" . "</td>\n";
                         }
                         $aViewUrls['output'] .= "" . "<td>\n" . "\t<span>\n";
                         $leftOperandType = 'unknown';
                         // prevquestion, tokenattr
                         if ($thissurvey['anonymized'] != 'Y' && preg_match('/^{TOKEN:([^}]*)}$/', $rows['cfieldname'], $extractedTokenAttr) > 0) {
                             $leftOperandType = 'tokenattr';
                             $aTokenAttrNames = getTokenFieldsAndNames($iSurveyID);
                             if (count($aTokenAttrNames) != 0) {
                                 $thisAttrName = HTMLEscape($aTokenAttrNames[strtolower($extractedTokenAttr[1])]['description']) . " [" . $clang->gT("From token table") . "]";
                             } else {
                                 $thisAttrName = HTMLEscape($extractedTokenAttr[1]) . " [" . $clang->gT("Inexistant token table") . "]";
                             }
                             $aViewUrls['output'] .= "\t{$thisAttrName}\n";
                             // TIBO not sure this is used anymore !!
                             $conditionsList[] = array("cid" => $rows['cid'], "text" => $thisAttrName);
                         } else {
                             $leftOperandType = 'prevquestion';
                             foreach ($cquestions as $cqn) {
                                 if ($cqn[3] == $rows['cfieldname']) {
                                     $aViewUrls['output'] .= "\t{$cqn['0']} (qid{$rows['cqid']})\n";
                                     $conditionsList[] = array("cid" => $rows['cid'], "text" => $cqn[0] . " ({$rows['value']})");
                                 } else {
                                     //$aViewUrls['output'] .= "\t<font color='red'>ERROR: Delete this condition. It is out of order.</font>\n";
                                 }
                             }
                         }
                         $aViewUrls['output'] .= "\t</span></td>\n" . "\t<td>\n" . "<span>\n" . $method[trim($rows['method'])] . "</span>\n" . "\t</td>\n" . "\n" . "\t<td>\n" . "<span>\n";
                         // let's read the condition's right operand
                         // determine its type and display it
                         $rightOperandType = 'unknown';
                         // predefinedAnsw,constantVal, prevQsgqa, tokenAttr, regexp
                         if ($rows['method'] == 'RX') {
                             $rightOperandType = 'regexp';
                             $aViewUrls['output'] .= "" . HTMLEscape($rows['value']) . "\n";
                         } elseif (preg_match('/^@([0-9]+X[0-9]+X[^@]*)@$/', $rows['value'], $matchedSGQA) > 0) {
                             // SGQA
                             $rightOperandType = 'prevQsgqa';
                             $textfound = false;
                             foreach ($cquestions as $cqn) {
                                 if ($cqn[3] == $matchedSGQA[1]) {
                                     $matchedSGQAText = $cqn[0];
                                     $textfound = true;
                                     break;
                                 }
                             }
                             if ($textfound === false) {
                                 $matchedSGQAText = $rows['value'] . ' (' . $clang->gT("Not found") . ')';
                             }
                             $aViewUrls['output'] .= "" . HTMLEscape($matchedSGQAText) . "\n";
                         } elseif ($thissurvey['anonymized'] != 'Y' && preg_match('/^{TOKEN:([^}]*)}$/', $rows['value'], $extractedTokenAttr) > 0) {
                             $rightOperandType = 'tokenAttr';
                             $aTokenAttrNames = getTokenFieldsAndNames($iSurveyID);
                             if (count($aTokenAttrNames) != 0) {
                                 $thisAttrName = HTMLEscape($aTokenAttrNames[strtolower($extractedTokenAttr[1])]['description']) . " [" . $clang->gT("From token table") . "]";
                             } else {
                                 $thisAttrName = HTMLEscape($extractedTokenAttr[1]) . " [" . $clang->gT("Inexistant token table") . "]";
                             }
                             $aViewUrls['output'] .= "\t{$thisAttrName}\n";
                         } elseif (isset($canswers)) {
                             foreach ($canswers as $can) {
                                 if ($can[0] == $rows['cfieldname'] && $can[1] == $rows['value']) {
                                     $aViewUrls['output'] .= "{$can['2']} ({$can['1']})\n";
                                     $rightOperandType = 'predefinedAnsw';
                                 }
                             }
                         }
                         // if $rightOperandType is still unkown then it is a simple constant
                         if ($rightOperandType == 'unknown') {
                             $rightOperandType = 'constantVal';
                             if ($rows['value'] == ' ' || $rows['value'] == '') {
                                 $aViewUrls['output'] .= "" . $clang->gT("No answer") . "\n";
                             } else {
                                 $aViewUrls['output'] .= "" . HTMLEscape($rows['value']) . "\n";
                             }
                         }
                         $aViewUrls['output'] .= "\t</span></td>\n" . "\t<td>\n";
                         if ($subaction == "editconditionsform" || $subaction == "insertcondition" || $subaction == "updatecondition" || $subaction == "editthiscondition" || $subaction == "renumberscenarios" || $subaction == "deleteallconditions" || $subaction == "updatescenario" || $subaction == "deletescenario" || $subaction == "delete") {
                             // show single condition action buttons in edit mode
                             $aData['rows'] = $rows;
                             $aData['sImageURL'] = Yii::app()->getConfig('adminimageurl');
                             //$aViewUrls['includes/conditions_edit'][] = $aData;
                             $aViewUrls['output'] .= $this->getController()->render('/admin/conditions/includes/conditions_edit', $aData, TRUE);
                             // now sets e corresponding hidden input field
                             // depending on the leftOperandType
                             if ($leftOperandType == 'tokenattr') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('csrctoken', HTMLEscape($rows['cfieldname']), array('id' => 'csrctoken' . $rows['cid']));
                             } else {
                                 $aViewUrls['output'] .= CHtml::hiddenField('cquestions', HTMLEscape($rows['cfieldname']), array('id' => 'cquestions' . $rows['cid']));
                             }
                             // now set the corresponding hidden input field
                             // depending on the rightOperandType
                             // This is used when Editting a condition
                             if ($rightOperandType == 'predefinedAnsw') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITcanswers[]', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             } elseif ($rightOperandType == 'prevQsgqa') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITprevQuestionSGQA', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             } elseif ($rightOperandType == 'tokenAttr') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITtokenAttr', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             } elseif ($rightOperandType == 'regexp') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITConditionRegexp', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             } else {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITConditionConst', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             }
                         }
                         $aViewUrls['output'] .= CHtml::closeTag('td') . CHtml::closeTag('tr') . CHtml::closeTag('table') . CHtml::closeTag('form') . CHtml::closeTag('td') . CHtml::closeTag('tr');
                         $currentfield = $rows['cfieldname'];
                     }
                 }
                 $s++;
             }
         } else {
             // no condition ==> disable delete all conditions button, and display a simple comment
             $aViewUrls['output'] = CHtml::openTag('tr') . CHtml::tag('td', array(), $clang->gT("This question is always shown.")) . CHtml::tag('td', array(), '&nbsp;') . CHtml::closeTag('tr');
         }
         $aViewUrls['output'] .= CHtml::closeTag('table');
     }
     //END DISPLAY CONDITIONS FOR THIS QUESTION
     // BEGIN: DISPLAY THE COPY CONDITIONS FORM
     if ($subaction == "copyconditionsform" || $subaction == "copyconditions") {
         $aViewUrls['output'] .= "<tr class=''><td colspan='3'>\n" . CHtml::form(array("/admin/conditions/sa/index/subaction/copyconditions/surveyid/{$iSurveyID}/gid/{$gid}/qid/{$qid}/"), 'post', array('id' => "copyconditions", 'name' => "copyconditions")) . "<div class='header ui-widget-header'>" . $clang->gT("Copy conditions") . "</div>\n";
         //CopyConditionsMessage
         if (isset($CopyConditionsMessage)) {
             $aViewUrls['output'] .= "<div class='messagebox ui-corner-all'>\n" . "{$CopyConditionsMessage}\n" . "</div>\n";
         }
         if (isset($conditionsList) && is_array($conditionsList)) {
             //TIBO
             $this->getController()->_js_admin_includes(Yii::app()->getConfig("generalscripts") . 'jquery/jquery.multiselect.min.js');
             // TODO
             $aViewUrls['output'] .= "<script type='text/javascript'>\$(document).ready(function () { \$('#copytomultiselect').multiselect( { autoOpen: true, noneSelectedText: '" . $clang->gT("No questions selected") . "', checkAllText: '" . $clang->gT("Check all") . "', uncheckAllText: '" . $clang->gT("Uncheck all") . "', selectedText: '# " . $clang->gT("selected") . "', beforeclose: function(){ return false;},height: 200 } ); });</script>";
             $aViewUrls['output'] .= "\t<div class='conditioncopy-tbl-row'>\n" . "\t<div class='condition-tbl-left'>" . $clang->gT("Copy the selected conditions to") . ":</div>\n" . "\t<div class='condition-tbl-right'>\n" . "\t\t<select name='copyconditionsto[]' id='copytomultiselect'  multiple='multiple' >\n";
             if (isset($pquestions) && count($pquestions) != 0) {
                 foreach ($pquestions as $pq) {
                     $aViewUrls['output'] .= "\t\t<option value='{$pq['fieldname']}'>" . $pq['text'] . "</option>\n";
                 }
             }
             $aViewUrls['output'] .= "\t\t</select>\n" . "\t</div>\n" . "\t</div>\n";
             if (!isset($pquestions) || count($pquestions) == 0) {
                 $disableCopyCondition = " disabled='disabled'";
             } else {
                 $disableCopyCondition = " ";
             }
             $aViewUrls['output'] .= "\t<div class='condition-tbl-full'>\n" . "\t\t<input type='submit' value='" . $clang->gT("Copy conditions") . "' onclick=\"prepareCopyconditions(); return true;\" {$disableCopyCondition}/>\n" . "<input type='hidden' name='subaction' value='copyconditions' />\n" . "<input type='hidden' name='sid' value='{$iSurveyID}' />\n" . "<input type='hidden' name='gid' value='{$gid}' />\n" . "<input type='hidden' name='qid' value='{$qid}' />\n" . "</div>\n";
             $aViewUrls['output'] .= "<script type=\"text/javascript\">\n" . "function prepareCopyconditions()\n" . "{\n" . "\t\$(\"input:checked[name^='aConditionFromScenario']\").each(function(i,val)\n" . "\t{\n" . "var thecid = val.value;\n" . "var theform = document.getElementById('copyconditions');\n" . "addHiddenElement(theform,'copyconditionsfrom[]',thecid);\n" . "return true;\n" . "\t});\n" . "}\n" . "</script>\n";
         } else {
             $aViewUrls['output'] .= "<div class='messagebox ui-corner-all'>\n" . "<div class='partialheader'>" . $clang->gT("There are no existing conditions in this survey.") . "</div><br />\n" . "</div>\n";
         }
         $aViewUrls['output'] .= "</form></td></tr>\n";
     }
     // END: DISPLAY THE COPY CONDITIONS FORM
     if (isset($cquestions)) {
         if (count($cquestions) > 0 && count($cquestions) <= 10) {
             $qcount = count($cquestions);
         } else {
             $qcount = 9;
         }
     } else {
         $qcount = 0;
     }
     //BEGIN: DISPLAY THE ADD or EDIT CONDITION FORM
     if ($subaction == "editconditionsform" || $subaction == "insertcondition" || $subaction == "updatecondition" || $subaction == "deletescenario" || $subaction == "renumberscenarios" || $subaction == "deleteallconditions" || $subaction == "updatescenario" || $subaction == "editthiscondition" || $subaction == "delete") {
         $aViewUrls['output'] .= CHtml::form(array("/admin/conditions/sa/index/subaction/{$subaction}/surveyid/{$iSurveyID}/gid/{$gid}/qid/{$qid}/"), 'post', array('id' => "editconditions", 'name' => "editconditions"));
         if ($subaction == "editthiscondition" && isset($p_cid)) {
             $mytitle = $clang->gT("Edit condition");
         } else {
             $mytitle = $clang->gT("Add condition");
         }
         $aViewUrls['output'] .= "<div class='header ui-widget-header'>" . $mytitle . "</div>\n";
         ///////////////////////////////////////////////////////////////////////////////////////////
         // Begin "Scenario" row
         if ($subaction != "editthiscondition" && isset($scenariocount) && ($scenariocount == 1 || $scenariocount == 0) || $subaction == "editthiscondition" && isset($scenario) && $scenario == 1) {
             $scenarioAddBtn = "\t<a id='scenarioaddbtn' href='#' onclick=\"\$('#scenarioaddbtn').hide();\$('#defaultscenariotxt').hide('slow');\$('#scenario').show('slow');\">" . "<img src='{$imageurl}/plus.png' alt='" . $clang->gT('Add scenario') . "' /></a>\n";
             $scenarioTxt = "<span id='defaultscenariotxt'>" . $clang->gT("Default scenario") . "</span>";
             $scenarioInputStyle = "style = 'display: none;'";
         } else {
             $scenarioAddBtn = "";
             $scenarioTxt = "";
             $scenarioInputStyle = "style = ''";
         }
         $aViewUrls['output'] .= "<div class='condition-tbl-row'>\n" . "<div class='condition-tbl-left'>{$scenarioAddBtn}&nbsp;" . $clang->gT("Scenario") . "</div>\n" . "<div class='condition-tbl-right'><input type='text' name='scenario' id='scenario' value='1' size='2' {$scenarioInputStyle}/>" . "{$scenarioTxt}\n" . "</div>\n" . "</div>\n";
         // Begin "Question" row
         $aViewUrls['output'] .= "<div class='condition-tbl-row'>\n" . "<div class='condition-tbl-left'>" . $clang->gT("Question") . "</div>\n" . "<div class='condition-tbl-right'>\n" . "\t<div id=\"conditionsource\" class=\"tabs-nav\">\n" . "\t<ul>\n" . "\t<li><a href=\"#SRCPREVQUEST\"><span>" . $clang->gT("Previous questions") . "</span></a></li>\n" . "\t<li><a href=\"#SRCTOKENATTRS\"><span>" . $clang->gT("Token fields") . "</span></a></li>\n" . "\t</ul>\n";
         // Previous question tab
         $aViewUrls['output'] .= "<div id='SRCPREVQUEST'><select name='cquestions' id='cquestions' size='" . ($qcount + 1) . "' >\n";
         if (isset($cquestions)) {
             $js_getAnswers_onload = "";
             foreach ($cquestions as $cqn) {
                 $aViewUrls['output'] .= "<option value='{$cqn['3']}' title=\"" . htmlspecialchars($cqn[0]) . "\"";
                 if (isset($p_cquestions) && $cqn[3] == $p_cquestions) {
                     $aViewUrls['output'] .= " selected";
                     if (isset($p_canswers)) {
                         $canswersToSelect = "";
                         foreach ($p_canswers as $checkval) {
                             $canswersToSelect .= ";{$checkval}";
                         }
                         $canswersToSelect = substr($canswersToSelect, 1);
                         $js_getAnswers_onload .= "\$('#canswersToSelect').val('{$canswersToSelect}');\n";
                     }
                 }
                 $aViewUrls['output'] .= ">{$cqn['0']}</option>\n";
             }
         }
         $aViewUrls['output'] .= "</select>\n" . "</div>\n";
         // Source token Tab
         $aViewUrls['output'] .= "<div id='SRCTOKENATTRS'><select name='csrctoken' id='csrctoken' size='" . ($qcount + 1) . "' >\n";
         foreach (getTokenFieldsAndNames($iSurveyID) as $tokenattr => $tokenattrName) {
             // Check to select
             if (isset($p_csrctoken) && $p_csrctoken == '{TOKEN:' . strtoupper($tokenattr) . '}') {
                 $selectThisSrcTokenAttr = "selected=\"selected\"";
             } else {
                 $selectThisSrcTokenAttr = "";
             }
             $aViewUrls['output'] .= "<option value='{TOKEN:" . strtoupper($tokenattr) . "}' {$selectThisSrcTokenAttr}>" . HTMLEscape($tokenattrName['description']) . "</option>\n";
         }
         $aViewUrls['output'] .= "</select>\n" . "</div>\n\n";
         $aViewUrls['output'] .= "\t</div>\n";
         // end conditionsource div
         $aViewUrls['output'] .= "</div>\n" . "</div>\n";
         // Begin "Comparison operator" row
         $aViewUrls['output'] .= "<div class='condition-tbl-row'>\n" . "<div class='condition-tbl-left'>" . $clang->gT("Comparison operator") . "</div>\n" . "<div class='condition-tbl-right'>\n" . "<select name='method' id='method'>\n";
         foreach ($method as $methodCode => $methodTxt) {
             $selected = $methodCode == "==" ? " selected='selected'" : "";
             $aViewUrls['output'] .= "\t<option value='" . $methodCode . "'{$selected}>" . $methodTxt . "</option>\n";
         }
         $aViewUrls['output'] .= "</select>\n" . "</div>\n" . "</div>\n";
         // Begin "Answer" row
         $aViewUrls['output'] .= "<div class='condition-tbl-row'>\n" . "<div class='condition-tbl-left'>" . $clang->gT("Answer") . "</div>\n";
         if ($subaction == "editthiscondition") {
             $multipletext = "";
             if (isset($_POST['EDITConditionConst']) && $_POST['EDITConditionConst'] != '') {
                 $EDITConditionConst = HTMLEscape($_POST['EDITConditionConst']);
             } else {
                 $EDITConditionConst = "";
             }
             if (isset($_POST['EDITConditionRegexp']) && $_POST['EDITConditionRegexp'] != '') {
                 $EDITConditionRegexp = HTMLEscape($_POST['EDITConditionRegexp']);
             } else {
                 $EDITConditionRegexp = "";
             }
         } else {
             $multipletext = "multiple";
             if (isset($_POST['ConditionConst']) && $_POST['ConditionConst'] != '') {
                 $EDITConditionConst = HTMLEscape($_POST['ConditionConst']);
             } else {
                 $EDITConditionConst = "";
             }
             if (isset($_POST['ConditionRegexp']) && $_POST['ConditionRegexp'] != '') {
                 $EDITConditionRegexp = HTMLEscape($_POST['ConditionRegexp']);
             } else {
                 $EDITConditionRegexp = "";
             }
         }
         $aViewUrls['output'] .= "" . "<div class='condition-tbl-right'>\n" . "<div id=\"conditiontarget\" class=\"tabs-nav\">\n" . "\t<ul>\n" . "\t\t<li><a href=\"#CANSWERSTAB\"><span>" . $clang->gT("Predefined") . "</span></a></li>\n" . "\t\t<li><a href=\"#CONST\"><span>" . $clang->gT("Constant") . "</span></a></li>\n" . "\t\t<li><a href=\"#PREVQUESTIONS\"><span>" . $clang->gT("Questions") . "</span></a></li>\n" . "\t\t<li><a href=\"#TOKENATTRS\"><span>" . $clang->gT("Token fields") . "</span></a></li>\n" . "\t\t<li><a href=\"#REGEXP\"><span>" . $clang->gT("RegExp") . "</span></a></li>\n" . "\t</ul>\n";
         // Predefined answers tab
         $aViewUrls['output'] .= "\t<div id='CANSWERSTAB'>\n" . "\t\t<select  name='canswers[]' {$multipletext} id='canswers' size='7'>\n" . "\t\t</select>\n" . "\t\t<br /><span id='canswersLabel'>" . $clang->gT("Predefined answer options for this question") . "</span>\n" . "\t</div>\n";
         // Constant tab
         $aViewUrls['output'] .= "\t<div id='CONST' style='display:block;' >\n" . "\t\t<textarea name='ConditionConst' id='ConditionConst' rows='5' cols='113'>{$EDITConditionConst}</textarea>\n" . "\t\t<br /><div id='ConditionConstLabel'>" . $clang->gT("Constant value") . "</div>\n" . "\t</div>\n";
         // Previous answers tab @SGQA@ placeholders
         $aViewUrls['output'] .= "\t<div id='PREVQUESTIONS'>\n" . "\t\t<select name='prevQuestionSGQA' id='prevQuestionSGQA' size='7'>\n";
         foreach ($cquestions as $cqn) {
             // building the @SGQA@ placeholders options
             if ($cqn[2] != 'M' && $cqn[2] != 'P') {
                 // Type M or P aren't real fieldnames and thus can't be used in @SGQA@ placehodlers
                 $aViewUrls['output'] .= "\t\t<option value='@{$cqn['3']}@' title=\"" . htmlspecialchars($cqn[0]) . "\"";
                 if (isset($p_prevquestionsgqa) && $p_prevquestionsgqa == "@" . $cqn[3] . "@") {
                     $aViewUrls['output'] .= " selected='selected'";
                 }
                 $aViewUrls['output'] .= ">{$cqn['0']}</option>\n";
             }
         }
         $aViewUrls['output'] .= "\t\t</select>\n" . "\t\t<br /><span id='prevQuestionSGQALabel'>" . $clang->gT("Answers from previous questions") . "</span>\n" . "\t</div>\n";
         // Token tab
         $aViewUrls['output'] .= "\t<div id='TOKENATTRS'>\n" . "\t\t<select name='tokenAttr' id='tokenAttr' size='7'>\n";
         foreach (getTokenFieldsAndNames($iSurveyID) as $tokenattr => $tokenattrName) {
             $aViewUrls['output'] .= "\t\t<option value='{TOKEN:" . strtoupper($tokenattr) . "}'>" . HTMLEscape($tokenattrName['description']) . "</option>\n";
         }
         $aViewUrls['output'] .= "\t\t</select>\n" . "\t\t<br /><span id='tokenAttrLabel'>" . $clang->gT("Attributes values from the participant's token") . "</span>\n" . "\t</div>\n";
         // Regexp Tab
         $aViewUrls['output'] .= "\t<div id='REGEXP' style='display:block;'>\n" . "\t\t<textarea name='ConditionRegexp' id='ConditionRegexp' rows='5' cols='113'>{$EDITConditionRegexp}</textarea>\n" . "\t\t<br /><div id='ConditionRegexpLabel'><a href=\"http://docs.limesurvey.org/tiki-index.php?page=Using+Regular+Expressions\" target=\"_blank\">" . $clang->gT("Regular expression") . "</a></div>\n" . "\t</div>\n";
         $aViewUrls['output'] .= "</div>\n";
         // end conditiontarget div
         $this->getController()->_js_admin_includes(Yii::app()->getConfig("adminscripts") . 'conditions.js');
         $this->getController()->_js_admin_includes(Yii::app()->getConfig("generalscripts") . 'jquery/lime-conditions-tabs.js');
         if ($subaction == "editthiscondition" && isset($p_cid)) {
             $submitLabel = $clang->gT("Update condition");
             $submitSubaction = "updatecondition";
             $submitcid = sanitize_int($p_cid);
         } else {
             $submitLabel = $clang->gT("Add condition");
             $submitSubaction = "insertcondition";
             $submitcid = "";
         }
         $aViewUrls['output'] .= "</div>\n" . "</div>\n";
         // Begin buttons row
         $aViewUrls['output'] .= "<div class='condition-tbl-full'>\n" . "\t<input type='reset' id='resetForm' value='" . $clang->gT("Clear") . "' />\n" . "\t<input type='submit' value='" . $submitLabel . "' />\n" . "<input type='hidden' name='sid' value='{$iSurveyID}' />\n" . "<input type='hidden' name='gid' value='{$gid}' />\n" . "<input type='hidden' name='qid' value='{$qid}' />\n" . "<input type='hidden' name='subaction' value='{$submitSubaction}' />\n" . "<input type='hidden' name='cqid' id='cqid' value='' />\n" . "<input type='hidden' name='cid' id='cid' value='" . $submitcid . "' />\n" . "<input type='hidden' name='editTargetTab' id='editTargetTab' value='' />\n" . "<input type='hidden' name='editSourceTab' id='editSourceTab' value='' />\n" . "<input type='hidden' name='canswersToSelect' id='canswersToSelect' value='' />\n" . "</div>\n" . "</form>\n";
         if (!isset($js_getAnswers_onload)) {
             $js_getAnswers_onload = '';
         }
         $aViewUrls['output'] .= "<script type='text/javascript'>\n" . "<!--\n" . "\t" . $js_getAnswers_onload . "\n";
         if (isset($p_method)) {
             $aViewUrls['output'] .= "\tdocument.getElementById('method').value='" . $p_method . "';\n";
         }
         if ($subaction == "editthiscondition") {
             // in edit mode we read previous values in order to dusplay them in the corresponding inputs
             if (isset($_POST['EDITConditionConst']) && $_POST['EDITConditionConst'] != '') {
                 // In order to avoid issues with backslash escaping, I don't use javascript to set the value
                 // Thus the value is directly set when creating the Textarea element
                 //$aViewUrls['output'] .= "\tdocument.getElementById('ConditionConst').value='".HTMLEscape($_POST['EDITConditionConst'])."';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#CONST';\n";
             } elseif (isset($_POST['EDITprevQuestionSGQA']) && $_POST['EDITprevQuestionSGQA'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('prevQuestionSGQA').value='" . HTMLEscape($_POST['EDITprevQuestionSGQA']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#PREVQUESTIONS';\n";
             } elseif (isset($_POST['EDITtokenAttr']) && $_POST['EDITtokenAttr'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('tokenAttr').value='" . HTMLEscape($_POST['EDITtokenAttr']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#TOKENATTRS';\n";
             } elseif (isset($_POST['EDITConditionRegexp']) && $_POST['EDITConditionRegexp'] != '') {
                 // In order to avoid issues with backslash escaping, I don't use javascript to set the value
                 // Thus the value is directly set when creating the Textarea element
                 //$aViewUrls['output'] .= "\tdocument.getElementById('ConditionRegexp').value='".HTMLEscape($_POST['EDITConditionRegexp'])."';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#REGEXP';\n";
             } elseif (isset($_POST['EDITcanswers']) && is_array($_POST['EDITcanswers'])) {
                 // was a predefined answers post
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#CANSWERSTAB';\n";
                 $aViewUrls['output'] .= "\t\$('#canswersToSelect').val('" . $_POST['EDITcanswers'][0] . "');\n";
             }
             if (isset($_POST['csrctoken']) && $_POST['csrctoken'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('csrctoken').value='" . HTMLEscape($_POST['csrctoken']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editSourceTab').value='#SRCTOKENATTRS';\n";
             } else {
                 if (isset($_POST['cquestions']) && $_POST['cquestions'] != '') {
                     $aViewUrls['output'] .= "\tdocument.getElementById('cquestions').value='" . HTMLEscape($_POST['cquestions']) . "';\n";
                     $aViewUrls['output'] .= "\tdocument.getElementById('editSourceTab').value='#SRCPREVQUEST';\n";
                 }
             }
         } else {
             // in other modes, for the moment we do the same as for edit mode
             if (isset($_POST['ConditionConst']) && $_POST['ConditionConst'] != '') {
                 // In order to avoid issues with backslash escaping, I don't use javascript to set the value
                 // Thus the value is directly set when creating the Textarea element
                 //$aViewUrls['output'] .= "\tdocument.getElementById('ConditionConst').value='".HTMLEscape($_POST['ConditionConst'])."';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#CONST';\n";
             } elseif (isset($_POST['prevQuestionSGQA']) && $_POST['prevQuestionSGQA'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('prevQuestionSGQA').value='" . HTMLEscape($_POST['prevQuestionSGQA']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#PREVQUESTIONS';\n";
             } elseif (isset($_POST['tokenAttr']) && $_POST['tokenAttr'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('tokenAttr').value='" . HTMLEscape($_POST['tokenAttr']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#TOKENATTRS';\n";
             } elseif (isset($_POST['ConditionRegexp']) && $_POST['ConditionRegexp'] != '') {
                 // In order to avoid issues with backslash escaping, I don't use javascript to set the value
                 // Thus the value is directly set when creating the Textarea element
                 //$aViewUrls['output'] .= "\tdocument.getElementById('ConditionRegexp').value='".HTMLEscape($_POST['ConditionRegexp'])."';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#REGEXP';\n";
             } else {
                 // was a predefined answers post
                 if (isset($_POST['cquestions'])) {
                     $aViewUrls['output'] .= "\tdocument.getElementById('cquestions').value='" . HTMLEscape($_POST['cquestions']) . "';\n";
                 }
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#CANSWERSTAB';\n";
             }
             if (isset($_POST['csrctoken']) && $_POST['csrctoken'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('csrctoken').value='" . HTMLEscape($_POST['csrctoken']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editSourceTab').value='#SRCTOKENATTRS';\n";
             } else {
                 if (isset($_POST['cquestions'])) {
                     $aViewUrls['output'] .= "\tdocument.getElementById('cquestions').value='" . javascriptEscape($_POST['cquestions']) . "';\n";
                 }
                 $aViewUrls['output'] .= "\tdocument.getElementById('editSourceTab').value='#SRCPREVQUEST';\n";
             }
         }
         if (isset($p_scenario)) {
             $aViewUrls['output'] .= "\tdocument.getElementById('scenario').value='" . $p_scenario . "';\n";
         }
         $aViewUrls['output'] .= "-->\n" . "</script>\n";
     }
     //END: DISPLAY THE ADD or EDIT CONDITION FORM
     $conditionsoutput = $aViewUrls['output'];
     $aData['conditionsoutput'] = $conditionsoutput;
     $this->_renderWrappedTemplate('conditions', $aViewUrls, $aData);
     // TMSW Conditions->Relevance:  Must call LEM->ConvertConditionsToRelevance() whenever Condition is added or updated - what is best location for that action?
 }
 function actionAction($surveyid, $language = null)
 {
     $sLanguage = $language;
     ob_start(function ($buffer, $phase) {
         App()->getClientScript()->render($buffer);
         App()->getClientScript()->reset();
         return $buffer;
     });
     ob_implicit_flush(false);
     $iSurveyID = (int) $surveyid;
     //$postlang = returnglobal('lang');
     Yii::import('application.libraries.admin.progressbar', true);
     Yii::app()->loadHelper("admin/statistics");
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('surveytranslator');
     App()->getClientScript()->registerPackage('jqueryui');
     App()->getClientScript()->registerPackage('jquery-touch-punch');
     App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "survey_runtime.js");
     $data = array();
     if (!isset($iSurveyID)) {
         $iSurveyID = returnGlobal('sid');
     } else {
         $iSurveyID = (int) $iSurveyID;
     }
     if (!$iSurveyID) {
         //This next line ensures that the $iSurveyID value is never anything but a number.
         safeDie('You have to provide a valid survey ID.');
     }
     if ($iSurveyID) {
         $actresult = Survey::model()->findAll('sid = :sid AND active = :active', array(':sid' => $iSurveyID, ':active' => 'Y'));
         //Checked
         if (count($actresult) == 0) {
             safeDie('You have to provide a valid survey ID.');
         } else {
             $surveyinfo = getSurveyInfo($iSurveyID);
             // CHANGE JSW_NZ - let's get the survey title for display
             $thisSurveyTitle = $surveyinfo["name"];
             // CHANGE JSW_NZ - let's get css from individual template.css - so define path
             $thisSurveyCssPath = getTemplateURL($surveyinfo["template"]);
             if ($surveyinfo['publicstatistics'] != 'Y') {
                 safeDie('The public statistics for this survey are deactivated.');
             }
             //check if graphs should be shown for this survey
             if ($surveyinfo['publicgraphs'] == 'Y') {
                 $publicgraphs = 1;
             } else {
                 $publicgraphs = 0;
             }
         }
     }
     //we collect all the output within this variable
     $statisticsoutput = '';
     //for creating graphs we need some more scripts which are included here
     //True -> include
     //False -> forget about charts
     if (isset($publicgraphs) && $publicgraphs == 1) {
         require_once APPPATH . 'third_party/pchart/pchart/pChart.class';
         require_once APPPATH . 'third_party/pchart/pchart/pData.class';
         require_once APPPATH . 'third_party/pchart/pchart/pCache.class';
         $MyCache = new pCache(Yii::app()->getConfig("tempdir") . DIRECTORY_SEPARATOR);
         //$currentuser is created as prefix for pchart files
         if (isset($_SERVER['REDIRECT_REMOTE_USER'])) {
             $currentuser = $_SERVER['REDIRECT_REMOTE_USER'];
         } else {
             if (session_id()) {
                 $currentuser = substr(session_id(), 0, 15);
             } else {
                 $currentuser = "******";
             }
         }
     }
     // Set language for questions and labels to base language of this survey
     if ($sLanguage == null || !in_array($sLanguage, Survey::model()->findByPk($iSurveyID)->getAllLanguages())) {
         $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
     } else {
         $sLanguage = sanitize_languagecode($sLanguage);
     }
     //set survey language for translations
     SetSurveyLanguage($iSurveyID, $sLanguage);
     //Create header
     sendCacheHeaders();
     $condition = false;
     $sitename = Yii::app()->getConfig("sitename");
     $data['surveylanguage'] = $sLanguage;
     $data['sitename'] = $sitename;
     $data['condition'] = $condition;
     $data['thisSurveyCssPath'] = $thisSurveyCssPath;
     /*
      * only show questions where question attribute "public_statistics" is set to "1"
      */
     $query = "SELECT q.* , group_name, group_order FROM {{questions}} q, {{groups}} g, {{question_attributes}} qa\n                    WHERE g.gid = q.gid AND g.language = :lang1 AND q.language = :lang2 AND q.sid = :surveyid AND q.qid = qa.qid AND q.parent_qid = 0 AND qa.attribute = 'public_statistics'";
     $databasetype = Yii::app()->db->getDriverName();
     if ($databasetype == 'mssql' || $databasetype == "sqlsrv" || $databasetype == "dblib") {
         $query .= " AND CAST(CAST(qa.value as varchar) as int)='1'\n";
     } else {
         $query .= " AND qa.value='1'\n";
     }
     //execute query
     $result = Yii::app()->db->createCommand($query)->bindParam(":lang1", $sLanguage, PDO::PARAM_STR)->bindParam(":lang2", $sLanguage, PDO::PARAM_STR)->bindParam(":surveyid", $iSurveyID, PDO::PARAM_INT)->queryAll();
     //store all the data in $rows
     $rows = $result;
     //SORT IN NATURAL ORDER!
     usort($rows, 'groupOrderThenQuestionOrder');
     //put the question information into the filter array
     foreach ($rows as $row) {
         //store some column names in $filters array
         $filters[] = array($row['qid'], $row['gid'], $row['type'], $row['title'], $row['group_name'], flattenText($row['question']));
     }
     //number of records for this survey
     $totalrecords = 0;
     //count number of answers
     $query = "SELECT count(*) FROM {{survey_" . intval($iSurveyID) . "}}";
     //if incompleted answers should be filtert submitdate has to be not null
     //this setting is taken from config-defaults.php
     if (Yii::app()->getConfig("filterout_incomplete_answers") == true) {
         $query .= " WHERE {{survey_" . intval($iSurveyID) . "}}.submitdate is not null";
     }
     $result = Yii::app()->db->createCommand($query)->queryAll();
     //$totalrecords = total number of answers
     foreach ($result as $row) {
         $totalrecords = reset($row);
     }
     //this is the array which we need later...
     $summary = array();
     //...while this is the array from copy/paste which we don't want to replace because this is a nasty source of error
     $allfields = array();
     //---------- CREATE SGQA OF ALL QUESTIONS WHICH USE "PUBLIC_STATISTICS" ----------
     /*
              * let's go through the filter array which contains
              *     ['qid'],
              ['gid'],
              ['type'],
              ['title'],
              ['group_name'],
              ['question'];
     */
     $currentgroup = '';
     // use to check if there are any question with public statistics
     if (isset($filters)) {
         foreach ($filters as $flt) {
             //SGQ identifier
             $myfield = "{$iSurveyID}X{$flt[1]}X{$flt[0]}";
             //let's switch through the question type for each question
             switch ($flt[2]) {
                 case "K":
                     // Multiple Numerical
                 // Multiple Numerical
                 case "Q":
                     // Multiple Short Text
                     //get answers
                     $query = "SELECT title as code, question as answer FROM {{questions}} WHERE parent_qid=:flt_0 AND language = :lang ORDER BY question_order";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     //go through all the (multiple) answers
                     foreach ($result as $row) {
                         $myfield2 = $flt[2] . $myfield . reset($row);
                         $allfields[] = $myfield2;
                     }
                     break;
                 case "A":
                     // ARRAY OF 5 POINT CHOICE QUESTIONS
                 // ARRAY OF 5 POINT CHOICE QUESTIONS
                 case "B":
                     // ARRAY OF 10 POINT CHOICE QUESTIONS
                 // ARRAY OF 10 POINT CHOICE QUESTIONS
                 case "C":
                     // ARRAY OF YES\No\gT("Uncertain") QUESTIONS
                 // ARRAY OF YES\No\gT("Uncertain") QUESTIONS
                 case "E":
                     // ARRAY OF Increase/Same/Decrease QUESTIONS
                 // ARRAY OF Increase/Same/Decrease QUESTIONS
                 case "F":
                     // FlEXIBLE ARRAY
                 // FlEXIBLE ARRAY
                 case "H":
                     // ARRAY (By Column)
                     //get answers
                     $query = "SELECT title as code, question as answer FROM {{questions}} WHERE parent_qid=:flt_0 AND language = :lang ORDER BY question_order";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     //go through all the (multiple) answers
                     foreach ($result as $row) {
                         $myfield2 = $myfield . reset($row);
                         $allfields[] = $myfield2;
                     }
                     break;
                     // all "free text" types (T, U, S)  get the same prefix ("T")
                 // all "free text" types (T, U, S)  get the same prefix ("T")
                 case "T":
                     // Long free text
                 // Long free text
                 case "U":
                     // Huge free text
                 // Huge free text
                 case "S":
                     // Short free text
                     $myfield = "T{$myfield}";
                     $allfields[] = $myfield;
                     break;
                 case ";":
                     //ARRAY (Multi Flex) (Text)
                 //ARRAY (Multi Flex) (Text)
                 case ":":
                     //ARRAY (Multi Flex) (Numbers)
                     $query = "SELECT title, question FROM {{questions}} WHERE parent_qid=:flt_0 AND language=:lang AND scale_id = 0 ORDER BY question_order";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     foreach ($result as $row) {
                         $fquery = "SELECT * FROM {{questions}} WHERE parent_qid = :flt_0 AND language = :lang AND scale_id = 1 ORDER BY question_order, title";
                         $fresult = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                         foreach ($fresult as $frow) {
                             $myfield2 = $myfield . reset($row) . "_" . $frow['title'];
                             $allfields[] = $myfield2;
                         }
                     }
                     break;
                 case "R":
                     //RANKING
                     //get some answers
                     $query = "SELECT code, answer FROM {{answers}} WHERE qid = :flt_0 AND language = :lang ORDER BY sortorder, answer";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     //get number of answers
                     $count = count($result);
                     //loop through all answers. if there are 3 items to rate there will be 3 statistics
                     for ($i = 1; $i <= $count; $i++) {
                         $myfield2 = "R" . $myfield . $i . "-" . strlen($i);
                         $allfields[] = $myfield2;
                     }
                     break;
                     //Boilerplate questions are only used to put some text between other questions -> no analysis needed
                 //Boilerplate questions are only used to put some text between other questions -> no analysis needed
                 case "X":
                     //This is a boilerplate question and it has no business in this script
                     break;
                 case "1":
                     // MULTI SCALE
                     //get answers
                     $query = "SELECT title, question FROM {{questions}} WHERE parent_qid = :flt_0 AND language = :lang ORDER BY question_order";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     //loop through answers
                     foreach ($result as $row) {
                         //----------------- LABEL 1 ---------------------
                         $myfield2 = $myfield . $row['title'] . "#0";
                         $allfields[] = $myfield2;
                         //----------------- LABEL 2 ---------------------
                         $myfield2 = $myfield . $row['title'] . "#1";
                         $allfields[] = $myfield2;
                     }
                     //end WHILE -> loop through all answers
                     break;
                 case "P":
                     //P - Multiple choice with comments
                 //P - Multiple choice with comments
                 case "M":
                     //M - Multiple choice
                 //M - Multiple choice
                 case "N":
                     //N - Numerical input
                 //N - Numerical input
                 case "D":
                     //D - Date
                     $myfield2 = $flt[2] . $myfield;
                     $allfields[] = $myfield2;
                     break;
                 default:
                     //Default settings
                     $allfields[] = $myfield;
                     break;
             }
             //end switch -> check question types and create filter forms
         }
         //end foreach -> loop through all questions with "public_statistics" enabled
     }
     // end if -> for removing the error message in case there are no filters
     $summary = $allfields;
     // Get the survey inforamtion
     $thissurvey = getSurveyInfo($surveyid, $sLanguage);
     //SET THE TEMPLATE DIRECTORY
     $data['sTemplatePath'] = $surveyinfo['template'];
     // surveyinfo=getSurveyInfo and if survey don't exist : stop before.
     //---------- CREATE STATISTICS ----------
     $redata = compact(array_keys(get_defined_vars()));
     doHeader();
     echo templatereplace(file_get_contents(getTemplatePath($data['sTemplatePath']) . DIRECTORY_SEPARATOR . "startpage.pstpl"), array(), $redata);
     //some progress bar stuff
     // Create progress bar which is shown while creating the results
     $prb = new ProgressBar();
     $prb->pedding = 2;
     // Bar Pedding
     $prb->brd_color = "#404040 #dfdfdf #dfdfdf #404040";
     // Bar Border Color
     $prb->setFrame();
     // set ProgressBar Frame
     $prb->frame['left'] = 50;
     // Frame position from left
     $prb->frame['top'] = 80;
     // Frame position from top
     $prb->addLabel('text', 'txt1', gT("Please wait ..."));
     // add Text as Label 'txt1' and value 'Please wait'
     $prb->addLabel('percent', 'pct1');
     // add Percent as Label 'pct1'
     $prb->addButton('btn1', gT('Go back'), '?action=statistics&amp;sid=' . $iSurveyID);
     // add Button as Label 'btn1' and action '?restart=1'
     //progress bar starts with 35%
     $process_status = 35;
     $prb->show();
     // show the ProgressBar
     // 1: Get list of questions with answers chosen
     //"Getting Questions and Answer ..." is shown above the bar
     $prb->setLabelValue('txt1', gT('Getting questions and answers ...'));
     $prb->moveStep(5);
     // creates array of post variable names
     for (reset($_POST); $key = key($_POST); next($_POST)) {
         $postvars[] = $key;
     }
     $data['thisSurveyTitle'] = $thisSurveyTitle;
     $data['totalrecords'] = $totalrecords;
     $data['summary'] = $summary;
     //show some main data at the beginnung
     // CHANGE JSW_NZ - let's allow html formatted questions to show
     //push progress bar from 35 to 40
     $process_status = 40;
     //Show Summary results
     if (isset($summary) && $summary) {
         //"Generating Summaries ..." is shown above the progress bar
         $prb->setLabelValue('txt1', gT('Generating summaries ...'));
         $prb->moveStep($process_status);
         //let's run through the survey // Fixed bug 3053 with array_unique
         $runthrough = array_unique($summary);
         //loop through all selected questions
         foreach ($runthrough as $rt) {
             //update progress bar
             if ($process_status < 100) {
                 $process_status++;
             }
             $prb->moveStep($process_status);
         }
         // end foreach -> loop through all questions
         $helper = new statistics_helper();
         $statisticsoutput .= $helper->generate_statistics($iSurveyID, $summary, $summary, $publicgraphs, 'html', null, $sLanguage, false);
     }
     //end if -> show summary results
     $data['statisticsoutput'] = $statisticsoutput;
     //done! set progress bar to 100%
     if (isset($prb)) {
         $prb->setLabelValue('txt1', gT('Completed'));
         $prb->moveStep(100);
         $prb->hide();
     }
     $redata = compact(array_keys(get_defined_vars()));
     $data['redata'] = $redata;
     Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . 'statistics_user.js');
     $this->renderPartial('/statistics_user_view', $data);
     //output footer
     echo getFooter();
     //Delete all Session Data
     Yii::app()->session['finished'] = true;
 }
Exemplo n.º 22
0
 public function dumplabel()
 {
     $lid = sanitize_int(Yii::app()->request->getParam('lid'));
     // DUMP THE RELATED DATA FOR A SINGLE QUESTION INTO A SQL FILE FOR IMPORTING LATER ON OR
     // ON ANOTHER SURVEY SETUP DUMP ALL DATA WITH RELATED QID FROM THE FOLLOWING TABLES
     // 1. questions
     // 2. answers
     $lids = returnGlobal('lids');
     if (!$lid && !$lids) {
         die('No LID has been provided. Cannot dump label set.');
     }
     if ($lid) {
         $lids = array($lid);
     }
     $lids = array_map('sanitize_int', $lids);
     $fn = "limesurvey_labelset_" . implode('_', $lids) . ".lsl";
     $xml = getXMLWriter();
     $this->_addHeaders($fn, "text/html/force-download", "Mon, 26 Jul 1997 05:00:00 GMT", "cache");
     $xml->openURI('php://output');
     $xml->setIndent(TRUE);
     $xml->startDocument('1.0', 'UTF-8');
     $xml->startElement('document');
     $xml->writeElement('LimeSurveyDocType', 'Label set');
     $xml->writeElement('DBVersion', getGlobalSetting("DBVersion"));
     // Label sets table
     $lsquery = "SELECT * FROM {{labelsets}} WHERE lid=" . implode(' or lid=', $lids);
     buildXMLFromQuery($xml, $lsquery, 'labelsets');
     // Labels
     $lquery = "SELECT lid, code, title, sortorder, language, assessment_value FROM {{labels}} WHERE lid=" . implode(' or lid=', $lids);
     buildXMLFromQuery($xml, $lquery, 'labels');
     $xml->endElement();
     // close columns
     $xml->endDocument();
     exit;
 }
Exemplo n.º 23
0
 /**
  * Process labels form data depending on $action.
  *
  * @access public
  * @return void
  */
 public function process()
 {
     $action = returnGlobal('action');
     Yii::app()->loadHelper('admin/label');
     $lid = returnGlobal('lid');
     if ($action == "updateset" && Permission::model()->hasGlobalPermission('labelsets', 'update')) {
         updateset($lid);
         Yii::app()->setFlashMessage(gT("Label set properties sucessfully updated."), 'success');
     }
     if ($action == "insertlabelset" && Permission::model()->hasGlobalPermission('labelsets', 'create')) {
         $lid = insertlabelset();
     }
     if (($action == "modlabelsetanswers" || $action == "ajaxmodlabelsetanswers") && Permission::model()->hasGlobalPermission('labelsets', 'update')) {
         modlabelsetanswers($lid);
     }
     if ($action == "deletelabelset" && Permission::model()->hasGlobalPermission('labelsets', 'delete')) {
         if (deletelabelset($lid)) {
             Yii::app()->setFlashMessage(gT("Label set sucessfully deleted."), 'success');
             $lid = 0;
         }
     }
     if ($lid) {
         $this->getController()->redirect(array("admin/labels/sa/view/lid/" . $lid));
     } else {
         $this->getController()->redirect(array("admin/labels/sa/view"));
     }
 }
Exemplo n.º 24
0
 /**
  * dataentry::insert()
  * insert new dataentry
  * @return
  */
 public function insert()
 {
     $clang = Yii::app()->lang;
     $subaction = Yii::app()->request->getPost('subaction');
     $surveyid = Yii::app()->request->getPost('sid');
     $lang = isset($_POST['lang']) ? Yii::app()->request->getPost('lang') : NULL;
     $aData = array('surveyid' => $surveyid, 'lang' => $lang, 'clang' => $clang);
     if (hasSurveyPermission($surveyid, 'responses', 'read')) {
         if ($subaction == "insert" && hasSurveyPermission($surveyid, 'responses', 'create')) {
             $surveytable = "{{survey_{$surveyid}}}";
             $thissurvey = getSurveyInfo($surveyid);
             $errormsg = "";
             Yii::app()->loadHelper("database");
             $aViewUrls['display']['menu_bars']['browse'] = $clang->gT("Data entry");
             $aDataentryoutput = '';
             $aDataentrymsgs = array();
             $hiddenfields = '';
             $lastanswfortoken = '';
             // check if a previous answer has been submitted or saved
             $rlanguage = '';
             if (isset($_POST['token'])) {
                 $tokencompleted = "";
                 $tcquery = "SELECT completed from {{tokens_{$surveyid}}} WHERE token='{$_POST['token']}'";
                 //dbQuoteAll($_POST['token'],true);
                 $tcresult = dbExecuteAssoc($tcquery);
                 $tcresult = $tcresult->readAll();
                 $tccount = count($tcresult);
                 foreach ($tcresult as $tcrow) {
                     $tokencompleted = $tcrow['completed'];
                 }
                 if ($tccount < 1) {
                     // token doesn't exist in token table
                     $lastanswfortoken = 'UnknownToken';
                 } elseif ($thissurvey['anonymized'] == "Y") {
                     // token exist but survey is anonymous, check completed state
                     if ($tokencompleted != "" && $tokencompleted != "N") {
                         // token is completed
                         $lastanswfortoken = 'PrivacyProtected';
                     }
                 } else {
                     // token is valid, survey not anonymous, try to get last recorded response id
                     $aquery = "SELECT id,startlanguage FROM {$surveytable} WHERE token='" . $_POST['token'] . "'";
                     //dbQuoteAll($_POST['token'],true);
                     $aresult = dbExecuteAssoc($aquery);
                     foreach ($aresult->readAll() as $arow) {
                         if ($tokencompleted != "N") {
                             $lastanswfortoken = $arow['id'];
                         }
                         $rlanguage = $arow['startlanguage'];
                     }
                 }
             }
             // First Check if the survey uses tokens and if a token has been provided
             if (tableExists('{{tokens_' . $thissurvey['sid'] . '}}') && !$_POST['token']) {
                 $errormsg = CHtml::tag('div', array('class' => 'warningheader'), $clang->gT("Error"));
                 $errormsg .= CHtml::tag('p', array(), $clang->gT("This is a closed-access survey, so you must supply a valid token.  Please contact the administrator for assistance."));
             } elseif (tableExists('{{tokens_' . $thissurvey['sid'] . '}}') && $lastanswfortoken == 'UnknownToken') {
                 $errormsg = CHtml::tag('div', array('class' => 'warningheader'), $clang->gT("Error"));
                 $errormsg .= CHtml::tag('p', array(), $clang->gT("The token you have provided is not valid or has already been used."));
             } elseif (tableExists('{{tokens_' . $thissurvey['sid'] . '}}') && $lastanswfortoken != '') {
                 $errormsg = CHtml::tag('div', array('class' => 'warningheader'), $clang->gT("Error"));
                 $errormsg .= CHtml::tag('p', array(), $clang->gT("There is already a recorded answer for this token"));
                 if ($lastanswfortoken != 'PrivacyProtected') {
                     $errormsg .= "<br /><br />" . $clang->gT("Follow the following link to update it") . ":\n";
                     $errormsg .= CHtml::link("[id:{$lastanswfortoken}]", Yii::app()->baseUrl . ('/admin/dataentry/editdata/subaction/edit/id/' . $lastanswfortoken . '/surveyid/' . $surveyid . '/lang/' . $rlanguage), array('title' => $clang->gT("Edit this entry")));
                 } else {
                     $errormsg .= "<br /><br />" . $clang->gT("This surveys uses anonymized responses, so you can't update your response.") . "\n";
                 }
             } else {
                 $last_db_id = 0;
                 if (isset($_POST['save']) && $_POST['save'] == "on") {
                     $aData['save'] = TRUE;
                     $saver['identifier'] = $_POST['save_identifier'];
                     $saver['language'] = $_POST['save_language'];
                     $saver['password'] = $_POST['save_password'];
                     $saver['passwordconfirm'] = $_POST['save_confirmpassword'];
                     $saver['email'] = $_POST['save_email'];
                     if (!returnGlobal('redo')) {
                         $password = md5($saver['password']);
                     } else {
                         $password = $saver['password'];
                     }
                     $errormsg = "";
                     if (!$saver['identifier']) {
                         $errormsg .= $clang->gT("Error") . ": " . $clang->gT("You must supply a name for this saved session.");
                     }
                     if (!$saver['password']) {
                         $errormsg .= $clang->gT("Error") . ": " . $clang->gT("You must supply a password for this saved session.");
                     }
                     if ($saver['password'] != $saver['passwordconfirm']) {
                         $errormsg .= $clang->gT("Error") . ": " . $clang->gT("Your passwords do not match.");
                     }
                     $aData['errormsg'] = $errormsg;
                     if ($errormsg) {
                         foreach ($_POST as $key => $val) {
                             if (substr($key, 0, 4) != "save" && $key != "action" && $key != "sid" && $key != "datestamp" && $key != "ipaddr") {
                                 $hiddenfields .= CHtml::hiddenField($key, $val);
                                 //$aDataentryoutput .= "<input type='hidden' name='$key' value='$val' />\n";
                             }
                         }
                     }
                 }
                 //BUILD THE SQL TO INSERT RESPONSES
                 $baselang = Survey::model()->findByPk($surveyid)->language;
                 $fieldmap = createFieldMap($surveyid, 'full', false, false, getBaseLanguageFromSurveyID($surveyid));
                 $insert_data = array();
                 $_POST['startlanguage'] = $baselang;
                 if ($thissurvey['datestamp'] == "Y") {
                     $_POST['startdate'] = $_POST['datestamp'];
                 }
                 if (isset($_POST['closerecord'])) {
                     if ($thissurvey['datestamp'] == "Y") {
                         $_POST['submitdate'] = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig('timeadjust'));
                     } else {
                         $_POST['submitdate'] = date("Y-m-d H:i:s", mktime(0, 0, 0, 1, 1, 1980));
                     }
                 }
                 foreach ($fieldmap as $irow) {
                     $fieldname = $irow['fieldname'];
                     if (isset($_POST[$fieldname])) {
                         if ($_POST[$fieldname] == "" && ($irow['type'] == 'D' || $irow['type'] == 'N' || $irow['type'] == 'K')) {
                             // can't add '' in Date column
                             // Do nothing
                         } else {
                             if ($irow['type'] == '|') {
                                 if (!strpos($irow['fieldname'], "_filecount")) {
                                     $json = $_POST[$fieldname];
                                     $phparray = json_decode(stripslashes($json));
                                     $filecount = 0;
                                     for ($i = 0; $filecount < count($phparray); $i++) {
                                         if ($_FILES[$fieldname . "_file_" . $i]['error'] != 4) {
                                             $target = Yii::app()->getConfig('uploaddir') . "/surveys/" . $thissurvey['sid'] . "/files/" . randomChars(20);
                                             $size = 0.001 * $_FILES[$fieldname . "_file_" . $i]['size'];
                                             $name = rawurlencode($_FILES[$fieldname . "_file_" . $i]['name']);
                                             if (move_uploaded_file($_FILES[$fieldname . "_file_" . $i]['tmp_name'], $target)) {
                                                 $phparray[$filecount]->filename = basename($target);
                                                 $phparray[$filecount]->name = $name;
                                                 $phparray[$filecount]->size = $size;
                                                 $pathinfo = pathinfo($_FILES[$fieldname . "_file_" . $i]['name']);
                                                 $phparray[$filecount]->ext = $pathinfo['extension'];
                                                 $filecount++;
                                             }
                                         }
                                     }
                                     $insert_data[$fieldname] = ls_json_encode($phparray);
                                 } else {
                                     $insert_data[$fieldname] = count($phparray);
                                 }
                             } elseif ($irow['type'] == 'D') {
                                 Yii::app()->loadLibrary('Date_Time_Converter');
                                 $qidattributes = getQuestionAttributeValues($irow['qid'], $irow['type']);
                                 $dateformatdetails = getDateFormatDataForQID($qidattributes, $thissurvey);
                                 $datetimeobj = new Date_Time_Converter($_POST[$fieldname], $dateformatdetails['phpdate']);
                                 $insert_data[$fieldname] = $datetimeobj->convert("Y-m-d H:i:s");
                             } else {
                                 $insert_data[$fieldname] = $_POST[$fieldname];
                             }
                         }
                     }
                 }
                 Survey_dynamic::sid($surveyid);
                 $new_response = new Survey_dynamic();
                 foreach ($insert_data as $column => $value) {
                     $new_response->{$column} = $value;
                 }
                 $new_response->save();
                 $last_db_id = $new_response->getPrimaryKey();
                 if (isset($_POST['closerecord']) && isset($_POST['token']) && $_POST['token'] != '') {
                     // get submit date
                     if (isset($_POST['closedate'])) {
                         $submitdate = $_POST['closedate'];
                     } else {
                         $submitdate = dateShift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust);
                     }
                     // check how many uses the token has left
                     $usesquery = "SELECT usesleft FROM {{tokens_}}{$surveyid} WHERE token='" . $_POST['token'] . "'";
                     $usesresult = dbExecuteAssoc($usesquery);
                     $usesrow = $usesresult->readAll();
                     //$usesresult->row_array()
                     if (isset($usesrow)) {
                         $usesleft = $usesrow[0]['usesleft'];
                     }
                     // query for updating tokens
                     $utquery = "UPDATE {{tokens_{$surveyid}}}\n";
                     if (isTokenCompletedDatestamped($thissurvey)) {
                         if (isset($usesleft) && $usesleft <= 1) {
                             $utquery .= "SET usesleft=usesleft-1, completed='{$submitdate}'\n";
                         } else {
                             $utquery .= "SET usesleft=usesleft-1\n";
                         }
                     } else {
                         if (isset($usesleft) && $usesleft <= 1) {
                             $utquery .= "SET usesleft=usesleft-1, completed='Y'\n";
                         } else {
                             $utquery .= "SET usesleft=usesleft-1\n";
                         }
                     }
                     $utquery .= "WHERE token='" . $_POST['token'] . "'";
                     $utresult = dbExecuteAssoc($utquery);
                     //Yii::app()->db->Execute($utquery) or safeDie ("Couldn't update tokens table!<br />\n$utquery<br />\n".Yii::app()->db->ErrorMsg());
                     // save submitdate into survey table
                     $srid = Yii::app()->db->getLastInsertID();
                     // Yii::app()->db->getLastInsertID();
                     $sdquery = "UPDATE {{survey_{$surveyid}}} SET submitdate='" . $submitdate . "' WHERE id={$srid}\n";
                     $sdresult = dbExecuteAssoc($sdquery) or safeDie("Couldn't set submitdate response in survey table!<br />\n{$sdquery}<br />\n");
                     $last_db_id = Yii::app()->db->getLastInsertID();
                 }
                 if (isset($_POST['save']) && $_POST['save'] == "on") {
                     $srid = Yii::app()->db->getLastInsertID();
                     //Yii::app()->db->getLastInsertID();
                     $aUserData = Yii::app()->session;
                     //CREATE ENTRY INTO "saved_control"
                     $saved_control_table = '{{saved_control}}';
                     $columns = array("sid", "srid", "identifier", "access_code", "email", "ip", "refurl", 'saved_thisstep', "status", "saved_date");
                     $values = array("'" . $surveyid . "'", "'" . $srid . "'", "'" . $saver['identifier'] . "'", "'" . $password . "'", "'" . $saver['email'] . "'", "'" . $aUserData['ip_address'] . "'", "'" . getenv("HTTP_REFERER") . "'", 0, "'" . "S" . "'", "'" . dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", "'" . Yii::app()->getConfig('timeadjust')) . "'");
                     $SQL = "INSERT INTO {$saved_control_table}\n                        (" . implode(',', $columns) . ")\n                        VALUES\n                        (" . implode(',', $values) . ")";
                     /*$scdata = array("sid"=>$surveyid,
                       "srid"=>$srid,
                       "identifier"=>$saver['identifier'],
                       "access_code"=>$password,
                       "email"=>$saver['email'],
                       "ip"=>$aUserData['ip_address'],
                       "refurl"=>getenv("HTTP_REFERER"),
                       'saved_thisstep' => 0,
                       "status"=>"S",
                       "saved_date"=>dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig('timeadjust')));
                       $this->load->model('saved_control_model');*/
                     if (dbExecuteAssoc($SQL)) {
                         $scid = Yii::app()->db->getLastInsertID();
                         // Yii::app()->db->getLastInsertID("{{saved_control}}","scid");
                         $aDataentrymsgs[] = CHtml::tag('font', array('class' => 'successtitle'), $clang->gT("Your survey responses have been saved successfully.  You will be sent a confirmation e-mail. Please make sure to save your password, since we will not be able to retrieve it for you."));
                         //$aDataentryoutput .= "<font class='successtitle'></font><br />\n";
                         $tokens_table = "{{tokens_{$surveyid}}}";
                         $last_db_id = Yii::app()->db->getLastInsertID();
                         if (tableExists($tokens_table)) {
                             $tkquery = "SELECT * FROM {$tokens_table}";
                             $tkresult = dbExecuteAssoc($tkquery);
                             /*$tokendata = array (
                               "firstname"=> $saver['identifier'],
                               "lastname"=> $saver['identifier'],
                               "email"=>$saver['email'],
                               "token"=>randomChars(15),
                               "language"=>$saver['language'],
                               "sent"=>dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", $timeadjust),
                               "completed"=>"N");*/
                             $columns = array("firstname", "lastname", "email", "token", "language", "sent", "completed");
                             $values = array("'" . $saver['identifier'] . "'", "'" . $saver['identifier'] . "'", "'" . $saver['email'] . "'", "'" . $password . "'", "'" . randomChars(15) . "'", "'" . $saver['language'] . "'", "'" . "N" . "'");
                             $SQL = "INSERT INTO {$token_table}\n                                (" . implode(',', $columns) . ")\n                                VALUES\n                                (" . implode(',', $values) . ")";
                             //$this->tokens_dynamic_model->insertToken($surveyid,$tokendata);
                             dbExecuteAssoc($SQL);
                             //Yii::app()->db->AutoExecute(db_table_name("tokens_".$surveyid), $tokendata,'INSERT');
                             $aDataentrymsgs[] = CHtml::tag('font', array('class' => 'successtitle'), $clang->gT("A token entry for the saved survey has been created too."));
                             //$aDataentryoutput .= "<font class='successtitle'></font><br />\n";
                             $last_db_id = Yii::app()->db->getLastInsertID();
                         }
                         if ($saver['email']) {
                             //Send email
                             if (validateEmailAddress($saver['email']) && !returnGlobal('redo')) {
                                 $subject = $clang->gT("Saved Survey Details");
                                 $message = $clang->gT("Thank you for saving your survey in progress.  The following details can be used to return to this survey and continue where you left off.  Please keep this e-mail for your reference - we cannot retrieve the password for you.");
                                 $message .= "\n\n" . $thissurvey['name'] . "\n\n";
                                 $message .= $clang->gT("Name") . ": " . $saver['identifier'] . "\n";
                                 $message .= $clang->gT("Password") . ": " . $saver['password'] . "\n\n";
                                 $message .= $clang->gT("Reload your survey by clicking on the following link (or pasting it into your browser):") . ":\n";
                                 $message .= Yii::app()->getConfig('publicurl') . "/index.php?sid={$surveyid}&loadall=reload&scid=" . $scid . "&lang=" . urlencode($saver['language']) . "&loadname=" . urlencode($saver['identifier']) . "&loadpass="******"&token=" . $tokendata['token'];
                                 }
                                 $from = $thissurvey['adminemail'];
                                 if (SendEmailMessage($message, $subject, $saver['email'], $from, $sitename, false, getBounceEmail($surveyid))) {
                                     $emailsent = "Y";
                                     $aDataentrymsgs[] = CHtml::tag('font', array('class' => 'successtitle'), $clang->gT("An email has been sent with details about your saved survey"));
                                 }
                             }
                         }
                     } else {
                         safeDie("Unable to insert record into saved_control table.<br /><br />");
                     }
                 }
                 $aData['thisid'] = $last_db_id;
             }
             $aData['errormsg'] = $errormsg;
             $aData['dataentrymsgs'] = $aDataentrymsgs;
             $this->_renderWrappedTemplate('dataentry', 'insert', $aData);
         }
     }
 }
Exemplo n.º 25
0
/**
* This function return actual completion state
*
* @return string (complete|incomplete|all) or false
*/
function incompleteAnsFilterState()
{
    $letsfilter = '';
    $letsfilter = returnGlobal('completionstate');
    //read get/post completionstate
    // first let's initialize the incompleteanswers session variable
    if ($letsfilter != '') {
        // use the read value if not empty
        Yii::app()->session['incompleteanswers'] = $letsfilter;
    } elseif (empty(Yii::app()->session['incompleteanswers'])) {
        // sets default variable value from config file
        Yii::app()->session['incompleteanswers'] = Yii::app()->getConfig('filterout_incomplete_answers');
    }
    if (Yii::app()->session['incompleteanswers'] == 'complete' || Yii::app()->session['incompleteanswers'] == 'all' || Yii::app()->session['incompleteanswers'] == 'incomplete') {
        return Yii::app()->session['incompleteanswers'];
    } else {
        // last resort is to prevent filtering
        return false;
    }
}
Exemplo n.º 26
0
 /**
  * Generates statistics
  *
  * @param int $surveyid The survey id
  * @param mixed $allfields
  * @param mixed $q2show
  * @param mixed $usegraph
  * @param string $outputType Optional - Can be xls, html or pdf - Defaults to pdf
  * @param string $pdfOutput Sets the target for the PDF output: DD=File download , F=Save file to local disk
  * @param string $statlangcode Lamguage for statistics
  * @param mixed $browse  Show browse buttons
  * @return buffer
  */
 public function generate_statistics($surveyid, $allfields, $q2show = 'all', $usegraph = 0, $outputType = 'pdf', $pdfOutput = 'I', $sLanguageCode = null, $browse = true)
 {
     $aStatisticsData = array();
     //astatdata generates data for the output page's javascript so it can rebuild graphs on the fly
     //load surveytranslator helper
     Yii::import('application.helpers.surveytranslator_helper', true);
     Yii::import('application.third_party.ar-php.Arabic', true);
     $sOutputHTML = "";
     //This string carries all the actual HTML code to print.
     $sTempDir = Yii::app()->getConfig("tempdir");
     $this->pdf = array();
     //Make sure $this->pdf exists - it will be replaced with an object if a $this->pdf is actually being created
     //pick the best font file if font setting is 'auto'
     if (is_null($sLanguageCode)) {
         $sLanguageCode = getBaseLanguageFromSurveyID($surveyid);
     }
     Yii::app()->setLanguage($sLanguageCode);
     /*
      * this variable is used in the function shortencode() which cuts off a question/answer title
      * after $maxchars and shows the rest as tooltip (in html mode)
      */
     $maxchars = 13;
     //we collect all the html-output within this variable
     $sOutputHTML = '';
     /**
      * $outputType: html || pdf ||
      */
     /**
      * get/set Survey Details
      */
     //no survey ID? -> come and get one
     if (!isset($surveyid)) {
         $surveyid = returnGlobal('sid');
     }
     //Get an array of codes of all available languages in this survey
     $surveylanguagecodes = Survey::model()->findByPk($surveyid)->additionalLanguages;
     $surveylanguagecodes[] = Survey::model()->findByPk($surveyid)->language;
     $fieldmap = createFieldMap($surveyid, "full", false, false, $sLanguageCode);
     // Set language for questions and answers to base language of this survey
     $language = $sLanguageCode;
     if ($q2show == 'all') {
         $summarySql = " SELECT gid, parent_qid, qid, type " . " FROM {{questions}} WHERE parent_qid=0" . " AND sid={$surveyid} ";
         $summaryRs = Yii::app()->db->createCommand($summarySql)->query()->readAll();
         foreach ($summaryRs as $field) {
             $myField = $surveyid . "X" . $field['gid'] . "X" . $field['qid'];
             // Multiple choice get special treatment
             if ($field['type'] == "M") {
                 $myField = "M{$myField}";
             }
             if ($field['type'] == "P") {
                 $myField = "P{$myField}";
             }
             //numerical input will get special treatment (arihtmetic mean, standard derivation, ...)
             if ($field['type'] == "N") {
                 $myField = "N{$myField}";
             }
             if ($field['type'] == "|") {
                 $myField = "|{$myField}";
             }
             if ($field['type'] == "Q") {
                 $myField = "Q{$myField}";
             }
             // textfields get special treatment
             if ($field['type'] == "S" || $field['type'] == "T" || $field['type'] == "U") {
                 $myField = "T{$myField}";
             }
             //statistics for Date questions are not implemented yet.
             if ($field['type'] == "D") {
                 $myField = "D{$myField}";
             }
             if ($field['type'] == "F" || $field['type'] == "H") {
                 //Get answers. We always use the answer code because the label might be too long elsewise
                 $query = "SELECT code, answer FROM {{answers}} WHERE qid='" . $field['qid'] . "' AND scale_id=0 AND language='{$language}' ORDER BY sortorder, answer";
                 $result = Yii::app()->db->createCommand($query)->query();
                 $counter2 = 0;
                 //check all the answers
                 foreach ($result->readAll() as $row) {
                     $row = array_values($row);
                     $myField = "{$myField}{$row[0]}";
                 }
                 //$myField = "{$surveyid}X{$flt[1]}X{$flt[0]}{$row[0]}[]";
             }
             if ($q2show == 'all') {
                 $summary[] = $myField;
             }
             //$allfields[]=$myField;
         }
     } else {
         // This gets all the 'to be shown questions' from the POST and puts these into an array
         if (!is_array($q2show)) {
             $summary = returnGlobal('summary');
         } else {
             $summary = $q2show;
         }
         //print_r($_POST);
         //if $summary isn't an array we create one
         if (isset($summary) && !is_array($summary)) {
             $summary = explode("+", $summary);
         }
     }
     /**
      * pdf Config
      */
     if ($outputType == 'pdf') {
         //require_once('classes/tcpdf/mypdf.php');
         Yii::import('application.libraries.admin.pdf', true);
         Yii::import('application.helpers.pdfHelper');
         $aPdfLanguageSettings = pdfHelper::getPdfLanguageSettings($language);
         // create new PDF document
         $this->pdf = new pdf();
         $surveyInfo = getSurveyInfo($surveyid, $language);
         // set document information
         $this->pdf->SetCreator(PDF_CREATOR);
         $this->pdf->SetAuthor('LimeSurvey');
         $this->pdf->SetTitle(sprintf(gT("Statistics survey %s"), $surveyid));
         $this->pdf->SetSubject($surveyInfo['surveyls_title']);
         $this->pdf->SetKeywords('LimeSurvey,' . gT("Statistics") . ', ' . sprintf(gT("Survey %s"), $surveyid));
         $this->pdf->SetDisplayMode('fullpage', 'two');
         $this->pdf->setLanguageArray($aPdfLanguageSettings['lg']);
         // set header and footer fonts
         $this->pdf->setHeaderFont(array($aPdfLanguageSettings['pdffont'], '', PDF_FONT_SIZE_MAIN));
         $this->pdf->setFooterFont(array($aPdfLanguageSettings['pdffont'], '', PDF_FONT_SIZE_DATA));
         // set default header data
         // Since png crashes some servers (and we can not try/catch that) we use .gif (or .jpg) instead
         $headerlogo = 'statistics.gif';
         $this->pdf->SetHeaderData($headerlogo, 10, gT("Quick statistics", 'unescaped'), gT("Survey") . " " . $surveyid . " '" . flattenText($surveyInfo['surveyls_title'], false, true, 'UTF-8') . "'");
         $this->pdf->SetFont($aPdfLanguageSettings['pdffont'], '', $aPdfLanguageSettings['pdffontsize']);
         // set default monospaced font
         $this->pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
     }
     if ($outputType == 'xls') {
         /**
          * Initiate the Spreadsheet_Excel_Writer
          */
         require_once APPPATH . '/third_party/pear/Spreadsheet/Excel/Xlswriter.php';
         if ($pdfOutput == 'F') {
             $sFileName = $sTempDir . '/statistic-survey' . $surveyid . '.xls';
             $this->workbook = new Xlswriter($sFileName);
         } else {
             $this->workbook = new Xlswriter();
         }
         $this->workbook->setVersion(8);
         // Inform the module that our data will arrive as UTF-8.
         // Set the temporary directory to avoid PHP error messages due to open_basedir restrictions and calls to tempnam("", ...)
         $this->workbook->setTempDir($sTempDir);
         // Inform the module that our data will arrive as UTF-8.
         // Set the temporary directory to avoid PHP error messages due to open_basedir restrictions and calls to tempnam("", ...)
         if (!empty($sTempDir)) {
             $this->workbook->setTempDir($sTempDir);
         }
         if ($pdfOutput != 'F') {
             $this->workbook->send('statistic-survey' . $surveyid . '.xls');
         }
         // Creating the first worksheet
         $this->sheet = $this->workbook->addWorksheet(utf8_decode('results-survey' . $surveyid));
         $this->xlsPercents =& $this->workbook->addFormat();
         $this->xlsPercents->setNumFormat('0.00%');
         $this->formatBold =& $this->workbook->addFormat(array('Bold' => 1));
         $this->sheet->setInputEncoding('utf-8');
         $this->sheet->setColumn(0, 20, 20);
         $separator = "~|";
         /**XXX*/
     }
     /**
      * Start generating
      */
     $selects = buildSelects($allfields, $surveyid, $language);
     //count number of answers
     $query = "SELECT count(*) FROM {{survey_{$surveyid}}}";
     //if incompleted answers should be filtert submitdate has to be not null
     if (incompleteAnsFilterState() == "incomplete") {
         $query .= " WHERE submitdate is null";
     } elseif (incompleteAnsFilterState() == "complete") {
         $query .= " WHERE submitdate is not null";
     }
     $total = Yii::app()->db->createCommand($query)->queryScalar();
     //are there any filters that have to be taken care of?
     if (isset($selects) && $selects) {
         //Save the filters to session for use in browsing text & other features (statistics.php function listcolumn())
         Yii::app()->session['statistics_selects_' . $surveyid] = $selects;
         //filter incomplete answers?
         if (incompleteAnsFilterState() == "complete" || incompleteAnsFilterState() == "incomplete") {
             $query .= " AND ";
         } else {
             $query .= " WHERE ";
         }
         //add filter criteria to SQL
         $query .= implode(" AND ", $selects);
     }
     //get me some data Scotty
     $results = Yii::app()->db->createCommand($query)->queryScalar();
     if ($total) {
         $percent = sprintf("%01.2f", $results / $total * 100);
     }
     switch ($outputType) {
         case "xls":
             $this->xlsRow = 0;
             $this->sheet->write($this->xlsRow, 0, gT("Number of records in this query:", 'unescaped'));
             $this->sheet->writeNumber($this->xlsRow, 1, $results);
             $this->xlsRow++;
             $this->sheet->write($this->xlsRow, 0, gT("Total records in survey:", 'unescaped'));
             $this->sheet->writeNumber($this->xlsRow, 1, $total);
             if ($total) {
                 $this->xlsRow++;
                 $this->sheet->write($this->xlsRow, 0, gT("Percentage of total:", 'unescaped'));
                 $this->sheet->writeNumber($this->xlsRow, 1, $results / $total, $this->xlsPercents);
             }
             break;
         case 'pdf':
             // add summary to pdf
             $array = array(array(gT("Number of records in this query:", 'unescaped'), $results), array(gT("Total records in survey:", 'unescaped'), $total));
             if ($total) {
                 $array[] = array(gT("Percentage of total:", 'unescaped'), $percent . "%");
             }
             $this->pdf->AddPage('P', ' A4');
             $this->pdf->Bookmark(gT("Results", 'unescaped'), 0, 0);
             $this->pdf->titleintopdf(gT("Results", 'unescaped'), gT("Survey", 'unescaped') . " " . $surveyid);
             $this->pdf->tableintopdf($array);
             break;
         case 'html':
             $sOutputHTML .= "<br />\n<table class='statisticssummary' >\n" . "\t<thead><tr><th colspan='2'>" . gT("Results") . "</th></tr></thead>\n" . "\t<tr><th >" . gT("Number of records in this query:") . '</th>' . "<td>{$results}</td></tr>\n" . "\t<tr><th>" . gT("Total records in survey:") . '</th>' . "<td>{$total}</td></tr>\n";
             //only calculate percentage if $total is set
             if ($total) {
                 $percent = sprintf("%01.2f", $results / $total * 100);
                 $sOutputHTML .= "\t<tr><th align='right'>" . gT("Percentage of total:") . '</th>' . "<td>{$percent}%</td></tr>\n";
             }
             $sOutputHTML .= "</table>\n";
             break;
         default:
             break;
     }
     //put everything from $selects array into a string connected by AND
     //This string ($sql) can then be passed on to other functions so you can
     //browse these results
     if (isset($selects) && $selects) {
         $sql = implode(" AND ", $selects);
     } elseif (!empty($newsql)) {
         $sql = $newsql;
     }
     if (!isset($sql) || !$sql) {
         $sql = null;
     }
     //only continue if we have something to output
     if ($results > 0) {
         if ($outputType == 'html' && $browse === true && Permission::model()->hasSurveyPermission($surveyid, 'responses', 'read')) {
             //add a buttons to browse results
             $sOutputHTML .= CHtml::form(array("admin/responses/sa/browse/surveyid/{$surveyid}"), 'post', array('target' => '_blank')) . "\n" . "\t\t<p>" . "\t\t\t<input type='submit' value='" . gT("Browse") . "'  />\n" . "\t\t\t<input type='hidden' name='sid' value='{$surveyid}' />\n" . "\t\t\t<input type='hidden' name='sql' value=\"{$sql}\" />\n" . "\t\t\t<input type='hidden' name='subaction' value='all' />\n" . "\t\t</p>" . "\t\t</form>\n";
         }
     }
     //end if (results > 0)
     /* Show Summary results
      * The $summary array contains each fieldname that we want to display statistics for
      *
      * */
     if (isset($summary) && $summary) {
         //let's run through the survey
         $runthrough = $summary;
         //START Chop up fieldname and find matching questions
         //loop through all selected questions
         foreach ($runthrough as $rt) {
             //Step 1: Get information about this response field (SGQA) for the summary
             $outputs = $this->buildOutputList($rt, $language, $surveyid, $outputType, $sql, $sLanguageCode);
             $sOutputHTML .= $outputs['statisticsoutput'];
             //2. Collect and Display results #######################################################################
             if (isset($outputs['alist']) && $outputs['alist']) {
                 $display = $this->displayResults($outputs, $results, $rt, $outputType, $surveyid, $sql, $usegraph, $browse, $sLanguageCode);
                 $sOutputHTML .= $display['statisticsoutput'];
                 $aStatisticsData = array_merge($aStatisticsData, $display['astatdata']);
             }
             //end if -> collect and display results
             //Delete Build Outputs data
             unset($outputs);
             unset($display);
         }
         // end foreach -> loop through all questions
         //output
         if ($outputType == 'html') {
             $sOutputHTML .= "<br />&nbsp;\n";
         }
     }
     //end if -> show summary results
     switch ($outputType) {
         case 'xls':
             $this->workbook->close();
             if ($pdfOutput == 'F') {
                 return $sFileName;
             } else {
                 return;
             }
             break;
         case 'pdf':
             $this->pdf->lastPage();
             if ($pdfOutput == 'F') {
                 // This is only used by lsrc to send an E-Mail attachment, so it gives back the filename to send and delete afterwards
                 $tempfilename = $sTempDir . "/Survey_" . $surveyid . ".pdf";
                 $this->pdf->Output($tempfilename, $pdfOutput);
                 return $tempfilename;
             } else {
                 return $this->pdf->Output(gT('Survey') . '_' . $surveyid . "_" . $surveyInfo['surveyls_title'] . '.pdf', $pdfOutput);
             }
             break;
         case 'html':
             $sGoogleMapsAPIKey = trim(Yii::app()->getConfig("googleMapsAPIKey"));
             if ($sGoogleMapsAPIKey != '') {
                 $sGoogleMapsAPIKey = '&key=' . $sGoogleMapsAPIKey;
             }
             $sSSL = '';
             if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != "off") {
                 $sSSL = 's';
             }
             $sOutputHTML .= "<script type=\"text/javascript\" src=\"http{$sSSL}://maps.googleapis.com/maps/api/js?sensor=false{$sGoogleMapsAPIKey}\"></script>\n" . "<script type=\"text/javascript\">var site_url='" . Yii::app()->baseUrl . "';var temppath='" . Yii::app()->getConfig("tempurl") . "';var imgpath='" . Yii::app()->getConfig('adminimageurl') . "';var aStatData=" . ls_json_encode($aStatisticsData) . "</script>";
             return $sOutputHTML;
             break;
         default:
             return $sOutputHTML;
             break;
     }
 }
Exemplo n.º 27
0
/**
* This function replaces keywords in a text and is mainly intended for templates
* If you use this functions put your replacement strings into the $replacements variable
* instead of using global variables
* NOTE - Don't do any embedded replacements in this function.  Create the array of replacement values and
* they will be done in batch at the end
*
* @param mixed $line Text to search in
* @param mixed $replacements Array of replacements:  Array( <stringtosearch>=><stringtoreplacewith>
* @param boolean $anonymized Determines if token data is being used or just replaced with blanks
* @param questionNum - needed to support dynamic JavaScript-based tailoring within questions
* @return string  Text with replaced strings
*/
function templatereplace($line, $replacements = array(), &$redata = array(), $debugSrc = 'Unspecified', $anonymized = false, $questionNum = NULL, $registerdata = array())
{
    /*
    global $clienttoken,$token,$sitename,$move,$showxquestions,$showqnumcode,$questioncode,$register_errormsg;
    global $s_lang,$errormsg,$saved_id, $relativeurl, $languagechanger,$captchapath,$loadname;
    */
    /*
    $allowedvars = array('surveylist', 'sitename', 'clienttoken', 'rooturl', 'thissurvey', 'imageurl', 'defaulttemplate',
    'percentcomplete', 'move', 'groupname', 'groupdescription', 'question', 'showxquestions',
    'showgroupinfo', 'showqnumcode', 'questioncode', 'answer', 'navigator', 'help', 'totalquestions',
    'surveyformat', 'completed', 'register_errormsg', 'notanswered', 'privacy', 'surveyid', 'publicurl',
    'templatedir', 'token', 'assessments', 's_lang', 'errormsg', 'clang', 'saved_id', 'usertemplaterootdir',
    'relativeurl', 'languagechanger', 'printoutput', 'captchapath', 'loadname');
    */
    $allowedvars = array('answer', 'assessments', 'captchapath', 'clienttoken', 'completed', 'errormsg', 'groupdescription', 'groupname', 'help', 'imageurl', 'languagechanger', 'loadname', 'move', 'navigator', 'percentcomplete', 'privacy', 'question', 'register_errormsg', 'relativeurl', 's_lang', 'saved_id', 'showgroupinfo', 'showqnumcode', 'showxquestions', 'sitename', 'surveylist', 'templatedir', 'thissurvey', 'token', 'totalBoilerplatequestions', 'totalquestions');
    $varsPassed = array();
    foreach ($allowedvars as $var) {
        if (isset($redata[$var])) {
            ${$var} = $redata[$var];
            $varsPassed[] = $var;
        }
    }
    //    if (count($varsPassed) > 0) {
    //        log_message('debug', 'templatereplace() called from ' . $debugSrc . ' contains: ' . implode(', ', $varsPassed));
    //    }
    //    if (isset($redata['question'])) {
    //        LimeExpressionManager::ShowStackTrace('has QID and/or SGA',$allowedvars);
    //    }
    //    extract($redata);   // creates variables for each of the keys in the array
    // Local over-rides in case not set above
    if (!isset($showgroupinfo)) {
        $showgroupinfo = Yii::app()->getConfig('showgroupinfo');
    }
    if (!isset($showqnumcode)) {
        $showqnumcode = Yii::app()->getConfig('showqnumcode');
    }
    $_surveyid = Yii::app()->getConfig('surveyID');
    if (!isset($showxquestions)) {
        $showxquestions = Yii::app()->getConfig('showxquestions');
    }
    if (!isset($s_lang)) {
        $s_lang = isset(Yii::app()->session['survey_' . $_surveyid]['s_lang']) ? Yii::app()->session['survey_' . $_surveyid]['s_lang'] : 'en';
    }
    if (!isset($captchapath)) {
        $captchapath = '';
    }
    $clang = Yii::app()->lang;
    Yii::app()->loadHelper('surveytranslator');
    $questiondetails = array('sid' => 0, 'gid' => 0, 'qid' => 0, 'aid' => 0);
    if (isset($question) && isset($question['sgq'])) {
        $questiondetails = getSIDGIDQIDAIDType($question['sgq']);
    }
    //Gets an array containing SID, GID, QID, AID and Question Type)
    if (isset($thissurvey['sid'])) {
        $surveyid = $thissurvey['sid'];
    }
    // lets sanitize the survey template
    if (isset($thissurvey['templatedir'])) {
        $templatename = $thissurvey['templatedir'];
    } else {
        $templatename = Yii::app()->getConfig('defaulttemplate');
    }
    if (!isset($templatedir)) {
        $templatedir = getTemplatePath($templatename);
    }
    if (!isset($templateurl)) {
        $templateurl = getTemplateURL($templatename) . "/";
    }
    // TEMPLATECSS and TEMPLATEJS
    $_templatecss = "";
    $_templatejs = "";
    if (stripos($line, "{TEMPLATECSS}")) {
        $css_header_includes = Yii::app()->getConfig("css_header_includes");
        if (file_exists($templatedir . DIRECTORY_SEPARATOR . 'jquery-ui-custom.css')) {
            $template_jqueryui_css = "<link rel='stylesheet' type='text/css' media='all' href='{$templateurl}jquery-ui-custom.css' />\n";
        } elseif (file_exists($templatedir . DIRECTORY_SEPARATOR . 'jquery-ui.css')) {
            $template_jqueryui_css = "<link rel='stylesheet' type='text/css' media='all' href='{$templateurl}jquery-ui.css' />\n";
        } else {
            $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='" . Yii::app()->getConfig('publicstyleurl') . "jquery-ui.css' />\n";
            // Remove it after corrected slider
            $template_jqueryui_css = "";
        }
        if ($css_header_includes) {
            foreach ($css_header_includes as $cssinclude) {
                if (substr($cssinclude, 0, 4) == 'http' || substr($cssinclude, 0, strlen(Yii::app()->getConfig('publicurl'))) == Yii::app()->getConfig('publicurl')) {
                    $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='" . $cssinclude . "' />\n";
                } else {
                    if (file_exists($templatedir . DIRECTORY_SEPARATOR . $cssinclude)) {
                        $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='{$templateurl}{$cssinclude}' />\n";
                    } else {
                        $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='" . Yii::app()->getConfig('publicstyleurl') . $cssinclude . "' />\n";
                    }
                }
            }
        }
        $_templatecss .= $template_jqueryui_css;
        // Template jquery ui after default css
        $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='{$templateurl}template.css' />\n";
        if (getLanguageRTL($clang->langcode)) {
            $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='{$templateurl}template-rtl.css' />\n";
        }
    }
    if (stripos($line, "{TEMPLATEJS}")) {
        $js_header_includes = header_includes(false, 'js');
        $_jqueryuijsurl = Yii::app()->getConfig('generalscripts') . "jquery/jquery-ui.js";
        $_templatejs .= "<script type='text/javascript' src='" . Yii::app()->getConfig('generalscripts') . "jquery/jquery.js'></script>\n";
        $_templatejs .= "<script type='text/javascript' src='{$_jqueryuijsurl}'></script>\n";
        $_templatejs .= "<script type='text/javascript' src='" . Yii::app()->getConfig('generalscripts') . "jquery/jquery.ui.touch-punch.min.js'></script>\n";
        if ($js_header_includes) {
            foreach ($js_header_includes as $jsinclude) {
                if (substr($jsinclude, 0, 4) == 'http' || substr($jsinclude, 0, strlen(Yii::app()->getConfig('publicurl'))) == Yii::app()->getConfig('publicurl')) {
                    $_templatejs .= "<script type='text/javascript' src='{$jsinclude}'></script>\n";
                } else {
                    $_templatejs .= "<script type='text/javascript' src='" . Yii::app()->getConfig('generalscripts') . $jsinclude . "'></script>\n";
                }
            }
        }
        $_templatejs .= "<script type='text/javascript' src='" . Yii::app()->getConfig('generalscripts') . "survey_runtime.js'></script>\n";
        $_templatejs .= "<script type='text/javascript' src='{$templateurl}template.js'></script>\n";
        $_templatejs .= useFirebug();
    }
    // surveyformat
    if (isset($thissurvey['format'])) {
        $surveyformat = str_replace(array("A", "S", "G"), array("allinone", "questionbyquestion", "groupbygroup"), $thissurvey['format']);
    } else {
        $surveyformat = "";
    }
    if (isset(Yii::app()->session['step']) && Yii::app()->session['step'] % 2 && $surveyformat != "allinone") {
        $surveyformat .= " page-odd";
    }
    if (isset($thissurvey['allowjumps']) && $thissurvey['allowjumps'] == "Y" && $surveyformat != "allinone" && (isset(Yii::app()->session['step']) && Yii::app()->session['step'] > 0)) {
        $surveyformat .= " withindex";
    }
    if (isset($thissurvey['showprogress']) && $thissurvey['showprogress'] == "Y") {
        $surveyformat .= " showprogress";
    }
    if (isset($thissurvey['showqnumcode'])) {
        $surveyformat .= " showqnumcode-" . $thissurvey['showqnumcode'];
    }
    // real survey contact
    if (isset($surveylist) && isset($surveylist['contact'])) {
        $surveycontact = $surveylist['contact'];
    } elseif (isset($surveylist) && isset($thissurvey['admin']) && $thissurvey['admin'] != "") {
        $surveycontact = sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['admin'], $thissurvey['adminemail']);
    } else {
        $surveycontact = "";
    }
    // If there are non-bracketed replacements to be made do so above this line.
    // Only continue in this routine if there are bracketed items to replace {}
    if (strpos($line, "{") === false) {
        // process string anyway so that it can be pretty-printed
        return LimeExpressionManager::ProcessString($line, $questionNum, NULL, false, 1, 1, true);
    }
    if ($showgroupinfo == 'both' || $showgroupinfo == 'name' || $showgroupinfo == 'choose' && !isset($thissurvey['showgroupinfo']) || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'B' || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'N') {
        $_groupname = isset($groupname) ? $groupname : '';
    } else {
        $_groupname = '';
    }
    if ($showgroupinfo == 'both' || $showgroupinfo == 'description' || $showgroupinfo == 'choose' && !isset($thissurvey['showgroupinfo']) || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'B' || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'D') {
        $_groupdescription = isset($groupdescription) ? $groupdescription : '';
    } else {
        $_groupdescription = '';
    }
    if (isset($question) && is_array($question)) {
        $_question = $question['all'];
        $_question_text = $question['text'];
        $_question_help = $question['help'];
        $_question_mandatory = $question['mandatory'];
        $_question_man_message = $question['man_message'];
        $_question_valid_message = $question['valid_message'];
        $_question_file_valid_message = $question['file_valid_message'];
        $_question_sgq = isset($question['sgq']) ? $question['sgq'] : '';
        $_question_essentials = $question['essentials'];
        $_getQuestionClass = $question['class'];
        $_question_man_class = $question['man_class'];
        $_question_input_error_class = $question['input_error_class'];
        $_question_number = $question['number'];
        $_question_code = $question['code'];
        $_question_type = $question['type'];
    } else {
        $_question = isset($question) ? $question : '';
        $_question_text = '';
        $_question_help = '';
        $_question_mandatory = '';
        $_question_man_message = '';
        $_question_valid_message = '';
        $_question_file_valid_message = '';
        $_question_sgq = '';
        $_question_essentials = '';
        $_getQuestionClass = '';
        $_question_man_class = '';
        $_question_input_error_class = '';
        $_question_number = '';
        $_question_code = '';
        $_question_type = '';
    }
    if ($_question_type == '*') {
        $_question_text = '<div class="em_equation">' . $_question_text . '</div>';
    }
    if (!($showqnumcode == 'both' || $showqnumcode == 'number' || $showqnumcode == 'choose' && !isset($thissurvey['showqnumcode']) || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'B' || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'N')) {
        $_question_number = '';
    }
    if (!($showqnumcode == 'both' || $showqnumcode == 'code' || $showqnumcode == 'choose' && !isset($thissurvey['showqnumcode']) || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'B' || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'C')) {
        $_question_code = '';
    }
    if (!isset($totalquestions)) {
        $totalquestions = 0;
    }
    $_totalquestionsAsked = $totalquestions;
    if ($showxquestions == 'show' || $showxquestions == 'choose' && !isset($thissurvey['showxquestions']) || $showxquestions == 'choose' && $thissurvey['showxquestions'] == 'Y') {
        if ($_totalquestionsAsked < 1) {
            $_therearexquestions = $clang->gT("There are no questions in this survey");
            // Singular
        } elseif ($_totalquestionsAsked == 1) {
            $_therearexquestions = $clang->gT("There is 1 question in this survey");
            //Singular
        } else {
            $_therearexquestions = $clang->gT("There are {NUMBEROFQUESTIONS} questions in this survey.");
            //Note this line MUST be before {NUMBEROFQUESTIONS}
        }
    } else {
        $_therearexquestions = '';
    }
    if (isset($token)) {
        $_token = $token;
    } elseif (isset($clienttoken)) {
        $_token = htmlentities($clienttoken, ENT_QUOTES, 'UTF-8');
        // or should it be URL-encoded?
    } else {
        $_token = '';
    }
    // Expiry
    if (isset($thissurvey['expiry'])) {
        $dateformatdetails = getDateFormatData($thissurvey['surveyls_dateformat']);
        Yii::import('application.libraries.Date_Time_Converter', true);
        $datetimeobj = new Date_Time_Converter($thissurvey['expiry'], "Y-m-d");
        $_dateoutput = $datetimeobj->convert($dateformatdetails['phpdate']);
    } else {
        $_dateoutput = '-';
    }
    $_submitbutton = "<input class='submit' type='submit' value=' " . $clang->gT("Submit") . " ' name='move2' onclick=\"javascript:document.limesurvey.move.value = 'movesubmit';\" />";
    if (isset($thissurvey['surveyls_url']) and $thissurvey['surveyls_url'] != "") {
        if (trim($thissurvey['surveyls_urldescription']) != '') {
            $_linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_urldescription']}</a>";
        } else {
            $_linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_url']}</a>";
        }
    } else {
        $_linkreplace = '';
    }
    if (isset($thissurvey['sid']) && isset($_SESSION['survey_' . $thissurvey['sid']]['srid']) && $thissurvey['active'] == 'Y') {
        $iscompleted = Survey_dynamic::model($surveyid)->isCompleted($_SESSION['survey_' . $thissurvey['sid']]['srid']);
    } else {
        $iscompleted = false;
    }
    if (isset($surveyid) && !$iscompleted) {
        $_clearall = "<input type='button' name='clearallbtn' value='" . $clang->gT("Exit and clear survey") . "' class='clearall' " . "onclick=\"if (confirm('" . $clang->gT("Are you sure you want to clear all your responses?", 'js') . "')) {\nwindow.open('" . Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}", array('move' => 'clearall', 'lang' => $s_lang), '&amp;');
        if (returnGlobal('token')) {
            $_clearall .= "&amp;token=" . urlencode(trim(sanitize_token(strip_tags(returnGlobal('token')))));
        }
        $_clearall .= "', '_self')}\" />";
    } else {
        $_clearall = "";
    }
    if (isset(Yii::app()->session['datestamp'])) {
        $_datestamp = Yii::app()->session['datestamp'];
    } else {
        $_datestamp = '-';
    }
    if (isset($thissurvey['allowsave']) and $thissurvey['allowsave'] == "Y") {
        // Find out if the user has any saved data
        if ($thissurvey['format'] == 'A') {
            if ($thissurvey['tokenanswerspersistence'] != 'Y' || !isset($surveyid) || !tableExists('tokens_' . $surveyid)) {
                $_saveall = "\t\t\t<input type='button' name='loadall' value='" . $clang->gT("Load unfinished survey") . "' class='saveall' onclick=\"javascript:addHiddenField(document.getElementById('limesurvey'),'loadall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>" . "\n\t\t\t<input type='button' name='saveallbtn' value='" . $clang->gT("Resume later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
                // Show Save So Far button
            } else {
                $_saveall = "\t\t\t<input type='button' name='saveallbtn' value='" . $clang->gT("Resume later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
                // Show Save So Far button
            }
        } elseif (isset($surveyid) && (!isset($_SESSION['survey_' . $surveyid]['step']) || !$_SESSION['survey_' . $surveyid]['step'])) {
            //First page, show LOAD
            if ($thissurvey['tokenanswerspersistence'] != 'Y' || !isset($surveyid) || !tableExists('tokens_' . $surveyid)) {
                $_saveall = "\t\t\t<input type='button' name='loadall' value='" . $clang->gT("Load unfinished survey") . "' class='saveall' onclick=\"javascript:addHiddenField(document.getElementById('limesurvey'),'loadall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
            } else {
                $_saveall = '';
            }
        } elseif (isset(Yii::app()->session['scid']) && (isset($move) && $move == "movelast")) {
            //Already saved and on Submit Page, dont show Save So Far button
            $_saveall = '';
        } else {
            $_saveall = "<input type='button' name='saveallbtn' value='" . $clang->gT("Resume later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
            // Show Save So Far button
        }
    } else {
        $_saveall = "";
    }
    if (!isset($help)) {
        $help = "";
    }
    if (flattenText($help, true, true) != '') {
        if (!isset($helpicon)) {
            if (file_exists($templatedir . '/help.gif')) {
                $helpicon = $templateurl . 'help.gif';
            } elseif (file_exists($templatedir . '/help.png')) {
                $helpicon = $templateurl . 'help.png';
            } else {
                $helpicon = Yii::app()->getConfig('imageurl') . "/help.gif";
            }
        }
        $_questionhelp = "<img src='{$helpicon}' alt='Help' align='left' />" . $help;
    } else {
        $_questionhelp = $help;
    }
    if (isset($thissurvey['allowprev']) && $thissurvey['allowprev'] == "N") {
        $_strreview = "";
    } else {
        $_strreview = $clang->gT("If you want to check any of the answers you have made, and/or change them, you can do that now by clicking on the [<< prev] button and browsing through your responses.");
    }
    if (isset($thissurvey['active']) and $thissurvey['active'] == "N") {
        $_restart = "<a href='" . Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}/newtest/Y");
        if (isset($s_lang) && $s_lang != '') {
            $_restart .= "/lang/" . $s_lang;
        }
        $_restart .= "'>" . $clang->gT("Restart this survey") . "</a>";
    } else {
        if (isset($surveyid)) {
            $restart_extra = "";
            $restart_token = returnGlobal('token');
            if (!empty($restart_token)) {
                $restart_extra .= "/token/" . urlencode($restart_token);
            } else {
                $restart_extra = "/newtest/Y";
            }
            if (!empty($_GET['lang'])) {
                $restart_extra .= "/lang/" . returnGlobal('lang');
            }
            $_restart = "<a href='" . Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}{$restart_extra}") . "'>" . $clang->gT("Restart this Survey") . "</a>";
        } else {
            $_restart = "";
        }
    }
    if (isset($thissurvey['anonymized']) && $thissurvey['anonymized'] == 'Y') {
        $_savealert = $clang->gT("To remain anonymous please use a pseudonym as your username, also an email address is not required.");
    } else {
        $_savealert = "";
    }
    if (isset($surveyid)) {
        $_return_to_survey = "<a href=" . Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}");
        if (returnGlobal('token')) {
            $_return_to_survey .= "?amp;token=" . urlencode(trim(sanitize_xss_string(strip_tags(returnGlobal('token')))));
        }
        $_return_to_survey .= "'>" . $clang->gT("Return to survey") . "</a>";
    } else {
        $_return_to_survey = "";
    }
    // Save Form
    $_saveform = "<table><tr><td align='right'>" . $clang->gT("Name") . ":</td><td><input type='text' name='savename' value='";
    if (isset($_POST['savename'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['savename']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Password") . ":</td><td><input type='password' name='savepass' value='";
    if (isset($_POST['savepass'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['savepass']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Repeat password") . ":</td><td><input type='password' name='savepass2' value='";
    if (isset($_POST['savepass2'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['savepass2']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Your email address") . ":</td><td><input type='text' name='saveemail' value='";
    if (isset($_POST['saveemail'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['saveemail']));
    }
    $_saveform .= "' /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
        $_saveform .= "<tr><td align='right'>" . $clang->gT("Security question") . ":</td><td><table><tr><td valign='middle'><img src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . (isset($surveyid) ? $surveyid : '')) . "' alt6='' /></td><td valign='middle' style='text-align:left'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table></td></tr>\n";
    }
    $_saveform .= "<tr><td align='right'></td><td></td></tr>\n" . "<tr><td></td><td><input type='submit'  id='savebutton' name='savesubmit' value='" . $clang->gT("Save Now") . "' /></td></tr>\n" . "</table>";
    // Load Form
    $_loadform = "<table><tr><td align='right'>" . $clang->gT("Saved name") . ":</td><td><input type='text' name='loadname' value='";
    if (isset($loadname)) {
        $_loadform .= HTMLEscape(autoUnescape($loadname));
    }
    $_loadform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Password") . ":</td><td><input type='password' name='loadpass' value='";
    if (isset($loadpass)) {
        $_loadform .= HTMLEscape(autoUnescape($loadpass));
    }
    $_loadform .= "' /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
        $_loadform .= "<tr><td align='right'>" . $clang->gT("Security question") . ":</td><td><table><tr><td valign='middle'><img src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='' /></td><td valign='middle'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' alt=''/></td></tr></table></td></tr>\n";
    }
    $_loadform .= "<tr><td align='right'></td><td></td></tr>\n" . "<tr><td></td><td><input type='submit' id='loadbutton' value='" . $clang->gT("Load now") . "' /></td></tr></table>\n";
    // Registration Form
    if (isset($surveyid) || isset($registerdata) && $debugSrc == 'register.php') {
        if (isset($surveyid)) {
            $tokensid = $surveyid;
        } else {
            $tokensid = $registerdata['sid'];
        }
        $_registerform = "<form method='post' action='" . Yii::app()->getController()->createUrl('/register/index/surveyid/' . $tokensid) . "'>\n";
        if (!isset($_REQUEST['lang'])) {
            $_reglang = Survey::model()->findByPk($tokensid)->language;
        } else {
            $_reglang = returnGlobal('lang');
        }
        $_registerform .= "<input type='hidden' name='lang' value='" . $_reglang . "' />\n";
        $_registerform .= "<input type='hidden' name='sid' value='{$tokensid}' id='sid' />\n";
        $_registerform .= "<table class='register' summary='Registrationform'>\n" . "<tr><td align='right'>" . $clang->gT("First name") . ":</td>" . "<td align='left'><input class='text' type='text' name='register_firstname'";
        if (isset($_POST['register_firstname'])) {
            $_registerform .= " value='" . htmlentities(returnGlobal('register_firstname'), ENT_QUOTES, 'UTF-8') . "'";
        }
        $_registerform .= " /></td></tr>" . "<tr><td align='right'>" . $clang->gT("Last name") . ":</td>\n" . "<td align='left'><input class='text' type='text' name='register_lastname'";
        if (isset($_POST['register_lastname'])) {
            $_registerform .= " value='" . htmlentities(returnGlobal('register_lastname'), ENT_QUOTES, 'UTF-8') . "'";
        }
        $_registerform .= " /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Email address") . ":</td>\n" . "<td align='left'><input class='text' type='text' name='register_email'";
        if (isset($_POST['register_email'])) {
            $_registerform .= " value='" . htmlentities(returnGlobal('register_email'), ENT_QUOTES, 'UTF-8') . "'";
        }
        $_registerform .= " /></td></tr>\n";
        foreach ($thissurvey['attributedescriptions'] as $field => $attribute) {
            if (empty($attribute['show_register']) || $attribute['show_register'] != 'Y') {
                continue;
            }
            $_registerform .= '
            <tr>
            <td align="right">' . $thissurvey['attributecaptions'][$field] . ($attribute['mandatory'] == 'Y' ? '*' : '') . ':</td>
            <td align="left"><input class="text" type="text" name="register_' . $field . '" /></td>
            </tr>';
        }
        if ((count($registerdata) > 1 || isset($thissurvey['usecaptcha'])) && function_exists("ImageCreate") && isCaptchaEnabled('registrationscreen', $thissurvey['usecaptcha'])) {
            $_registerform .= "<tr><td align='right'>" . $clang->gT("Security Question") . ":</td><td><table><tr><td valign='middle'><img src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='' /></td><td valign='middle'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table></td></tr>\n";
        }
        $_registerform .= "<tr><td></td><td><input id='registercontinue' class='submit' type='submit' value='" . $clang->gT("Continue") . "' />" . "</td></tr>\n" . "</table>\n";
        if (count($registerdata) > 1 && $registerdata['sid'] != NULL && $debugSrc == 'register.php') {
            $_registerform .= "<input name='startdate' type ='hidden' value='" . $registerdata['startdate'] . "' />";
            $_registerform .= "<input name='enddate' type ='hidden' value='" . $registerdata['enddate'] . "' />";
        }
        $_registerform .= "</form>\n";
    } else {
        $_registerform = "";
    }
    // Assessments
    $assessmenthtml = "";
    if (isset($surveyid) && !is_null($surveyid) && function_exists('doAssessment')) {
        $assessmentdata = doAssessment($surveyid, true);
        $_assessment_current_total = $assessmentdata['total'];
        if (stripos($line, "{ASSESSMENTS}")) {
            $assessmenthtml = doAssessment($surveyid, false);
        }
    } else {
        $_assessment_current_total = '';
    }
    if (isset($thissurvey['googleanalyticsapikey']) && trim($thissurvey['googleanalyticsapikey']) != '') {
        $_googleAnalyticsAPIKey = trim($thissurvey['googleanalyticsapikey']);
    } else {
        $_googleAnalyticsAPIKey = trim(getGlobalSetting('googleanalyticsapikey'));
    }
    $_googleAnalyticsStyle = isset($thissurvey['googleanalyticsstyle']) ? $thissurvey['googleanalyticsstyle'] : '0';
    $_googleAnalyticsJavaScript = '';
    if ($_googleAnalyticsStyle != '' && $_googleAnalyticsStyle != 0 && $_googleAnalyticsAPIKey != '') {
        switch ($_googleAnalyticsStyle) {
            case '1':
                // Default Google Tracking
                $_googleAnalyticsJavaScript = <<<EOD
<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', '{$_googleAnalyticsAPIKey}']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
</script>
EOD;
                break;
            case '2':
                // SurveyName-[SID]/[GSEQ]-GroupName - create custom GSEQ based upon page step
                $moveInfo = LimeExpressionManager::GetLastMoveResult();
                if (is_null($moveInfo)) {
                    $gseq = 'welcome';
                } else {
                    if ($moveInfo['finished']) {
                        $gseq = 'finished';
                    } else {
                        if (isset($moveInfo['at_start']) && $moveInfo['at_start']) {
                            $gseq = 'welcome';
                        } else {
                            if (is_null($_groupname)) {
                                $gseq = 'printanswers';
                            } else {
                                $gseq = $moveInfo['gseq'] + 1;
                            }
                        }
                    }
                }
                $_trackURL = htmlspecialchars($thissurvey['name'] . '-[' . $surveyid . ']/[' . $gseq . ']-' . $_groupname);
                $_googleAnalyticsJavaScript = <<<EOD
<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', '{$_googleAnalyticsAPIKey}']);
  _gaq.push(['_trackPageview','{$_trackURL}']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
</script>
EOD;
                break;
        }
    }
    $_endtext = '';
    if (isset($thissurvey['surveyls_endtext']) && trim($thissurvey['surveyls_endtext']) != '') {
        $_endtext = $thissurvey['surveyls_endtext'];
    }
    // Set the array of replacement variables here - don't include curly braces
    $coreReplacements = array();
    $coreReplacements['ACTIVE'] = isset($thissurvey['active']) && !($thissurvey['active'] != "Y");
    $coreReplacements['AID'] = isset($questiondetails['aid']) ? $questiondetails['aid'] : '';
    $coreReplacements['ANSWER'] = isset($answer) ? $answer : '';
    // global
    $coreReplacements['ANSWERSCLEARED'] = $clang->gT("Answers cleared");
    $coreReplacements['ASSESSMENTS'] = $assessmenthtml;
    $coreReplacements['ASSESSMENT_CURRENT_TOTAL'] = $_assessment_current_total;
    $coreReplacements['ASSESSMENT_HEADING'] = $clang->gT("Your assessment");
    $coreReplacements['CHECKJAVASCRIPT'] = "<noscript><span class='warningjs'>" . $clang->gT("Caution: JavaScript execution is disabled in your browser. You may not be able to answer all questions in this survey. Please, verify your browser parameters.") . "</span></noscript>";
    $coreReplacements['CLEARALL'] = $_clearall;
    $coreReplacements['CLOSEWINDOW'] = "<a href='javascript:%20self.close()'>" . $clang->gT("Close this window") . "</a>";
    $coreReplacements['COMPLETED'] = isset($redata['completed']) ? $redata['completed'] : '';
    // global
    $coreReplacements['DATESTAMP'] = $_datestamp;
    $coreReplacements['ENDTEXT'] = $_endtext;
    $coreReplacements['EXPIRY'] = $_dateoutput;
    $coreReplacements['GID'] = isset($questiondetails['gid']) ? $questiondetails['gid'] : '';
    $coreReplacements['GOOGLE_ANALYTICS_API_KEY'] = $_googleAnalyticsAPIKey;
    $coreReplacements['GOOGLE_ANALYTICS_JAVASCRIPT'] = $_googleAnalyticsJavaScript;
    $coreReplacements['GROUPDESCRIPTION'] = $_groupdescription;
    $coreReplacements['GROUPNAME'] = $_groupname;
    $coreReplacements['LANG'] = $clang->getlangcode();
    $coreReplacements['LANGUAGECHANGER'] = isset($languagechanger) ? $languagechanger : '';
    // global
    $coreReplacements['LOADERROR'] = isset($errormsg) ? $errormsg : '';
    // global
    $coreReplacements['LOADFORM'] = $_loadform;
    $coreReplacements['LOADHEADING'] = $clang->gT("Load a previously saved survey");
    $coreReplacements['LOADMESSAGE'] = $clang->gT("You can load a survey that you have previously saved from this screen.") . "<br />" . $clang->gT("Type in the 'name' you used to save the survey, and the password.") . "<br />";
    $coreReplacements['NAVIGATOR'] = isset($navigator) ? $navigator : '';
    // global
    $coreReplacements['NOSURVEYID'] = isset($surveylist) ? $surveylist['nosid'] : '';
    $coreReplacements['NUMBEROFQUESTIONS'] = $_totalquestionsAsked;
    $coreReplacements['PERCENTCOMPLETE'] = isset($percentcomplete) ? $percentcomplete : '';
    // global
    $coreReplacements['PRIVACY'] = isset($privacy) ? $privacy : '';
    // global
    $coreReplacements['PRIVACYMESSAGE'] = "<span style='font-weight:bold; font-style: italic;'>" . $clang->gT("A Note On Privacy") . "</span><br />" . $clang->gT("This survey is anonymous.") . "<br />" . $clang->gT("The record kept of your survey responses does not contain any identifying information about you unless a specific question in the survey has asked for this. If you have responded to a survey that used an identifying token to allow you to access the survey, you can rest assured that the identifying token is not kept with your responses. It is managed in a separate database, and will only be updated to indicate that you have (or haven't) completed this survey. There is no way of matching identification tokens with survey responses in this survey.");
    $coreReplacements['QID'] = isset($questiondetails['qid']) ? $questiondetails['qid'] : '';
    $coreReplacements['QUESTION'] = $_question;
    $coreReplacements['QUESTIONHELP'] = $_questionhelp;
    $coreReplacements['QUESTIONHELPPLAINTEXT'] = strip_tags(addslashes($help));
    // global
    $coreReplacements['QUESTION_CLASS'] = $_getQuestionClass;
    $coreReplacements['QUESTION_CODE'] = $_question_code;
    $coreReplacements['QUESTION_ESSENTIALS'] = $_question_essentials;
    $coreReplacements['QUESTION_FILE_VALID_MESSAGE'] = $_question_file_valid_message;
    $coreReplacements['QUESTION_HELP'] = $_question_help;
    $coreReplacements['QUESTION_INPUT_ERROR_CLASS'] = $_question_input_error_class;
    $coreReplacements['QUESTION_MANDATORY'] = $_question_mandatory;
    $coreReplacements['QUESTION_MAN_CLASS'] = $_question_man_class;
    $coreReplacements['QUESTION_MAN_MESSAGE'] = $_question_man_message;
    $coreReplacements['QUESTION_NUMBER'] = $_question_number;
    $coreReplacements['QUESTION_TEXT'] = $_question_text;
    $coreReplacements['QUESTION_VALID_MESSAGE'] = $_question_valid_message;
    $coreReplacements['REGISTERERROR'] = isset($register_errormsg) ? $register_errormsg : '';
    // global
    $coreReplacements['REGISTERFORM'] = $_registerform;
    $coreReplacements['REGISTERMESSAGE1'] = $clang->gT("You must be registered to complete this survey");
    $coreReplacements['REGISTERMESSAGE2'] = $clang->gT("You may register for this survey if you wish to take part.") . "<br />\n" . $clang->gT("Enter your details below, and an email containing the link to participate in this survey will be sent immediately.");
    $coreReplacements['RESTART'] = $_restart;
    $coreReplacements['RETURNTOSURVEY'] = $_return_to_survey;
    $coreReplacements['SAVE'] = $_saveall;
    $coreReplacements['SAVEALERT'] = $_savealert;
    $coreReplacements['SAVEDID'] = isset($saved_id) ? $saved_id : '';
    // global
    $coreReplacements['SAVEERROR'] = isset($errormsg) ? $errormsg : '';
    // global - same as LOADERROR
    $coreReplacements['SAVEFORM'] = $_saveform;
    $coreReplacements['SAVEHEADING'] = $clang->gT("Save your unfinished survey");
    $coreReplacements['SAVEMESSAGE'] = $clang->gT("Enter a name and password for this survey and click save below.") . "<br />\n" . $clang->gT("Your survey will be saved using that name and password, and can be completed later by logging in with the same name and password.") . "<br /><br />\n" . $clang->gT("If you give an email address, an email containing the details will be sent to you.") . "<br /><br />\n" . $clang->gT("After having clicked the save button you can either close this browser window or continue filling out the survey.");
    $coreReplacements['SGQ'] = $_question_sgq;
    $coreReplacements['SID'] = isset($surveyid) ? $surveyid : (isset($questiondetails['sid']) ? $questiondetails['sid'] : '');
    $coreReplacements['SITENAME'] = isset($sitename) ? $sitename : '';
    // global
    $coreReplacements['SUBMITBUTTON'] = $_submitbutton;
    $coreReplacements['SUBMITCOMPLETE'] = "<strong>" . $clang->gT("Thank you!") . "<br /><br />" . $clang->gT("You have completed answering the questions in this survey.") . "</strong><br /><br />" . $clang->gT("Click on 'Submit' now to complete the process and save your answers.");
    $coreReplacements['SUBMITREVIEW'] = $_strreview;
    $coreReplacements['SURVEYCONTACT'] = $surveycontact;
    $coreReplacements['SURVEYDESCRIPTION'] = isset($thissurvey['description']) ? $thissurvey['description'] : '';
    $coreReplacements['SURVEYFORMAT'] = isset($surveyformat) ? $surveyformat : '';
    // global
    $coreReplacements['SURVEYLANGAGE'] = $clang->langcode;
    $coreReplacements['SURVEYLANGUAGE'] = $clang->langcode;
    $coreReplacements['SURVEYLIST'] = isset($surveylist) ? $surveylist['list'] : '';
    $coreReplacements['SURVEYLISTHEADING'] = isset($surveylist) ? $surveylist['listheading'] : '';
    $coreReplacements['SURVEYNAME'] = isset($thissurvey['name']) ? $thissurvey['name'] : '';
    $coreReplacements['TEMPLATECSS'] = $_templatecss;
    $coreReplacements['TEMPLATEJS'] = $_templatejs;
    $coreReplacements['TEMPLATEURL'] = $templateurl;
    $coreReplacements['THEREAREXQUESTIONS'] = $_therearexquestions;
    if (!$anonymized) {
        $coreReplacements['TOKEN'] = $_token;
    }
    $coreReplacements['URL'] = $_linkreplace;
    $coreReplacements['WELCOME'] = isset($thissurvey['welcome']) ? $thissurvey['welcome'] : '';
    if (!is_null($replacements) && is_array($replacements)) {
        $doTheseReplacements = array_merge($coreReplacements, $replacements);
        // so $replacements overrides core values
    } else {
        $doTheseReplacements = $coreReplacements;
    }
    // Now do all of the replacements - In rare cases, need to do 3 deep recursion, that that is default
    $line = LimeExpressionManager::ProcessString($line, $questionNum, $doTheseReplacements, false, 3, 1);
    return $line;
}
Exemplo n.º 28
0
 function _getParameters($args = array(), $post = array())
 {
     $param = array();
     if (@$args[0] == __CLASS__) {
         array_shift($args);
     }
     if (count($args) % 2 == 0) {
         for ($i = 0; $i < count($args); $i += 2) {
             //Sanitize input from URL with returnGlobal
             $param[$args[$i]] = returnGlobal($args[$i], true);
         }
     }
     // Need some $param (else PHP notice)
     foreach (array('lang', 'action', 'newtest', 'qid', 'gid', 'sid', 'loadname', 'loadpass', 'scid', 'thisstep', 'move', 'token') as $sNeededParam) {
         $param[$sNeededParam] = returnGlobal($sNeededParam, true);
     }
     return $param;
 }
 private function _saveSettings()
 {
     if ($_POST['action'] !== "globalsettingssave") {
         return;
     }
     if (Yii::app()->session['USER_RIGHT_CONFIGURATOR'] != 1) {
         $this->getController()->redirect($this->getController()->createUrl('/admin'));
     }
     $clang = $this->getController()->lang;
     Yii::app()->loadHelper('surveytranslator');
     $maxemails = $_POST['maxemails'];
     if (sanitize_int($_POST['maxemails']) < 1) {
         $maxemails = 1;
     }
     $defaultlang = sanitize_languagecode($_POST['defaultlang']);
     $aRestrictToLanguages = explode(' ', sanitize_languagecodeS($_POST['restrictToLanguages']));
     if (!in_array($defaultlang, $aRestrictToLanguages)) {
         // Force default language in restrictToLanguages
         $aRestrictToLanguages[] = $defaultlang;
     }
     if (count(array_diff(array_keys(getLanguageData(false, Yii::app()->session['adminlang'])), $aRestrictToLanguages)) == 0) {
         $aRestrictToLanguages = '';
     } else {
         $aRestrictToLanguages = implode(' ', $aRestrictToLanguages);
     }
     setGlobalSetting('defaultlang', $defaultlang);
     setGlobalSetting('restrictToLanguages', trim($aRestrictToLanguages));
     setGlobalSetting('sitename', strip_tags($_POST['sitename']));
     setGlobalSetting('updatecheckperiod', (int) $_POST['updatecheckperiod']);
     setGlobalSetting('defaulthtmleditormode', sanitize_paranoid_string($_POST['defaulthtmleditormode']));
     setGlobalSetting('defaultquestionselectormode', sanitize_paranoid_string($_POST['defaultquestionselectormode']));
     setGlobalSetting('defaulttemplateeditormode', sanitize_paranoid_string($_POST['defaulttemplateeditormode']));
     setGlobalSetting('defaulttemplate', sanitize_paranoid_string($_POST['defaulttemplate']));
     setGlobalSetting('admintheme', sanitize_paranoid_string($_POST['admintheme']));
     setGlobalSetting('adminthemeiconsize', trim(file_get_contents(Yii::app()->getConfig("styledir") . DIRECTORY_SEPARATOR . sanitize_paranoid_string($_POST['admintheme']) . DIRECTORY_SEPARATOR . 'iconsize')));
     setGlobalSetting('emailmethod', strip_tags($_POST['emailmethod']));
     setGlobalSetting('emailsmtphost', strip_tags(returnGlobal('emailsmtphost')));
     if (returnGlobal('emailsmtppassword') != 'somepassword') {
         setGlobalSetting('emailsmtppassword', strip_tags(returnGlobal('emailsmtppassword')));
     }
     setGlobalSetting('bounceaccounthost', strip_tags(returnGlobal('bounceaccounthost')));
     setGlobalSetting('bounceaccounttype', strip_tags(returnGlobal('bounceaccounttype')));
     setGlobalSetting('bounceencryption', strip_tags(returnGlobal('bounceencryption')));
     setGlobalSetting('bounceaccountuser', strip_tags(returnGlobal('bounceaccountuser')));
     if (returnGlobal('bounceaccountpass') != 'enteredpassword') {
         setGlobalSetting('bounceaccountpass', strip_tags(returnGlobal('bounceaccountpass')));
     }
     setGlobalSetting('emailsmtpssl', sanitize_paranoid_string(Yii::app()->request->getPost('emailsmtpssl', '')));
     setGlobalSetting('emailsmtpdebug', sanitize_int(Yii::app()->request->getPost('emailsmtpdebug', '0')));
     setGlobalSetting('emailsmtpuser', strip_tags(returnGlobal('emailsmtpuser')));
     setGlobalSetting('filterxsshtml', strip_tags($_POST['filterxsshtml']));
     setGlobalSetting('siteadminbounce', strip_tags($_POST['siteadminbounce']));
     setGlobalSetting('siteadminemail', strip_tags($_POST['siteadminemail']));
     setGlobalSetting('siteadminname', strip_tags($_POST['siteadminname']));
     setGlobalSetting('shownoanswer', sanitize_int($_POST['shownoanswer']));
     setGlobalSetting('showxquestions', $_POST['showxquestions']);
     setGlobalSetting('showgroupinfo', $_POST['showgroupinfo']);
     setGlobalSetting('showqnumcode', $_POST['showqnumcode']);
     $repeatheadingstemp = (int) $_POST['repeatheadings'];
     if ($repeatheadingstemp == 0) {
         $repeatheadingstemp = 25;
     }
     setGlobalSetting('repeatheadings', $repeatheadingstemp);
     setGlobalSetting('maxemails', sanitize_int($maxemails));
     $iSessionExpirationTime = (int) $_POST['iSessionExpirationTime'];
     if ($iSessionExpirationTime == 0) {
         $iSessionExpirationTime = 7200;
     }
     setGlobalSetting('iSessionExpirationTime', $iSessionExpirationTime);
     setGlobalSetting('ipInfoDbAPIKey', $_POST['ipInfoDbAPIKey']);
     setGlobalSetting('googleMapsAPIKey', $_POST['googleMapsAPIKey']);
     setGlobalSetting('googleanalyticsapikey', $_POST['googleanalyticsapikey']);
     setGlobalSetting('googletranslateapikey', $_POST['googletranslateapikey']);
     setGlobalSetting('force_ssl', $_POST['force_ssl']);
     setGlobalSetting('surveyPreview_require_Auth', $_POST['surveyPreview_require_Auth']);
     setGlobalSetting('RPCInterface', $_POST['RPCInterface']);
     $savetime = (double) $_POST['timeadjust'] * 60 . ' minutes';
     //makes sure it is a number, at least 0
     if (substr($savetime, 0, 1) != '-' && substr($savetime, 0, 1) != '+') {
         $savetime = '+' . $savetime;
     }
     setGlobalSetting('timeadjust', $savetime);
     setGlobalSetting('usercontrolSameGroupPolicy', strip_tags($_POST['usercontrolSameGroupPolicy']));
     Yii::app()->session['flashmessage'] = $clang->gT("Global settings were saved.");
     $url = htmlspecialchars_decode(Yii::app()->session['refurl']);
     if ($url) {
         Yii::app()->getController()->redirect($url);
     }
 }
/**
* Shows the welcome page, used in group by group and question by question mode
*/
function display_first_page()
{
    global $token, $surveyid, $thissurvey, $navigator;
    $totalquestions = $_SESSION['survey_' . $surveyid]['totalquestions'];
    // Fill some necessary var for template
    $aNavigator = surveymover();
    $moveprevbutton = $aNavigator['sMovePrevButton'];
    $movenextbutton = $aNavigator['sMoveNextButton'];
    $navigator = $moveprevbutton . ' ' . $movenextbutton;
    $sitename = Yii::app()->getConfig('sitename');
    $languagechanger = makeLanguageChangerSurvey(App()->language);
    sendCacheHeaders();
    doHeader();
    LimeExpressionManager::StartProcessingPage();
    LimeExpressionManager::StartProcessingGroup(-1, false, $surveyid);
    // start on welcome page
    $redata = compact(array_keys(get_defined_vars()));
    $oTemplate = Template::model()->getInstance('', $surveyid);
    $sTemplatePath = $oTemplate->path;
    $sTemplateViewPath = $oTemplate->viewPath;
    echo templatereplace(file_get_contents($sTemplateViewPath . "startpage.pstpl"), array(), $redata, 'frontend_helper[2757]');
    echo CHtml::form(array("/survey/index", "sid" => $surveyid), 'post', array('id' => 'limesurvey', 'name' => 'limesurvey', 'autocomplete' => 'off', 'class' => 'frontend_helper'));
    echo templatereplace(file_get_contents($sTemplateViewPath . "welcome.pstpl"), array(), $redata, 'frontend_helper[2762]') . "\n";
    if ($thissurvey['anonymized'] == "Y") {
        echo templatereplace(file_get_contents($sTemplateViewPath . "/privacy.pstpl"), array(), $redata, 'frontend_helper[2765]') . "\n";
    }
    echo templatereplace(file_get_contents($sTemplateViewPath . "navigator.pstpl"), array(), $redata, 'frontend_helper[2767]');
    echo "\n<input type='hidden' name='sid' value='{$surveyid}' id='sid' />\n";
    if (isset($token) && !empty($token)) {
        echo "\n<input type='hidden' name='token' value='{$token}' id='token' />\n";
    }
    echo "\n<input type='hidden' name='lastgroupname' value='_WELCOME_SCREEN_' id='lastgroupname' />\n";
    //This is to ensure consistency with mandatory checks, and new group test
    $loadsecurity = returnGlobal('loadsecurity', true);
    if (isset($loadsecurity)) {
        echo "\n<input type='hidden' name='loadsecurity' value='{$loadsecurity}' id='loadsecurity' />\n";
    }
    $_SESSION['survey_' . $surveyid]['LEMpostKey'] = mt_rand();
    echo "<input type='hidden' name='LEMpostKey' value='{$_SESSION['survey_' . $surveyid]['LEMpostKey']}' id='LEMpostKey' />\n";
    echo "<input type='hidden' name='thisstep' id='thisstep' value='0' />\n";
    echo "<!--frontendhelper --></form>";
    echo templatereplace(file_get_contents($sTemplateViewPath . "endpage.pstpl"), array(), $redata, 'frontend_helper[2782]');
    echo LimeExpressionManager::GetRelevanceAndTailoringJavaScript();
    LimeExpressionManager::FinishProcessingPage();
    doFooter();
    echo "<!-- end of frontend_helper /  display_first_page -->";
}