/**
* fixes the numbering of questions
* This can happen if question 1 have subquestion code 1 and have question 11 in same survey and group (then same SGQA)
* @param int $fixnumbering
* @todo can call this function (no $_GET, but getParam) AND do it with Yii
*/
function fixNumbering($iQuestionID, $iSurveyID)
{
    Yii::app()->loadHelper("database");
    LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
    //Fix a question id - requires renumbering a question
    $iQuestionID = (int) $iQuestionID;
    $iMaxQID = Question::model()->getMaxId('qid', true);
    // Always refresh as we insert new qid's
    $iNewQID = $iMaxQID + 1;
    // Not sure we can do this in MSSQL ?
    $sQuery = "UPDATE {{questions}} SET qid={$iNewQID} WHERE qid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    // Update subquestions
    $sQuery = "UPDATE {{questions}} SET parent_qid={$iNewQID} WHERE parent_qid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    //Update conditions.. firstly conditions FOR this question
    $sQuery = "UPDATE {{conditions}} SET qid={$iNewQID} WHERE qid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    //Update default values
    $sQuery = "UPDATE {{defaultvalues}} SET qid={$iNewQID} WHERE qid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    $sQuery = "UPDATE {{defaultvalues}} SET sqid={$iNewQID} WHERE sqid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    //Update quotas
    $sQuery = "UPDATE {{quota_members}} SET qid={$iNewQID} WHERE qid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    //Update url params
    $sQuery = "UPDATE {{survey_url_parameters}} SET targetqid={$iNewQID} WHERE targetqid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    $sQuery = "UPDATE {{survey_url_parameters}} SET targetsqid={$iNewQID} WHERE targetsqid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    //Now conditions based upon this question
    $sQuery = "SELECT cqid, cfieldname FROM {{conditions}} WHERE cqid={$iQuestionID}";
    $sResult = Yii::app()->db->createCommand($sQuery)->query();
    foreach ($sResult->readAll() as $row) {
        $aSwitcher[] = array("cqid" => $row['cqid'], "cfieldname" => $row['cfieldname']);
    }
    if (isset($aSwitcher)) {
        foreach ($aSwitcher as $aSwitch) {
            $sQuery = "UPDATE {{conditions}}\n            SET cqid={$iNewQID},\n            cfieldname='" . str_replace("X" . $iQuestionID, "X" . $iNewQID, $aSwitch['cfieldname']) . "'\n            WHERE cqid={$iQuestionID}";
            $sResult = db_execute_assosc($sQuery);
        }
    }
    //Now question_attributes
    $sQuery = "UPDATE {{question_attributes}} SET qid={$iNewQID} WHERE qid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    //Now answers
    $sQuery = "UPDATE {{answers}} SET qid={$iNewQID} WHERE qid={$iQuestionID}";
    Yii::app()->db->createCommand($sQuery)->query();
    LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
}
 function actiontokens($surveyid, $token, $langcode = '')
 {
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('sanitize');
     $sLanguageCode = $langcode;
     $iSurveyID = $surveyid;
     $sToken = $token;
     $sToken = sanitize_token($sToken);
     if (!$iSurveyID) {
         $this->redirect(array('/'));
     }
     $iSurveyID = (int) $iSurveyID;
     //Check that there is a SID
     // Get passed language from form, so that we dont loose this!
     if (!isset($sLanguageCode) || $sLanguageCode == "" || !$sLanguageCode) {
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
     } else {
         $sBaseLanguage = sanitize_languagecode($sLanguageCode);
     }
     Yii::app()->setLanguage($sBaseLanguage);
     $aSurveyInfo = getSurveyInfo($iSurveyID, $sBaseLanguage);
     if ($aSurveyInfo == false || !tableExists("{{tokens_{$iSurveyID}}}")) {
         throw new CHttpException(404, "This survey does not seem to exist. It may have been deleted or the link you were given is outdated or incorrect.");
     } else {
         LimeExpressionManager::singleton()->loadTokenInformation($iSurveyID, $token, false);
         $oToken = Token::model($iSurveyID)->findByAttributes(array('token' => $token));
         if (!isset($oToken)) {
             $sMessage = gT('You are not a participant in this survey.');
         } else {
             if ($oToken->emailstatus == 'OptOut') {
                 $oToken->emailstatus = 'OK';
                 $oToken->save();
                 $sMessage = gT('You have been successfully added back to this survey.');
             } elseif ($oToken->emailstatus == 'OK') {
                 $sMessage = gT('You are already a part of this survey.');
             } else {
                 $sMessage = gT('You have been already removed from this survey.');
             }
         }
     }
     //PRINT COMPLETED PAGE
     if (!$aSurveyInfo['templatedir']) {
         $sTemplate = getTemplatePath(Yii::app()->getConfig("defaulttemplate"));
     } else {
         $sTemplate = getTemplatePath($aSurveyInfo['templatedir']);
     }
     $this->_renderHtml($sMessage, $sTemplate, $aSurveyInfo);
 }
/**
* fixes the numbering of questions
* @param <type> $fixnumbering
*/
function fixNumbering($fixnumbering, $iSurveyID)
{
    Yii::app()->loadHelper("database");
    LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
    //Fix a question id - requires renumbering a question
    $oldqid = $fixnumbering;
    $query = "SELECT qid FROM {{questions}} ORDER BY qid DESC";
    $result = dbSelectLimitAssoc($query, 1);
    foreach ($result->readAll() as $row) {
        $lastqid = $row['qid'];
    }
    $newqid = $lastqid + 1;
    $query = "UPDATE {{questions}} SET qid={$newqid} WHERE qid={$oldqid}";
    $result = db_execute_assosc($query);
    // Update subquestions
    $query = "UPDATE {{questions}} SET parent_qid={$newqid} WHERE parent_qid={$oldqid}";
    $result = db_execute_assosc($query);
    //Update conditions.. firstly conditions FOR this question
    $query = "UPDATE {{conditions}} SET qid={$newqid} WHERE qid={$oldqid}";
    $result = db_execute_assosc($query);
    //Now conditions based upon this question
    $query = "SELECT cqid, cfieldname FROM {{conditions}} WHERE cqid={$oldqid}";
    $result = dbExecuteAssoc($query);
    foreach ($result->readAll() as $row) {
        $switcher[] = array("cqid" => $row['cqid'], "cfieldname" => $row['cfieldname']);
    }
    if (isset($switcher)) {
        foreach ($switcher as $switch) {
            $query = "UPDATE {{conditions}}\n            SET cqid={$newqid},\n            cfieldname='" . str_replace("X" . $oldqid, "X" . $newqid, $switch['cfieldname']) . "'\n            WHERE cqid={$oldqid}";
            $result = db_execute_assosc($query);
        }
    }
    // TMSW Conditions->Relevance:  (1) Call LEM->ConvertConditionsToRelevance()when done. (2) Should relevance for old conditions be removed first?
    //Now question_attributes
    $query = "UPDATE {{question_attributes}} SET qid={$newqid} WHERE qid={$oldqid}";
    $result = db_execute_assosc($query);
    //Now answers
    $query = "UPDATE {{answers}} SET qid={$newqid} WHERE qid={$oldqid}";
    $result = db_execute_assosc($query);
    LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
}
Beispiel #4
0
/**
* fixes the numbering of questions
* @global $dbprefix $dbprefix
* @global $connect $connect
* @global $clang $clang
* @param <type> $fixnumbering
*/
function fixNumbering($fixnumbering)
{
    global $dbprefix, $connect, $clang, $surveyid;
    LimeExpressionManager::RevertUpgradeConditionsToRelevance($surveyid);
    //Fix a question id - requires renumbering a question
    $oldqid = sanitize_int($fixnumbering);
    $query = "SELECT qid FROM {$dbprefix}questions ORDER BY qid DESC";
    $result = db_select_limit_assoc($query, 1) or safe_die($query . "<br />" . $connect->ErrorMsg());
    while ($row = $result->FetchRow()) {
        $lastqid = $row['qid'];
    }
    $newqid = $lastqid + 1;
    $query = "UPDATE {$dbprefix}questions SET qid={$newqid} WHERE qid={$oldqid}";
    $result = $connect->Execute($query) or safe_die($query . "<br />" . $connect->ErrorMsg());
    // Update subquestions
    $query = "UPDATE {$dbprefix}questions SET parent_qid={$newqid} WHERE parent_qid={$oldqid}";
    $result = $connect->Execute($query) or safe_die($query . "<br />" . $connect->ErrorMsg());
    //Update conditions.. firstly conditions FOR this question
    $query = "UPDATE {$dbprefix}conditions SET qid={$newqid} WHERE qid={$oldqid}";
    $result = $connect->Execute($query) or safe_die($query . "<br />" . $connect->ErrorMsg());
    //Now conditions based upon this question
    $query = "SELECT cqid, cfieldname FROM {$dbprefix}conditions WHERE cqid={$oldqid}";
    $result = db_execute_assoc($query) or safe_die($query . "<br />" . $connect->ErrorMsg());
    while ($row = $result->FetchRow()) {
        $switcher[] = array("cqid" => $row['cqid'], "cfieldname" => $row['cfieldname']);
    }
    if (isset($switcher)) {
        foreach ($switcher as $switch) {
            $query = "UPDATE {$dbprefix}conditions\n            SET cqid={$newqid},\n            cfieldname='" . str_replace("X" . $oldqid, "X" . $newqid, $switch['cfieldname']) . "'\n            WHERE cqid={$oldqid}";
            $result = $connect->Execute($query) or safe_die($query . "<br />" . $connect->ErrorMsg());
        }
    }
    //Now question_attributes
    $query = "UPDATE {$dbprefix}question_attributes SET qid={$newqid} WHERE qid={$oldqid}";
    $result = $connect->Execute($query) or safe_die($query . "<br />" . $connect->ErrorMsg());
    //Now answers
    $query = "UPDATE {$dbprefix}answers SET qid={$newqid} WHERE qid={$oldqid}";
    $result = $connect->Execute($query) or safe_die($query . "<br />" . $connect->ErrorMsg());
    LimeExpressionManager::UpgradeConditionsToRelevance($surveyid);
}
<?php

$data = LimeExpressionManager::UpgradeConditionsToRelevance();
if (is_null($data)) {
    echo "No conditions found in database";
} else {
    echo "Found and converted conditions for " . count($data) . " question(s)<br/>";
    echo "<pre>";
    print_r($data);
    echo "</pre>";
}
    $clang = new limesurvey_lang("en");
    $surveyInfo = explode('|', $_POST['sid']);
    $surveyid = $surveyInfo[0];
    $assessments = $surveyInfo[1] == 'Y';
    $surveyMode = $_POST['surveyMode'];
    $LEMdebugLevel = (isset($_POST['LEM_DEBUG_TIMING']) && $_POST['LEM_DEBUG_TIMING'] == 'Y' ? LEM_DEBUG_TIMING : 0) + (isset($_POST['LEM_DEBUG_VALIDATION_SUMMARY']) && $_POST['LEM_DEBUG_VALIDATION_SUMMARY'] == 'Y' ? LEM_DEBUG_VALIDATION_SUMMARY : 0) + (isset($_POST['LEM_DEBUG_VALIDATION_DETAIL']) && $_POST['LEM_DEBUG_VALIDATION_DETAIL'] == 'Y' ? LEM_DEBUG_VALIDATION_DETAIL : 0) + (isset($_POST['LEM_DEBUG_LOG_SYNTAX_ERRORS_TO_DB']) && $_POST['LEM_DEBUG_LOG_SYNTAX_ERRORS_TO_DB'] == 'Y' ? LEM_DEBUG_LOG_SYNTAX_ERRORS_TO_DB : 0) + (isset($_POST['LEM_PRETTY_PRINT_ALL_SYNTAX']) && $_POST['LEM_PRETTY_PRINT_ALL_SYNTAX'] == 'Y' ? LEM_PRETTY_PRINT_ALL_SYNTAX : 0);
    $surveyOptions = array('active' => false, 'allowsave' => true, 'anonymized' => false, 'assessments' => $assessments, 'datestamp' => true, 'hyperlinkSyntaxHighlighting' => true, 'ipaddr' => true, 'rooturl' => '../../..');
    print '<h3>Starting survey ' . $surveyid . " using Survey Mode '" . $surveyMode . ($assessments ? "' [Uses Assessments]" : "'") . "</h3>";
    $now = microtime(true);
    LimeExpressionManager::StartSurvey($surveyid, $surveyMode, $surveyOptions, true, $LEMdebugLevel);
    print '<b>[StartSurvey() took ' . (microtime(true) - $now) . ' seconds]</b><br/>';
    while (true) {
        $now = microtime(true);
        $result = LimeExpressionManager::NavigateForwards(true);
        print $result['message'] . "<br/>";
        LimeExpressionManager::FinishProcessingPage();
        //                    print LimeExpressionManager::GetRelevanceAndTailoringJavaScript();
        if (($LEMdebugLevel & LEM_DEBUG_TIMING) == LEM_DEBUG_TIMING) {
            print LimeExpressionManager::GetDebugTimingMessage();
        }
        print '<b>[NavigateForwards() took ' . (microtime(true) - $now) . ' seconds]</b><br/>';
        if (is_null($result) || $result['finished'] == true) {
            break;
        }
    }
    print "<h3>Finished survey " . $surveyid . "</h3>";
}
?>
    </body>
</html>
 /**
  * printanswers::view()
  * View answers at the end of a survey in one place. To export as pdf, set 'usepdfexport' = 1 in lsconfig.php and $printableexport='pdf'.
  * @param mixed $surveyid
  * @param bool $printableexport
  * @return
  */
 function actionView($surveyid, $printableexport = FALSE)
 {
     Yii::app()->loadHelper("frontend");
     Yii::import('application.libraries.admin.pdf');
     $iSurveyID = (int) $surveyid;
     $sExportType = $printableexport;
     Yii::app()->loadHelper('database');
     if (isset($_SESSION['survey_' . $iSurveyID]['sid'])) {
         $iSurveyID = $_SESSION['survey_' . $iSurveyID]['sid'];
     } else {
         //die('Invalid survey/session');
     }
     // Get the survey inforamtion
     // Set the language for dispay
     if (isset($_SESSION['survey_' . $iSurveyID]['s_lang'])) {
         $sLanguage = $_SESSION['survey_' . $iSurveyID]['s_lang'];
     } elseif (Survey::model()->findByPk($iSurveyID)) {
         $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
     } else {
         $iSurveyID = 0;
         $sLanguage = Yii::app()->getConfig("defaultlang");
     }
     $clang = SetSurveyLanguage($iSurveyID, $sLanguage);
     $aSurveyInfo = getSurveyInfo($iSurveyID, $sLanguage);
     //SET THE TEMPLATE DIRECTORY
     if (!isset($aSurveyInfo['templatedir']) || !$aSurveyInfo['templatedir']) {
         $aSurveyInfo['templatedir'] = Yii::app()->getConfig('defaulttemplate');
     }
     $sTemplate = validateTemplateDir($aSurveyInfo['templatedir']);
     //Survey is not finished or don't exist
     if (!isset($_SESSION['survey_' . $iSurveyID]['finished']) || !isset($_SESSION['survey_' . $iSurveyID]['srid'])) {
         sendCacheHeaders();
         doHeader();
         echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/startpage.pstpl'), array());
         echo "<center><br />\n" . "\t<font color='RED'><strong>" . $clang->gT("Error") . "</strong></font><br />\n" . "\t" . $clang->gT("We are sorry but your session has expired.") . "<br />" . $clang->gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection.") . "<br />\n" . "\t" . sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), Yii::app()->getConfig("siteadminname"), Yii::app()->getConfig("siteadminemail")) . "\n" . "</center><br />\n";
         echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/endpage.pstpl'), array());
         doFooter();
         exit;
     }
     //Fin session time out
     $sSRID = $_SESSION['survey_' . $iSurveyID]['srid'];
     //I want to see the answers with this id
     //Ensure script is not run directly, avoid path disclosure
     //if (!isset($rootdir) || isset($_REQUEST['$rootdir'])) {die( "browse - Cannot run this script directly");}
     if ($aSurveyInfo['printanswers'] == 'N') {
         die;
         //Die quietly if print answers is not permitted
     }
     //CHECK IF SURVEY IS ACTIVATED AND EXISTS
     $sSurveyName = $aSurveyInfo['surveyls_title'];
     $sAnonymized = $aSurveyInfo['anonymized'];
     //OK. IF WE GOT THIS FAR, THEN THE SURVEY EXISTS AND IT IS ACTIVE, SO LETS GET TO WORK.
     //SHOW HEADER
     $sOutput = CHtml::form(array("printanswers/view/surveyid/{$iSurveyID}/printableexport/pdf"), 'post') . "<center><input type='submit' value='" . $clang->gT("PDF export") . "'id=\"exportbutton\"/><input type='hidden' name='printableexport' /></center></form>";
     if ($sExportType == 'pdf') {
         //require (Yii::app()->getConfig('rootdir').'/application/config/tcpdf.php');
         Yii::import('application.libraries.admin.pdf', true);
         Yii::import('application.helpers.pdfHelper');
         $aPdfLanguageSettings = pdfHelper::getPdfLanguageSettings($clang->langcode);
         $oPDF = new pdf();
         $oPDF->SetTitle($clang->gT("Survey name (ID)", 'unescaped') . ": {$sSurveyName} ({$iSurveyID})");
         $oPDF->SetSubject($sSurveyName);
         $oPDF->SetDisplayMode('fullpage', 'two');
         $oPDF->setLanguageArray($aPdfLanguageSettings['lg']);
         $oPDF->setHeaderFont(array($aPdfLanguageSettings['pdffont'], '', PDF_FONT_SIZE_MAIN));
         $oPDF->setFooterFont(array($aPdfLanguageSettings['pdffont'], '', PDF_FONT_SIZE_DATA));
         $oPDF->SetFont($aPdfLanguageSettings['pdffont'], '', $aPdfLanguageSettings['pdffontsize']);
         $oPDF->AddPage();
         $oPDF->titleintopdf($clang->gT("Survey name (ID)", 'unescaped') . ": {$sSurveyName} ({$iSurveyID})");
     }
     $sOutput .= "\t<div class='printouttitle'><strong>" . $clang->gT("Survey name (ID):") . "</strong> {$sSurveyName} ({$iSurveyID})</div><p>&nbsp;\n";
     LimeExpressionManager::StartProcessingPage(true);
     // means that all variables are on the same page
     // Since all data are loaded, and don't need JavaScript, pretend all from Group 1
     LimeExpressionManager::StartProcessingGroup(1, $aSurveyInfo['anonymized'] != "N", $iSurveyID);
     $printanswershonorsconditions = Yii::app()->getConfig('printanswershonorsconditions');
     $aFullResponseTable = getFullResponseTable($iSurveyID, $sSRID, $sLanguage, $printanswershonorsconditions);
     //Get the fieldmap @TODO: do we need to filter out some fields?
     if ($aSurveyInfo['datestamp'] != "Y" || $sAnonymized == 'Y') {
         unset($aFullResponseTable['submitdate']);
     } else {
         unset($aFullResponseTable['id']);
     }
     unset($aFullResponseTable['token']);
     unset($aFullResponseTable['lastpage']);
     unset($aFullResponseTable['startlanguage']);
     unset($aFullResponseTable['datestamp']);
     unset($aFullResponseTable['startdate']);
     $sOutput .= "<table class='printouttable' >\n";
     foreach ($aFullResponseTable as $sFieldname => $fname) {
         if (substr($sFieldname, 0, 4) == 'gid_') {
             $sOutput .= "\t<tr class='printanswersgroup'><td colspan='2'>{$fname[0]}</td></tr>\n";
         } elseif (substr($sFieldname, 0, 4) == 'qid_') {
             $sOutput .= "\t<tr class='printanswersquestionhead'><td colspan='2'>{$fname[0]}</td></tr>\n";
         } elseif ($sFieldname == 'submitdate') {
             if ($sAnonymized != 'Y') {
                 $sOutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]} {$sFieldname}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>";
             }
         } else {
             $sOutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]}</td><td class='printanswersanswertext'>" . flattenText($fname[2]) . "</td></tr>";
         }
     }
     $sOutput .= "</table>\n";
     $sData['thissurvey'] = $aSurveyInfo;
     $sOutput = templatereplace($sOutput, array(), $sData, '', $aSurveyInfo['anonymized'] == "Y", NULL, array(), true);
     // Do a static replacement
     if ($sExportType == 'pdf') {
         $oPDF->writeHTML($sOutput);
         header("Pragma: public");
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         $sExportFileName = sanitize_filename($sSurveyName);
         $oPDF->Output($sExportFileName . "-" . $iSurveyID . ".pdf", "D");
     } else {
         ob_start(function ($buffer, $phase) {
             App()->getClientScript()->render($buffer);
             App()->getClientScript()->reset();
             return $buffer;
         });
         ob_implicit_flush(false);
         sendCacheHeaders();
         doHeader();
         echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/startpage.pstpl'), array(), $sData);
         echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/printanswers.pstpl'), array('ANSWERTABLE' => $sOutput), $sData);
         echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/endpage.pstpl'), array(), $sData);
         echo "</body></html>";
         ob_flush();
     }
     LimeExpressionManager::FinishProcessingGroup();
     LimeExpressionManager::FinishProcessingPage();
 }
function ReplaceFields($text, $fieldsarray, $bReplaceInsertans = true, $staticReplace = true)
{
    if ($bReplaceInsertans) {
        $replacements = array();
        foreach ($fieldsarray as $key => $value) {
            $replacements[substr($key, 1, -1)] = $value;
        }
        $text = LimeExpressionManager::ProcessString($text, NULL, $replacements, false, 2, 1, false, false, $staticReplace);
    } else {
        foreach ($fieldsarray as $key => $value) {
            $text = str_replace($key, $value, $text);
        }
    }
    return $text;
}
Beispiel #9
0
 /**
  * dataentry::view()
  * view a dataentry
  * @param mixed $surveyid
  * @param mixed $lang
  * @return
  */
 public function view($surveyid, $lang = NULL)
 {
     $surveyid = sanitize_int($surveyid);
     $lang = isset($_GET['lang']) ? $_GET['lang'] : NULL;
     if (isset($lang)) {
         $lang = sanitize_languagecode($lang);
     }
     $aViewUrls = array();
     if (hasSurveyPermission($surveyid, 'responses', 'read')) {
         $clang = Yii::app()->lang;
         $sDataEntryLanguage = Survey::model()->findByPk($surveyid)->language;
         $surveyinfo = getSurveyInfo($surveyid);
         $slangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
         $baselang = Survey::model()->findByPk($surveyid)->language;
         array_unshift($slangs, $baselang);
         if (is_null($lang) || !in_array($lang, $slangs)) {
             $sDataEntryLanguage = $baselang;
             $blang = $clang;
         } else {
             Yii::app()->loadLibrary('Limesurvey_lang', array($lang));
             $blang = new Limesurvey_lang($lang);
             $sDataEntryLanguage = $lang;
         }
         $langlistbox = languageDropdown($surveyid, $sDataEntryLanguage);
         $thissurvey = getSurveyInfo($surveyid);
         //This is the default, presenting a blank dataentry form
         LimeExpressionManager::StartSurvey($surveyid, 'survey', NULL, false, LEM_PRETTY_PRINT_ALL_SYNTAX);
         $moveResult = LimeExpressionManager::NavigateForwards();
         $aData['thissurvey'] = $thissurvey;
         $aData['langlistbox'] = $langlistbox;
         $aData['surveyid'] = $surveyid;
         $aData['blang'] = $blang;
         $aData['site_url'] = Yii::app()->homeUrl;
         LimeExpressionManager::StartProcessingPage(true, Yii::app()->baseUrl);
         // means that all variables are on the same page
         $aViewUrls[] = 'caption_view';
         Yii::app()->loadHelper('database');
         // SURVEY NAME AND DESCRIPTION TO GO HERE
         $degquery = "SELECT * FROM {{groups}} WHERE sid={$surveyid} AND language='{$sDataEntryLanguage}' ORDER BY {{groups}}.group_order";
         $degresult = dbExecuteAssoc($degquery);
         // GROUP NAME
         $aDataentryoutput = '';
         foreach ($degresult->readAll() as $degrow) {
             LimeExpressionManager::StartProcessingGroup($degrow['gid'], $thissurvey['anonymized'] != "N", $surveyid);
             $deqquery = "SELECT * FROM {{questions}} WHERE sid={$surveyid} AND parent_qid=0 AND gid={$degrow['gid']} AND language='{$sDataEntryLanguage}'";
             $deqrows = (array) dbExecuteAssoc($deqquery)->readAll();
             $aDataentryoutput .= "\t<tr>\n" . "<td colspan='3' align='center'><strong>" . flattenText($degrow['group_name'], true) . "</strong></td>\n" . "\t</tr>\n";
             $gid = $degrow['gid'];
             $aDataentryoutput .= "\t<tr class='data-entry-separator'><td colspan='3'></td></tr>\n";
             // Perform a case insensitive natural sort on group name then question title of a multidimensional array
             usort($deqrows, 'groupOrderThenQuestionOrder');
             $bgc = 'odd';
             foreach ($deqrows as $deqrow) {
                 $qidattributes = getQuestionAttributeValues($deqrow['qid'], $deqrow['type']);
                 $cdata['qidattributes'] = $qidattributes;
                 $hidden = isset($qidattributes['hidden']) ? $qidattributes['hidden'] : 0;
                 // TODO - can questions be hidden?  Are JavaScript variables names used?  Consistently with everywhere else?
                 //                    LimeExpressionManager::ProcessRelevance($qidattributes['relevance'],$deqrow['qid'],NULL,$deqrow['type'],$hidden);
                 // TMSW Conditions->Relevance:  Show relevance equation instead of conditions here - better yet, have data entry use survey-at-a-time but with different view
                 $qinfo = LimeExpressionManager::GetQuestionStatus($deqrow['qid']);
                 $relevance = trim($qinfo['info']['relevance']);
                 $explanation = trim($qinfo['relEqn']);
                 $validation = trim($qinfo['prettyValidTip']);
                 $qidattributes = getQuestionAttributeValues($deqrow['qid']);
                 $array_filter_help = flattenText($this->_array_filter_help($qidattributes, $sDataEntryLanguage, $surveyid));
                 if ($relevance != '' && $relevance != '1' || $validation != '' || $array_filter_help != '') {
                     $showme = '';
                     if ($bgc == "even") {
                         $bgc = "odd";
                     } else {
                         $bgc = "even";
                     }
                     //Do no alternate on explanation row
                     if ($relevance != '' && $relevance != '1') {
                         $showme = "[" . $blang->gT("Only answer this if the following conditions are met:") . "]<br />{$explanation}\n";
                     }
                     if ($showme != '' && $validation != '') {
                         $showme .= '<br/>';
                     }
                     if ($validation != '') {
                         $showme .= "[" . $blang->gT("The answer(s) must meet these validation criteria:") . "]<br />{$validation}\n";
                     }
                     if ($showme != '' && $array_filter_help != '') {
                         $showme .= '<br/>';
                     }
                     if ($array_filter_help != '') {
                         $showme .= "[" . $blang->gT("The answer(s) must meet these array_filter criteria:") . "]<br />{$array_filter_help}\n";
                     }
                     $cdata['explanation'] = "<tr class ='data-entry-explanation'><td class='data-entry-small-text' colspan='3' align='left'>{$showme}</td></tr>\n";
                 }
                 //END OF GETTING CONDITIONS
                 //Alternate bgcolor for different groups
                 if (!isset($bgc)) {
                     $bgc = "even";
                 }
                 if ($bgc == "even") {
                     $bgc = "odd";
                 } else {
                     $bgc = "even";
                 }
                 $qid = $deqrow['qid'];
                 $fieldname = "{$surveyid}" . "X" . "{$gid}" . "X" . "{$qid}";
                 $cdata['bgc'] = $bgc;
                 $cdata['fieldname'] = $fieldname;
                 $cdata['deqrow'] = $deqrow;
                 $cdata['clang'] = $clang;
                 //DIFFERENT TYPES OF DATA FIELD HERE
                 $cdata['blang'] = $blang;
                 $cdata['thissurvey'] = $thissurvey;
                 if ($deqrow['help']) {
                     $hh = addcslashes($deqrow['help'], "..'\"");
                     //Escape ASCII decimal 0-32 plus single and double quotes to make JavaScript happy.
                     $hh = htmlspecialchars($hh, ENT_QUOTES);
                     //Change & " ' < > to HTML entities to make HTML happy.
                     $cdata['hh'] = $hh;
                     //$aDataentryoutput .= "\t<img src='$imageurl/help.gif' alt='".$blang->gT("Help about this question")."' align='right' onclick=\"javascript:alert('Question {$deqrow['title']} Help: $hh')\" />\n";
                 }
                 switch ($deqrow['type']) {
                     case "Q":
                         //MULTIPLE SHORT TEXT
                     //MULTIPLE SHORT TEXT
                     case "K":
                         $deaquery = "SELECT question,title FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $dearesult = dbExecuteAssoc($deaquery);
                         $cdata['dearesult'] = $dearesult->readAll();
                         break;
                     case "1":
                         // multi scale^
                         $deaquery = "SELECT * FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$baselang}' ORDER BY question_order";
                         $dearesult = dbExecuteAssoc($deaquery);
                         $cdata['dearesult'] = $dearesult->readAll();
                         $oquery = "SELECT other FROM {{questions}} WHERE qid={$deqrow['qid']} AND language='{$baselang}'";
                         $oresult = dbExecuteAssoc($oquery) or safeDie("Couldn't get other for list question<br />" . $oquery);
                         foreach ($oresult->readAll() as $orow) {
                             $cdata['fother'] = $orow['other'];
                         }
                         break;
                     case "L":
                         //LIST drop-down/radio-button list
                     //LIST drop-down/radio-button list
                     case "!":
                         //                            $qidattributes=getQuestionAttributeValues($deqrow['qid']);
                         if ($deqrow['type'] == '!' && trim($qidattributes['category_separator']) != '') {
                             $optCategorySeparator = $qidattributes['category_separator'];
                         } else {
                             unset($optCategorySeparator);
                         }
                         $defexists = "";
                         $deaquery = "SELECT * FROM {{answers}} WHERE qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY sortorder, answer";
                         $dearesult = dbExecuteAssoc($deaquery);
                         //$aDataentryoutput .= "\t<select name='$fieldname'>\n";
                         $aDatatemp = '';
                         if (!isset($optCategorySeparator)) {
                             foreach ($dearesult->readAll() as $dearow) {
                                 $aDatatemp .= "<option value='{$dearow['code']}'";
                                 //if ($dearow['default_value'] == "Y") {$aDatatemp .= " selected='selected'"; $defexists = "Y";}
                                 $aDatatemp .= ">{$dearow['answer']}</option>\n";
                             }
                         } else {
                             $defaultopts = array();
                             $optgroups = array();
                             foreach ($dearesult->readAll() as $dearow) {
                                 list($categorytext, $answertext) = explode($optCategorySeparator, $dearow['answer']);
                                 if ($categorytext == '') {
                                     $defaultopts[] = array('code' => $dearow['code'], 'answer' => $answertext, 'default_value' => $dearow['assessment_value']);
                                 } else {
                                     $optgroups[$categorytext][] = array('code' => $dearow['code'], 'answer' => $answertext, 'default_value' => $dearow['assessment_value']);
                                 }
                             }
                             foreach ($optgroups as $categoryname => $optionlistarray) {
                                 $aDatatemp .= "<optgroup class=\"dropdowncategory\" label=\"" . $categoryname . "\">\n";
                                 foreach ($optionlistarray as $optionarray) {
                                     $aDatatemp .= "\t<option value='{$optionarray['code']}'";
                                     //if ($optionarray['default_value'] == "Y") {$aDatatemp .= " selected='selected'"; $defexists = "Y";}
                                     $aDatatemp .= ">{$optionarray['answer']}</option>\n";
                                 }
                                 $aDatatemp .= "</optgroup>\n";
                             }
                             foreach ($defaultopts as $optionarray) {
                                 $aDatatemp .= "\t<option value='{$optionarray['code']}'";
                                 //if ($optionarray['default_value'] == "Y") {$aDatatemp .= " selected='selected'"; $defexists = "Y";}
                                 $aDatatemp .= ">{$optionarray['answer']}</option>\n";
                             }
                         }
                         $oquery = "SELECT other FROM {{questions}} WHERE qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}'";
                         $oresult = dbExecuteAssoc($oquery) or safeDie("Couldn't get other for list question<br />");
                         foreach ($oresult->readAll() as $orow) {
                             $fother = $orow['other'];
                         }
                         $cdata['fother'] = $fother;
                         $cdata['defexists'] = $defexists;
                         $cdata['datatemp'] = $aDatatemp;
                         break;
                     case "O":
                         //LIST WITH COMMENT drop-down/radio-button list + textarea
                         $defexists = "";
                         $deaquery = "SELECT * FROM {{answers}} WHERE qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY sortorder, answer";
                         $dearesult = dbExecuteAssoc($deaquery);
                         //$aDataentryoutput .= "\t<select name='$fieldname'>\n";
                         $aDatatemp = '';
                         foreach ($dearesult->readAll() as $dearow) {
                             $aDatatemp .= "<option value='{$dearow['code']}'";
                             //if ($dearow['default_value'] == "Y") {$aDatatemp .= " selected='selected'"; $defexists = "Y";}
                             $aDatatemp .= ">{$dearow['answer']}</option>\n";
                         }
                         $cdata['datatemp'] = $aDatatemp;
                         $cdata['defexists'] = $defexists;
                         break;
                     case "R":
                         //RANKING TYPE QUESTION
                         $thisqid = $deqrow['qid'];
                         $ansquery = "SELECT * FROM {{answers}} WHERE qid={$thisqid} AND language='{$sDataEntryLanguage}' ORDER BY sortorder, answer";
                         $ansresult = dbExecuteAssoc($ansquery);
                         $ansresult = $ansresult->readAll();
                         $anscount = count($ansresult);
                         $cdata['thisqid'] = $thisqid;
                         $cdata['anscount'] = $anscount;
                         foreach ($ansresult as $ansrow) {
                             $answers[] = array($ansrow['code'], $ansrow['answer']);
                         }
                         for ($i = 1; $i <= $anscount; $i++) {
                             if (isset($fname)) {
                                 $myfname = $fname . $i;
                             }
                             if (isset($myfname) && Yii::app()->session[$myfname]) {
                                 $existing++;
                             }
                         }
                         for ($i = 1; $i <= $anscount; $i++) {
                             if (isset($fname)) {
                                 $myfname = $fname . $i;
                             }
                             if (isset($myfname) && Yii::app()->session[$myfname]) {
                                 foreach ($answers as $ans) {
                                     if ($ans[0] == Yii::app()->session[$myfname]) {
                                         $thiscode = $ans[0];
                                         $thistext = $ans[1];
                                     }
                                 }
                             }
                             if (!isset($ranklist)) {
                                 $ranklist = "";
                             }
                             $ranklist .= "&nbsp;<font color='#000080'>{$i}:&nbsp;<input class='ranklist' type='text' name='RANK{$i}' id='RANK_{$thisqid}{$i}'";
                             if (isset($myfname) && Yii::app()->session[$myfname]) {
                                 $ranklist .= " value='";
                                 $ranklist .= $thistext;
                                 $ranklist .= "'";
                             }
                             $ranklist .= " onFocus=\"this.blur()\"  />\n";
                             $ranklist .= "<input type='hidden' id='d{$fieldname}{$i}' name='{$fieldname}{$i}' value='";
                             $chosen[] = "";
                             //create array
                             if (isset($myfname) && Yii::app()->session[$myfname]) {
                                 $ranklist .= $thiscode;
                                 $chosen[] = array($thiscode, $thistext);
                             }
                             $ranklist .= "' /></font>\n";
                             $ranklist .= "<img src='" . Yii::app()->getConfig('imageurl') . "/cut.gif' alt='" . $blang->gT("Remove this item") . "' title='" . $blang->gT("Remove this item") . "' ";
                             if (!isset($existing) || $i != $existing) {
                                 $ranklist .= "style='display:none'";
                             }
                             $mfn = $fieldname . $i;
                             $ranklist .= " id='cut_{$thisqid}{$i}' onclick=\"deletethis_{$thisqid}(document.addsurvey.RANK_{$thisqid}{$i}.value, document.addsurvey.d{$fieldname}{$i}.value, document.addsurvey.RANK_{$thisqid}{$i}.id, this.id)\" /><br />\n\n";
                         }
                         if (!isset($choicelist)) {
                             $choicelist = "";
                         }
                         $choicelist .= "<select size='{$anscount}' class='choicelist' name='CHOICES' id='CHOICES_{$thisqid}' onclick=\"rankthis_{$thisqid}(this.options[this.selectedIndex].value, this.options[this.selectedIndex].text)\" >\n";
                         foreach ($answers as $ans) {
                             if (!in_array($ans, $chosen)) {
                                 $choicelist .= "\t<option value='{$ans[0]}'>{$ans[1]}</option>\n";
                             }
                         }
                         $choicelist .= "</select>\n";
                         $cdata['choicelist'] = $choicelist;
                         $cdata['ranklist'] = $ranklist;
                         if (isset($multifields)) {
                             $cdata['multifields'] = $multifields;
                         }
                         $choicelist = "";
                         $ranklist = "";
                         unset($answers);
                         break;
                     case "M":
                         //Multiple choice checkbox (Quite tricky really!)
                         //                            $qidattributes=getQuestionAttributeValues($deqrow['qid']);
                         if (trim($qidattributes['display_columns']) != '') {
                             $dcols = $qidattributes['display_columns'];
                         } else {
                             $dcols = 0;
                         }
                         $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery);
                         $cdata['dcols'] = $dcols;
                         $cdata['meacount'] = $meacount;
                         $cdata['mearesult'] = $mearesult->readAll();
                         $meacount = count($cdata['mearesult']);
                         break;
                     case "I":
                         //Language Switch
                         $slangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
                         $sbaselang = Survey::model()->findByPk($surveyid)->language;
                         array_unshift($slangs, $sbaselang);
                         $cdata['slangs'] = $slangs;
                         break;
                     case "P":
                         //Multiple choice with comments checkbox + text
                         //$aDataentryoutput .= "<table border='0'>\n";
                         $meaquery = "SELECT * FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order, question";
                         $mearesult = dbExecuteAssoc($meaquery);
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case "|":
                         //                            $qidattributes = getQuestionAttributeValues($deqrow['qid']);
                         $cdata['qidattributes'] = $qidattributes;
                         $maxfiles = $qidattributes['max_num_of_files'];
                         $cdata['maxfiles'] = $maxfiles;
                         break;
                     case "A":
                         //ARRAY (5 POINT CHOICE) radio-buttons
                         $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery);
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case "B":
                         //ARRAY (10 POINT CHOICE) radio-buttons
                         $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery);
                         $cdata['mearesult'] = $mearesult->readAll();
                     case "C":
                         //ARRAY (YES/UNCERTAIN/NO) radio-buttons
                         $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery);
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case "E":
                         //ARRAY (YES/UNCERTAIN/NO) radio-buttons
                         $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery) or safeDie("Couldn't get answers, Type \"E\"<br />{$meaquery}<br />");
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case ":":
                         //ARRAY (Multi Flexi)
                         //                            $qidattributes=getQuestionAttributeValues($deqrow['qid']);
                         $minvalue = 1;
                         $maxvalue = 10;
                         if (trim($qidattributes['multiflexible_max']) != '' && trim($qidattributes['multiflexible_min']) == '') {
                             $maxvalue = $qidattributes['multiflexible_max'];
                             $minvalue = 1;
                         }
                         if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) == '') {
                             $minvalue = $qidattributes['multiflexible_min'];
                             $maxvalue = $qidattributes['multiflexible_min'] + 10;
                         }
                         if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) != '') {
                             if ($qidattributes['multiflexible_min'] < $qidattributes['multiflexible_max']) {
                                 $minvalue = $qidattributes['multiflexible_min'];
                                 $maxvalue = $qidattributes['multiflexible_max'];
                             }
                         }
                         if (trim($qidattributes['multiflexible_step']) != '') {
                             $stepvalue = $qidattributes['multiflexible_step'];
                         } else {
                             $stepvalue = 1;
                         }
                         if ($qidattributes['multiflexible_checkbox'] != 0) {
                             $minvalue = 0;
                             $maxvalue = 1;
                             $stepvalue = 1;
                         }
                         $cdata['minvalue'] = $minvalue;
                         $cdata['maxvalue'] = $maxvalue;
                         $cdata['stepvalue'] = $stepvalue;
                         $lquery = "SELECT question, title FROM {{questions}} WHERE parent_qid={$deqrow['qid']} and scale_id=1 and language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $lresult = dbExecuteAssoc($lquery) or die("Couldn't get labels, Type \":\"<br />{$lquery}<br />");
                         $cdata['lresult'] = $lresult->readAll();
                         $meaquery = "SELECT question, title FROM {{questions}} WHERE parent_qid={$deqrow['qid']} and scale_id=0 and language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery) or die("Couldn't get answers, Type \":\"<br />{$meaquery}<br />");
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case ";":
                         //ARRAY (Multi Flexi)
                         $lquery = "SELECT * FROM {{questions}} WHERE scale_id=1 and parent_qid={$deqrow['qid']} and language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $lresult = dbExecuteAssoc($lquery) or die("Couldn't get labels, Type \":\"<br />{$lquery}<br />");
                         $cdata['lresult'] = $lresult->readAll();
                         $meaquery = "SELECT * FROM {{questions}} WHERE scale_id=0 and parent_qid={$deqrow['qid']} and language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery) or die("Couldn't get answers, Type \":\"<br />{$meaquery}<br />");
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case "F":
                         //ARRAY (Flexible Labels)
                     //ARRAY (Flexible Labels)
                     case "H":
                         $meaquery = "SELECT * FROM {{questions}} WHERE parent_qid={$deqrow['qid']} and language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery) or safeDie("Couldn't get answers, Type \"E\"<br />{$meaquery}<br />");
                         $cdata['mearesult'] = $mearesult->readAll();
                         $fquery = "SELECT * FROM {{answers}} WHERE qid={$deqrow['qid']} and language='{$sDataEntryLanguage}' ORDER BY sortorder, code";
                         $fresult = dbExecuteAssoc($fquery);
                         $cdata['fresult'] = $fresult->readAll();
                         break;
                 }
                 $cdata['sDataEntryLanguage'] = $sDataEntryLanguage;
                 $viewdata = $this->getController()->render("/admin/dataentry/content_view", $cdata, TRUE);
                 $viewdata_em = LimeExpressionManager::ProcessString($viewdata, $deqrow['qid'], NULL, false, 1, 1);
                 $aDataentryoutput .= $viewdata_em;
             }
             LimeExpressionManager::FinishProcessingGroup();
         }
         LimeExpressionManager::FinishProcessingPage();
         $aDataentryoutput .= LimeExpressionManager::GetRelevanceAndTailoringJavaScript();
         $aViewUrls['output'] = $aDataentryoutput;
         $aData['thissurvey'] = $thissurvey;
         $aData['surveyid'] = $surveyid;
         $aData['sDataEntryLanguage'] = $sDataEntryLanguage;
         if ($thissurvey['active'] == "Y" && $thissurvey['allowsave'] == "Y") {
             $slangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
             $sbaselang = Survey::model()->findByPk($surveyid)->language;
             array_unshift($slangs, $sbaselang);
             $aData['slangs'] = $slangs;
             $aData['baselang'] = $baselang;
         }
         $aViewUrls[] = 'active_html_view';
         $this->_renderWrappedTemplate('dataentry', $aViewUrls, $aData);
     }
 }
 /**
  * Construction of replacement array, actually doing it with redata
  *
  * @param $aQuestionQanda : array from qanda helper
  * @return aray of replacement for question.psptl
  **/
 public static function getQuestionReplacement($aQuestionQanda)
 {
     // Get the default replacement and set empty value by default
     $aReplacement = array("QID" => "", "SGQ" => "", "AID" => "", "QUESTION_CODE" => "", "QUESTION_NUMBER" => "", "QUESTION" => "", "QUESTION_TEXT" => "", "QUESTIONHELP" => "", "QUESTIONHELPPLAINTEXT" => "", "QUESTION_CLASS" => "", "QUESTION_MAN_CLASS" => "", "QUESTION_INPUT_ERROR_CLASS" => "", "ANSWER" => "", "QUESTION_HELP" => "", "QUESTION_VALID_MESSAGE" => "", "QUESTION_FILE_VALID_MESSAGE" => "", "QUESTION_MAN_MESSAGE" => "", "QUESTION_MANDATORY" => "", "QUESTION_ESSENTIALS" => "");
     if (!is_array($aQuestionQanda) || empty($aQuestionQanda[0])) {
         return $aReplacement;
     }
     $iQid = $aQuestionQanda[4];
     $lemQuestionInfo = LimeExpressionManager::GetQuestionStatus($iQid);
     $iSurveyId = Yii::app()->getConfig('surveyID');
     // Or : by SGQA of question ? by Question::model($iQid)->sid;
     $oSurveyId = Survey::model()->findByPk($iSurveyId);
     $sType = $lemQuestionInfo['info']['type'];
     // Core value : not replaced
     $aReplacement['QID'] = $iQid;
     $aReplacement['GID'] = $aQuestionQanda[6];
     // Not sure for aleatory : it's the real gid or the updated gid ? We need original gid or updated gid ?
     $aReplacement['SGQ'] = $aQuestionQanda[7];
     $aReplacement['AID'] = isset($aQuestionQanda[0]['aid']) ? $aQuestionQanda[0]['aid'] : "";
     $aReplacement['QUESTION_CODE'] = $aReplacement['QUESTION_NUMBER'] = "";
     $sCode = $aQuestionQanda[5];
     $iNumber = $aQuestionQanda[0]['number'];
     switch (Yii::app()->getConfig('showqnumcode')) {
         case 'both':
             $aReplacement['QUESTION_CODE'] = $sCode;
             $aReplacement['QUESTION_NUMBER'] = $iNumber;
             break;
         case 'number':
             $aReplacement['QUESTION_NUMBER'] = $iNumber;
             break;
         case 'number':
             $aReplacement['QUESTION_CODE'] = $sCode;
             break;
         case 'choose':
         default:
             switch ($oSurveyId->showqnumcode) {
                 case 'B':
                     // Both
                     $aReplacement['QUESTION_CODE'] = $sCode;
                     $aReplacement['QUESTION_NUMBER'] = $iNumber;
                     break;
                 case 'N':
                     $aReplacement['QUESTION_NUMBER'] = $iNumber;
                     break;
                 case 'C':
                     $aReplacement['QUESTION_CODE'] = $sCode;
                     break;
                 case 'X':
                 default:
                     break;
             }
             break;
     }
     $aReplacement['QUESTION'] = $aQuestionQanda[0]['all'];
     // Deprecated : only used in old template (very old)
     // Core value : user text
     $aReplacement['QUESTION_TEXT'] = $aQuestionQanda[0]['text'];
     $aReplacement['QUESTIONHELP'] = $lemQuestionInfo['info']['help'];
     // User help
     // To be moved in a extra plugin : QUESTIONHELP img adding
     $sTemplateDir = Template::model()->getTemplatePath($oSurveyId->template);
     $sTemplateUrl = Template::model()->getTemplateURL($oSurveyId->template);
     if (flattenText($aReplacement['QUESTIONHELP'], true, true) != '') {
         $aReplacement['QUESTIONHELP'] = Yii::app()->getController()->renderPartial('/survey/system/questionhelp/questionhelp', array('questionHelp' => $aReplacement['QUESTIONHELP']), true);
     }
     // Core value :the classes
     $aReplacement['QUESTION_CLASS'] = Question::getQuestionClass($sType);
     //get additional question classes from question attribute
     $aQuestionAttributes = getQuestionAttributeValues($aQuestionQanda[4]);
     //add additional classes
     if (isset($aQuestionAttributes['cssclass'])) {
         $aReplacement['QUESTION_CLASS'] .= " " . $aQuestionAttributes['cssclass'];
     }
     $aMandatoryClass = array();
     if ($lemQuestionInfo['info']['mandatory'] == 'Y') {
         $aMandatoryClass[] = 'mandatory';
     }
     if ($lemQuestionInfo['anyUnanswered'] && $_SESSION['survey_' . $iSurveyId]['maxstep'] != $_SESSION['survey_' . $iSurveyId]['step']) {
         $aMandatoryClass[] = 'missing';
     }
     $aReplacement['QUESTION_MAN_CLASS'] = !empty($aMandatoryClass) ? " " . implode(" ", $aMandatoryClass) : "";
     $aReplacement['QUESTION_INPUT_ERROR_CLASS'] = $aQuestionQanda[0]['input_error_class'];
     // Core value : LS text : EM and not
     $aReplacement['ANSWER'] = $aQuestionQanda[1];
     $aReplacement['QUESTION_HELP'] = $aQuestionQanda[0]['help'];
     // Core help only, not EM
     $aReplacement['QUESTION_VALID_MESSAGE'] = $aQuestionQanda[0]['valid_message'];
     // $lemQuestionInfo['validTip']
     $aReplacement['QUESTION_FILE_VALID_MESSAGE'] = $aQuestionQanda[0]['file_valid_message'];
     // $lemQuestionInfo['??']
     $aReplacement['QUESTION_MAN_MESSAGE'] = $aQuestionQanda[0]['man_message'];
     $aReplacement['QUESTION_MANDATORY'] = $aQuestionQanda[0]['mandatory'];
     // For QUESTION_ESSENTIALS
     $aHtmlOptions = array();
     if (!$lemQuestionInfo['relevant'] || $lemQuestionInfo['hidden']) {
         $aHtmlOptions['style'] = 'display: none;';
     }
     // Launch the event
     $event = new PluginEvent('beforeQuestionRender');
     // Some helper
     $event->set('surveyId', $iSurveyId);
     $event->set('type', $sType);
     $event->set('code', $sCode);
     $event->set('qid', $iQid);
     $event->set('gid', $aReplacement['GID']);
     // User text
     $event->set('text', $aReplacement['QUESTION_TEXT']);
     $event->set('questionhelp', $aReplacement['QUESTIONHELP']);
     // The classes
     $event->set('class', $aReplacement['QUESTION_CLASS']);
     $event->set('man_class', $aReplacement['QUESTION_MAN_CLASS']);
     $event->set('input_error_class', $aReplacement['QUESTION_INPUT_ERROR_CLASS']);
     // LS core text
     $event->set('answers', $aReplacement['ANSWER']);
     $event->set('help', $aReplacement['QUESTION_HELP']);
     $event->set('man_message', $aReplacement['QUESTION_MAN_MESSAGE']);
     $event->set('valid_message', $aReplacement['QUESTION_VALID_MESSAGE']);
     $event->set('file_valid_message', $aReplacement['QUESTION_FILE_VALID_MESSAGE']);
     // htmlOptions for container
     $event->set('aHtmlOptions', $aHtmlOptions);
     App()->getPluginManager()->dispatchEvent($event);
     // User text
     $aReplacement['QUESTION_TEXT'] = $event->get('text');
     $aReplacement['QUESTIONHELP'] = $event->get('questionhelp');
     $aReplacement['QUESTIONHELPPLAINTEXT'] = strip_tags(addslashes($aReplacement['QUESTIONHELP']));
     // The classes
     $aReplacement['QUESTION_CLASS'] = $event->get('class');
     $aReplacement['QUESTION_MAN_CLASS'] = $event->get('man_class');
     $aReplacement['QUESTION_INPUT_ERROR_CLASS'] = $event->get('input_error_class');
     // LS core text
     $aReplacement['ANSWER'] = $event->get('answers');
     $aReplacement['QUESTION_HELP'] = $event->get('help');
     $aReplacement['QUESTION_MAN_MESSAGE'] = $event->get('man_message');
     $aReplacement['QUESTION_VALID_MESSAGE'] = $event->get('valid_message');
     $aReplacement['QUESTION_FILE_VALID_MESSAGE'] = $event->get('file_valid_message');
     $aReplacement['QUESTION_MANDATORY'] = $event->get('mandatory', $aReplacement['QUESTION_MANDATORY']);
     // Always add id for QUESTION_ESSENTIALS
     $aHtmlOptions['id'] = "question{$iQid}";
     $aReplacement['QUESTION_ESSENTIALS'] = CHtml::renderAttributes($aHtmlOptions);
     return $aReplacement;
 }
Beispiel #11
0
                } else {
                    $conditionDuplicated = true;
                }
            }
        }
        if (isset($conditionCopied) && $conditionCopied === true) {
            if (isset($conditionDuplicated) && $conditionDuplicated == true) {
                $CopyConditionsMessage = "<div class='partialheader'>(" . $clang->gT("Conditions successfully copied (some were skipped because they were duplicates)") . ")</div>";
            } else {
                $CopyConditionsMessage = "<div class='successheader'>(" . $clang->gT("Conditions successfully copied") . ")</div>";
            }
        } else {
            $CopyConditionsMessage = "<div class='warningheader'>(" . $clang->gT("No conditions could be copied (due to duplicates)") . ")</div>";
        }
    }
    LimeExpressionManager::UpgradeConditionsToRelevance($surveyid);
    // 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($surveyid)) {
    $surveyid = returnglobal('sid');
}
$thissurvey = getSurveyInfo($surveyid);
$query = "SELECT * " . "FROM {$dbprefix}questions, " . "{$dbprefix}groups " . "WHERE {$dbprefix}questions.gid={$dbprefix}groups.gid " . "AND qid={$qid} " . "AND parent_qid=0 " . "AND {$dbprefix}questions.language='" . GetBaseLanguageFromSurveyID($surveyid) . "'";
 private function translate_google_api()
 {
     $sBaselang = Yii::app()->getRequest()->getPost('baselang');
     $sTolang = Yii::app()->getRequest()->getPost('tolang');
     $sToconvert = Yii::app()->getRequest()->getPost('text');
     $aSearch = array('zh-Hans', 'zh-Hant-HK', 'zh-Hant-TW', 'nl-informal', 'de-informal', 'it-formal', 'pt-BR', 'es-MX', 'nb', 'nn');
     $aReplace = array('zh-CN', 'zh-TW', 'zh-TW', 'nl', 'de', 'it', 'pt', 'es', 'no', 'no');
     $sBaselang = str_replace($aSearch, $aReplace, $sBaselang);
     $sTolang = str_replace($aSearch, $aReplace, $sTolang);
     $error = false;
     try {
         require_once APPPATH . '/third_party/gtranslate-api/GTranslate.php';
         $gtranslate = new Gtranslate();
         $objGt = $gtranslate;
         // Gtranslate requires you to run function named XXLANG_to_XXLANG
         $sProcedure = $sBaselang . "_to_" . $sTolang;
         $parts = LimeExpressionManager::SplitStringOnExpressions($sToconvert);
         $sparts = array();
         foreach ($parts as $part) {
             if ($part[2] == 'EXPRESSION') {
                 $sparts[] = $part[0];
             } else {
                 $convertedPart = $objGt->{$sProcedure}($part[0]);
                 $convertedPart = str_replace("<br>", "\r\n", $convertedPart);
                 $convertedPart = html_entity_decode(stripcslashes($convertedPart));
                 $sparts[] = $convertedPart;
             }
         }
         $sOutput = implode(' ', $sparts);
     } catch (GTranslateException $ge) {
         // Get the error message and build the ouput array
         $error = TRUE;
         $sOutput = $ge->getMessage();
     }
     $aOutput = array('error' => $error, 'baselang' => $sBaselang, 'tolang' => $sTolang, 'converted' => $sOutput);
     header('Content-type: application/json');
     return ls_json_encode($aOutput);
     Yii::app()->end();
 }
Beispiel #13
0
/**
* Import survey from an TSV file template that does not require or allow assigning of GID or QID values.
* NOTE:  This currently only supports import of one language
* @global type $connect
* @global type $dbprefix
* @global type $clang
* @global type $timeadjust
* @param type $sFullFilePath
* @return type
*
* @author TMSWhite
*/
function TSVImportSurvey($sFullFilePath)
{
    $clang = Yii::app()->lang;
    $insertdata = array();
    $results = array();
    $results['error'] = false;
    $baselang = 'en';
    // TODO set proper default
    $encoding = '';
    $handle = fopen($sFullFilePath, 'r');
    $bom = fread($handle, 2);
    rewind($handle);
    $aAttributeList = questionAttributes();
    // Excel tends to save CSV as UTF-16, which PHP does not properly detect
    if ($bom === chr(0xff) . chr(0xfe) || $bom === chr(0xfe) . chr(0xff)) {
        // UTF16 Byte Order Mark present
        $encoding = 'UTF-16';
    } else {
        $file_sample = fread($handle, 1000) + 'e';
        //read first 1000 bytes
        // + e is a workaround for mb_string bug
        rewind($handle);
        $encoding = mb_detect_encoding($file_sample, 'UTF-8, UTF-7, ASCII, EUC-JP,SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP');
    }
    if ($encoding && $encoding != 'UTF-8') {
        stream_filter_append($handle, 'convert.iconv.' . $encoding . '/UTF-8');
    }
    $file = stream_get_contents($handle);
    fclose($handle);
    // fix Excel non-breaking space
    $file = str_replace("0xC20xA0", ' ', $file);
    $filelines = explode("\n", $file);
    $row = array_shift($filelines);
    $headers = explode("\t", $row);
    $rowheaders = array();
    foreach ($headers as $header) {
        $rowheaders[] = trim($header);
    }
    // remove BOM from the first header cell, if needed
    $rowheaders[0] = preg_replace("/^\\W+/", "", $rowheaders[0]);
    if (preg_match('/class$/', $rowheaders[0])) {
        $rowheaders[0] = 'class';
        // second attempt to remove BOM
    }
    $adata = array();
    foreach ($filelines as $rowline) {
        $rowarray = array();
        $row = explode("\t", $rowline);
        for ($i = 0; $i < count($rowheaders); ++$i) {
            $val = isset($row[$i]) ? $row[$i] : '';
            // if Excel was used, it surrounds strings with quotes and doubles internal double quotes.  Fix that.
            if (preg_match('/^".*"$/', $val)) {
                $val = str_replace('""', '"', substr($val, 1, -1));
            }
            $rowarray[$rowheaders[$i]] = $val;
        }
        $adata[] = $rowarray;
    }
    $results['defaultvalues'] = 0;
    $results['answers'] = 0;
    $results['surveys'] = 0;
    $results['languages'] = 0;
    $results['questions'] = 0;
    $results['subquestions'] = 0;
    $results['question_attributes'] = 0;
    $results['groups'] = 0;
    $results['importwarnings'] = array();
    // these aren't used here, but are needed to avoid errors in post-import display
    $results['assessments'] = 0;
    $results['quota'] = 0;
    $results['quotamembers'] = 0;
    $results['quotals'] = 0;
    // collect information about survey and its language settings
    $surveyinfo = array();
    $surveyls = array();
    foreach ($adata as $row) {
        switch ($row['class']) {
            case 'S':
                if (isset($row['text']) && $row['name'] != 'datecreated') {
                    $surveyinfo[$row['name']] = $row['text'];
                }
                break;
            case 'SL':
                if (!isset($surveyls[$row['language']])) {
                    $surveyls[$row['language']] = array();
                }
                if (isset($row['text'])) {
                    $surveyls[$row['language']][$row['name']] = $row['text'];
                }
                break;
        }
    }
    $iOldSID = 1;
    if (isset($surveyinfo['sid'])) {
        $iOldSID = (int) $surveyinfo['sid'];
    }
    // Create the survey entry
    $surveyinfo['startdate'] = NULL;
    $surveyinfo['active'] = 'N';
    // unset($surveyinfo['datecreated']);
    $iNewSID = Survey::model()->insertNewSurvey($surveyinfo);
    //or safeDie($clang->gT("Error").": Failed to insert survey<br />");
    if (!$iNewSID) {
        $results['error'] = Survey::model()->getErrors();
        $results['bFailed'] = true;
        return $results;
    }
    $surveyinfo['sid'] = $iNewSID;
    $results['surveys']++;
    $results['newsid'] = $iNewSID;
    $gid = 0;
    $gseq = 0;
    // group_order
    $qid = 0;
    $qseq = 0;
    // question_order
    $qtype = 'T';
    $aseq = 0;
    // answer sortorder
    // set the language for the survey
    $_title = 'Missing Title';
    foreach ($surveyls as $_lang => $insertdata) {
        $insertdata['surveyls_survey_id'] = $iNewSID;
        $insertdata['surveyls_language'] = $_lang;
        if (isset($insertdata['surveyls_title'])) {
            $_title = $insertdata['surveyls_title'];
        } else {
            $insertdata['surveyls_title'] = $_title;
        }
        $result = SurveyLanguageSetting::model()->insertNewSurvey($insertdata);
        //
        if (!$result) {
            $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Failed to insert survey language");
            break;
        }
        $results['languages']++;
    }
    $ginfo = array();
    $qinfo = array();
    $sqinfo = array();
    if (isset($surveyinfo['language'])) {
        $baselang = $surveyinfo['language'];
        // the base language
    }
    $rownumber = 1;
    $lastglang = '';
    foreach ($adata as $row) {
        $rownumber += 1;
        switch ($row['class']) {
            case 'G':
                // insert group
                $insertdata = array();
                $insertdata['sid'] = $iNewSID;
                $gname = !empty($row['name']) ? $row['name'] : 'G' . $gseq;
                $glang = !empty($row['language']) ? $row['language'] : $baselang;
                // when a multi-lang tsv-file without information on the group id/number (old style) is imported,
                // we make up this information by giving a number 0..[numberofgroups-1] per language.
                // the number and order of groups per language should be the same, so we can also import these files
                if ($lastglang != $glang) {
                    $iGroupcounter = 0;
                }
                $lastglang = $glang;
                //use group id/number from file. if missing, use an increasing number (s.a.)
                $sGroupseq = !empty($row['type/scale']) ? $row['type/scale'] : 'G' . $iGroupcounter++;
                $insertdata['group_name'] = $gname;
                $insertdata['grelevance'] = isset($row['relevance']) ? $row['relevance'] : '';
                $insertdata['description'] = isset($row['text']) ? $row['text'] : '';
                $insertdata['language'] = $glang;
                // For multi language survey: same gid/sort order across all languages
                if (isset($ginfo[$sGroupseq])) {
                    $gid = $ginfo[$sGroupseq]['gid'];
                    $insertdata['gid'] = $gid;
                    $insertdata['group_order'] = $ginfo[$sGroupseq]['group_order'];
                } else {
                    $insertdata['group_order'] = $gseq;
                }
                $newgid = QuestionGroup::model()->insertRecords($insertdata);
                if (!$newgid) {
                    $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Failed to insert group") . ". " . $clang->gT("Text file row number ") . $rownumber . " (" . $gname . ")";
                    break;
                }
                if (!isset($ginfo[$sGroupseq])) {
                    $results['groups']++;
                    $gid = $newgid;
                    $ginfo[$sGroupseq]['gid'] = $gid;
                    $ginfo[$sGroupseq]['group_order'] = $gseq++;
                }
                $qseq = 0;
                // reset the question_order
                break;
            case 'Q':
                // insert question
                $insertdata = array();
                $insertdata['sid'] = $iNewSID;
                $qtype = isset($row['type/scale']) ? $row['type/scale'] : 'T';
                $qname = isset($row['name']) ? $row['name'] : 'Q' . $qseq;
                $insertdata['gid'] = $gid;
                $insertdata['type'] = $qtype;
                $insertdata['title'] = $qname;
                $insertdata['question'] = isset($row['text']) ? $row['text'] : '';
                $insertdata['relevance'] = isset($row['relevance']) ? $row['relevance'] : '';
                $insertdata['preg'] = isset($row['validation']) ? $row['validation'] : '';
                $insertdata['help'] = isset($row['help']) ? $row['help'] : '';
                $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                $insertdata['mandatory'] = isset($row['mandatory']) ? $row['mandatory'] : '';
                $lastother = $insertdata['other'] = isset($row['other']) ? $row['other'] : 'N';
                // Keep trace of other settings for sub question
                $insertdata['same_default'] = isset($row['same_default']) ? $row['same_default'] : 0;
                $insertdata['parent_qid'] = 0;
                // For multi numeric survey : same name, add the gid to have same name on different gid. Bad for EM.
                $fullqname = "G{$gid}_" . $qname;
                if (isset($qinfo[$fullqname])) {
                    $qseq = $qinfo[$fullqname]['question_order'];
                    $qid = $qinfo[$fullqname]['qid'];
                    $insertdata['qid'] = $qid;
                    $insertdata['question_order'] = $qseq;
                } else {
                    $insertdata['question_order'] = $qseq;
                }
                // Insert question and keep the qid for multi language survey
                $result = Question::model()->insertRecords($insertdata);
                if (!$result) {
                    $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Could not insert question") . ". " . $clang->gT("Text file row number ") . $rownumber . " (" . $qname . ")";
                    break;
                }
                $newqid = $result;
                if (!isset($qinfo[$fullqname])) {
                    $results['questions']++;
                    $qid = $newqid;
                    // save this for later
                    $qinfo[$fullqname]['qid'] = $qid;
                    $qinfo[$fullqname]['question_order'] = $qseq++;
                }
                $aseq = 0;
                //reset the answer sortorder
                $sqseq = 0;
                //reset the sub question sortorder
                // insert question attributes
                foreach ($row as $key => $val) {
                    switch ($key) {
                        case 'class':
                        case 'type/scale':
                        case 'name':
                        case 'text':
                        case 'validation':
                        case 'relevance':
                        case 'help':
                        case 'language':
                        case 'mandatory':
                        case 'other':
                        case 'same_default':
                        case 'default':
                            break;
                        default:
                            if ($key != '' && $val != '') {
                                $insertdata = array();
                                $insertdata['qid'] = $qid;
                                // check if attribute is a i18n attribute. If yes, set language, else set language to null in attribute table
                                if (isset($aAttributeList[$qtype][$key]['i18n']) && $aAttributeList[$qtype][$key]['i18n'] == 1) {
                                    $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                                } else {
                                    $insertdata['language'] = NULL;
                                }
                                $insertdata['attribute'] = $key;
                                $insertdata['value'] = $val;
                                $result = QuestionAttribute::model()->insertRecords($insertdata);
                                //
                                if (!$result) {
                                    $results['importwarnings'][] = $clang->gT("Warning") . " : " . $clang->gT("Failed to insert question attribute") . ". " . $clang->gT("Text file row number ") . $rownumber . " ({$key})";
                                    break;
                                }
                                $results['question_attributes']++;
                            }
                            break;
                    }
                }
                // insert default value
                if (isset($row['default'])) {
                    $insertdata = array();
                    $insertdata['qid'] = $qid;
                    $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                    $insertdata['defaultvalue'] = $row['default'];
                    $result = DefaultValue::model()->insertRecords($insertdata);
                    if (!$result) {
                        $results['importwarnings'][] = $clang->gT("Warning") . " : " . $clang->gT("Failed to insert default value") . ". " . $clang->gT("Text file row number ") . $rownumber;
                        break;
                    }
                    $results['defaultvalues']++;
                }
                break;
            case 'SQ':
                $sqname = isset($row['name']) ? $row['name'] : 'SQ' . $sqseq;
                if ($qtype == 'O' || $qtype == '|') {
                    // these are fake rows to show naming of comment and filecount fields
                } elseif ($sqname == 'other' && $lastother == "Y") {
                    if ($qtype == "!" || $qtype == "L") {
                        // only used to set default value for 'other' in these cases
                        if (isset($row['default'])) {
                            $insertdata = array();
                            $insertdata['qid'] = $qid;
                            $insertdata['specialtype'] = 'other';
                            $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                            $insertdata['defaultvalue'] = $row['default'];
                            $result = DefaultValue::model()->insertRecords($insertdata);
                            if (!$result) {
                                $results['importwarnings'][] = $clang->gT("Warning") . " : " . $clang->gT("Failed to insert default value") . ". " . $clang->gT("Text file row number ") . $rownumber;
                                break;
                            }
                            $results['defaultvalues']++;
                        }
                    }
                } else {
                    $insertdata = array();
                    $scale_id = isset($row['type/scale']) ? $row['type/scale'] : 0;
                    $insertdata['sid'] = $iNewSID;
                    $insertdata['gid'] = $gid;
                    $insertdata['parent_qid'] = $qid;
                    $insertdata['type'] = $qtype;
                    $insertdata['title'] = $sqname;
                    $insertdata['question'] = isset($row['text']) ? $row['text'] : '';
                    $insertdata['relevance'] = isset($row['relevance']) ? $row['relevance'] : '';
                    $insertdata['preg'] = isset($row['validation']) ? $row['validation'] : '';
                    $insertdata['help'] = isset($row['help']) ? $row['help'] : '';
                    $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                    $insertdata['mandatory'] = isset($row['mandatory']) ? $row['mandatory'] : '';
                    $insertdata['scale_id'] = $scale_id;
                    // For multi nueric language, qid is needed, why not gid. name is not unique.
                    $fullsqname = "G{$gid}Q{$qid}_{$scale_id}_{$sqname}";
                    if (isset($sqinfo[$fullsqname])) {
                        $qseq = $sqinfo[$fullsqname]['question_order'];
                        $sqid = $sqinfo[$fullsqname]['sqid'];
                        $insertdata['question_order'] = $qseq;
                        $insertdata['qid'] = $sqid;
                    } else {
                        $insertdata['question_order'] = $qseq;
                    }
                    // Insert sub question and keep the sqid for multi language survey
                    $newsqid = Question::model()->insertRecords($insertdata);
                    if (!$newsqid) {
                        $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Could not insert subquestion") . ". " . $clang->gT("Text file row number ") . $rownumber . " (" . $qname . ")";
                        break;
                    }
                    if (!isset($sqinfo[$fullsqname])) {
                        $sqinfo[$fullsqname]['question_order'] = $qseq++;
                        $sqid = $newsqid;
                        // save this for later
                        $sqinfo[$fullsqname]['sqid'] = $sqid;
                        $results['subquestions']++;
                    }
                    // insert default value
                    if (isset($row['default'])) {
                        $insertdata = array();
                        $insertdata['qid'] = $qid;
                        $insertdata['sqid'] = $sqid;
                        $insertdata['scale_id'] = $scale_id;
                        $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                        $insertdata['defaultvalue'] = $row['default'];
                        $result = DefaultValue::model()->insertRecords($insertdata);
                        if (!$result) {
                            $results['importwarnings'][] = $clang->gT("Warning") . " : " . $clang->gT("Failed to insert default value") . ". " . $clang->gT("Text file row number ") . $rownumber;
                            break;
                        }
                        $results['defaultvalues']++;
                    }
                }
                break;
            case 'A':
                $insertdata = array();
                $insertdata['qid'] = $qid;
                $insertdata['code'] = isset($row['name']) ? $row['name'] : 'A' . $aseq;
                $insertdata['answer'] = isset($row['text']) ? $row['text'] : '';
                $insertdata['scale_id'] = isset($row['type/scale']) ? $row['type/scale'] : 0;
                $insertdata['language'] = isset($row['language']) ? $row['language'] : $baselang;
                $insertdata['assessment_value'] = (int) (isset($row['relevance']) ? $row['relevance'] : '');
                $insertdata['sortorder'] = ++$aseq;
                $result = Answer::model()->insertRecords($insertdata);
                // or safeDie("Error: Failed to insert answer<br />");
                if (!$result) {
                    $results['error'][] = $clang->gT("Error") . " : " . $clang->gT("Could not insert answer") . ". " . $clang->gT("Text file row number ") . $rownumber;
                }
                $results['answers']++;
                break;
        }
    }
    // Delete the survey if error found
    if (is_array($results['error'])) {
        $result = Survey::model()->deleteSurvey($iNewSID);
    } else {
        LimeExpressionManager::SetSurveyId($iNewSID);
        LimeExpressionManager::RevertUpgradeConditionsToRelevance($iNewSID);
        LimeExpressionManager::UpgradeConditionsToRelevance($iNewSID);
    }
    return $results;
}
<?php

$data = LimeExpressionManager::UnitTestConvertConditionsToRelevance();
echo count($data) . " question(s) in your database contain conditions.  Below is the mapping of question ID number to generated relevance equation<br/>";
echo "<pre>";
print_r($data);
echo "</pre>";
 /**
  * Action to delete a question group.
  *
  * @access public
  * @return void
  */
 public function delete($iSurveyId, $iGroupId)
 {
     $iSurveyId = sanitize_int($iSurveyId);
     if (Permission::model()->hasSurveyPermission($iSurveyId, 'surveycontent', 'delete')) {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyId);
         $iGroupId = sanitize_int($iGroupId);
         $iGroupsDeleted = QuestionGroup::deleteWithDependency($iGroupId, $iSurveyId);
         if ($iGroupsDeleted > 0) {
             fixSortOrderGroups($iSurveyId);
             Yii::app()->setFlashMessage(gT('The question group was deleted.'));
         } else {
             Yii::app()->setFlashMessage(gT('Group could not be deleted'), 'error');
         }
         LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyId);
         $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $iSurveyId));
     }
 }
function do_multiplenumeric($ia)
{
    global $thissurvey;
    $clang = Yii::app()->lang;
    $extraclass = "";
    $checkconditionFunction = "fixnum_checkconditions";
    $aQuestionAttributes = getQuestionAttributeValues($ia[0], $ia[4]);
    $answer = '';
    $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']);
    $sSeparator = $sSeparator['separator'];
    //Must turn on the "numbers only javascript"
    $extraclass .= " numberonly";
    if (intval(trim($aQuestionAttributes['maximum_chars'])) > 0) {
        // Only maxlength attribute, use textarea[maxlength] jquery selector for textarea
        $maximum_chars = intval(trim($aQuestionAttributes['maximum_chars']));
        $maxlength = "maxlength='{$maximum_chars}' ";
        $extraclass .= " maxchars maxchars-" . $maximum_chars;
    } else {
        $maxlength = " maxlength='25' ";
    }
    if (trim($aQuestionAttributes['prefix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') {
        $prefix = $aQuestionAttributes['prefix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']];
        $extraclass .= " withprefix";
    } else {
        $prefix = '';
    }
    if (trim($aQuestionAttributes['suffix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') {
        $suffix = $aQuestionAttributes['suffix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']];
        $extraclass .= " withsuffix";
    } else {
        $suffix = '';
    }
    if ($thissurvey['nokeyboard'] == 'Y') {
        includeKeypad();
        $kpclass = "num-keypad";
        $extraclass .= " keypad";
    } else {
        $kpclass = "";
    }
    $numbersonly_slider = '';
    // DEPRECATED
    if (trim($aQuestionAttributes['text_input_width']) != '') {
        $tiwidth = $aQuestionAttributes['text_input_width'];
        $extraclass .= " inputwidth" . trim($aQuestionAttributes['text_input_width']);
    } else {
        $tiwidth = 10;
    }
    $prefixclass = "numeric";
    if ($aQuestionAttributes['slider_layout'] == 1) {
        $prefixclass = "slider";
        $slider_layout = true;
        $extraclass .= " withslider";
        if (trim($aQuestionAttributes['slider_accuracy']) != '') {
            $slider_step = $aQuestionAttributes['slider_accuracy'];
        } else {
            $slider_step = 1;
        }
        if (trim($aQuestionAttributes['slider_min']) != '') {
            $slider_mintext = $aQuestionAttributes['slider_min'];
            $slider_min = $aQuestionAttributes['slider_min'];
        } else {
            $slider_mintext = 0;
            $slider_min = 0;
        }
        if (trim($aQuestionAttributes['slider_max']) != '') {
            $slider_maxtext = $aQuestionAttributes['slider_max'];
            $slider_max = $aQuestionAttributes['slider_max'];
        } else {
            $slider_maxtext = "100";
            $slider_max = 100;
        }
        $slider_default = trim($aQuestionAttributes['slider_default']) != '' ? $aQuestionAttributes['slider_default'] : "";
        if ($slider_default == '' && $aQuestionAttributes['slider_middlestart'] == 1) {
            $slider_middlestart = intval(($slider_max + $slider_min) / 2);
        } else {
            $slider_middlestart = '';
        }
        $slider_separator = trim($aQuestionAttributes['slider_separator']) != '' ? $aQuestionAttributes['slider_separator'] : "";
        $slider_reset = $aQuestionAttributes['slider_reset'] ? 1 : 0;
    } else {
        $slider_layout = false;
    }
    $hidetip = $aQuestionAttributes['hide_tip'];
    if ($aQuestionAttributes['random_order'] == 1) {
        $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']}  AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY " . dbRandom();
    } else {
        $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']}  AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY question_order";
    }
    $ansresult = dbExecuteAssoc($ansquery);
    //Checked
    $aSubquestions = $ansresult->readAll();
    $anscount = count($aSubquestions) * 2;
    $fn = 1;
    $answer_main = '';
    if ($anscount == 0) {
        $inputnames = array();
        $answer_main .= '    <li>' . $clang->gT('Error: This question has no answers.') . "</li>\n";
    } else {
        foreach ($aSubquestions as $ansrow) {
            $myfname = $ia[1] . $ansrow['title'];
            if ($ansrow['question'] == "") {
                $ansrow['question'] = "&nbsp;";
            }
            if ($slider_layout === false || $slider_separator == '') {
                $theanswer = $ansrow['question'];
                $sliderleft = '';
                $sliderright = '';
            } else {
                $aAnswer = explode($slider_separator, $ansrow['question']);
                $theanswer = isset($aAnswer[0]) ? $aAnswer[0] : "";
                $sliderleft = isset($aAnswer[1]) ? $aAnswer[1] : "";
                $sliderright = isset($aAnswer[2]) ? $aAnswer[2] : "";
                $sliderleft = "<div class=\"slider_lefttext\">{$sliderleft}</div>";
                $sliderright = "<div class=\"slider_righttext\">{$sliderright}</div>";
            }
            // color code missing mandatory questions red
            if ($ia[6] == 'Y' && ($_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['step'] == $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['prevstep'] || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['maxstep'] > $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['step']) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] === '') {
                $theanswer = "<span class='errormandatory'>{$theanswer}</span>";
            }
            list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname, '', $myfname, "li", "question-item answer-item text-item numeric-item" . $extraclass);
            $answer_main .= "\t{$htmltbody2}\n";
            $answer_main .= "<label for=\"answer{$myfname}\" class=\"{$prefixclass}-label\">{$theanswer}</label>\n";
            $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']);
            $sSeparator = $sSeparator['separator'];
            $answer_main .= "{$sliderleft}<span class=\"input\">\n\t" . $prefix . "\n\t<input class=\"text {$kpclass}\" type=\"text\" size=\"" . $tiwidth . "\" name=\"" . $myfname . "\" id=\"answer" . $myfname . "\" title=\"" . $clang->gT('Only numbers may be entered in this field.') . "\" value=\"";
            if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname])) {
                $dispVal = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname];
                if (strpos($dispVal, ".")) {
                    $dispVal = rtrim(rtrim($dispVal, "0"), ".");
                }
                $dispVal = str_replace('.', $sSeparator, $dispVal);
                $answer_main .= $dispVal;
            }
            $answer_main .= '" onkeyup="' . $checkconditionFunction . '(this.value, this.name, this.type);" ' . " {$maxlength} />\n\t" . $suffix . "\n</span>{$sliderright}\n\t</li>\n";
            $fn++;
            $inputnames[] = $myfname;
        }
        if (trim($aQuestionAttributes['equals_num_value']) != '' || trim($aQuestionAttributes['min_num_value']) != '' || trim($aQuestionAttributes['max_num_value']) != '') {
            $qinfo = LimeExpressionManager::GetQuestionStatus($ia[0]);
            if (trim($aQuestionAttributes['equals_num_value']) != '') {
                $answer_main .= "\t<li class='multiplenumerichelp help-item'>\n" . "<span class=\"label\">" . $clang->gT('Remaining: ') . "</span>\n" . "<span id=\"remainingvalue_{$ia[0]}\" class=\"dynamic_remaining\">{$prefix}\n" . "{" . $qinfo['sumRemainingEqn'] . "}\n" . "{$suffix}</span>\n" . "\t</li>\n";
            }
            $answer_main .= "\t<li class='multiplenumerichelp  help-item'>\n" . "<span class=\"label\">" . $clang->gT('Total: ') . "</span>\n" . "<span id=\"totalvalue_{$ia[0]}\" class=\"dynamic_sum\">{$prefix}\n" . "{" . $qinfo['sumEqn'] . "}\n" . "{$suffix}</span>\n" . "\t</li>\n";
        }
        $answer .= "<ul class=\"subquestions-list questions-list text-list {$prefixclass}-list\">\n" . $answer_main . "</ul>\n";
    }
    if ($aQuestionAttributes['slider_layout'] == 1) {
        Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "numeric-slider.js");
        Yii::app()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl') . "numeric-slider.css");
        if ($slider_default != "") {
            $slider_startvalue = $slider_default;
            $slider_displaycallout = 1;
        } elseif ($slider_middlestart != '') {
            $slider_startvalue = $slider_middlestart;
            $slider_displaycallout = 0;
        } else {
            $slider_startvalue = 'NULL';
            $slider_displaycallout = 0;
        }
        $slider_showminmax = $aQuestionAttributes['slider_showminmax'] == 1 ? 1 : 0;
        //some var for slider
        $aJsLang = array('reset' => $clang->gT('Reset'), 'tip' => $clang->gT('Please click and drag the slider handles to enter your answer.'));
        $aJsVar = array('slider_showminmax' => $slider_showminmax, 'slider_min' => $slider_min, 'slider_mintext' => $slider_mintext, 'slider_max' => $slider_max, 'slider_maxtext' => $slider_maxtext, 'slider_step' => $slider_step, 'slider_startvalue' => $slider_startvalue, 'slider_displaycallout' => $slider_displaycallout, 'slider_prefix' => $prefix, 'slider_suffix' => $suffix, 'slider_reset' => $slider_reset, 'lang' => $aJsLang);
        $answer .= "<script type='text/javascript'><!--\n" . " doNumericSlider({$ia[0]}," . ls_json_encode($aJsVar) . ");\n" . " //--></script>";
    }
    $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']);
    $sSeparator = $sSeparator['separator'];
    return array($answer, $inputnames);
}
    ?>
</td>
<td><?php 
    echo $assess['maximum'];
    ?>
</td>
<td><?php 
    $aReplacementData = array();
    templatereplace($assess['name'], array(), $aReplacementData, 'Unspecified', false, $assess['sid']);
    echo FlattenText(LimeExpressionManager::GetLastPrettyPrintExpression(), true);
    ?>
</td>
<td><?php 
    $aReplacementData = array();
    templatereplace($assess['message'], array(), $aReplacementData, 'Unspecified', false, $assess['sid']);
    echo FlattenText(LimeExpressionManager::GetLastPrettyPrintExpression(), true);
    ?>
</td>

</tr>
<?php 
}
?>
</tbody></table>

<?php 
if (Permission::model()->hasSurveyPermission($surveyid, 'assessments', 'update') && $actionvalue == "assessmentupdate" || Permission::model()->hasSurveyPermission($surveyid, 'assessments', 'create') && $actionvalue == "assessmentadd") {
    ?>
<br />
<?php 
    echo CHtml::form(array("admin/assessments/sa/index/surveyid/{$surveyid}"), 'post', array('class' => 'form30', 'id' => 'assessmentsform', 'name' => 'assessmentsform'));
 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?
 }
Beispiel #19
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);
     }
 }
Beispiel #20
0
 /**
  * Set the value of a registered variable
  * @param $op - the operator (=,*=,/=,+=,-=)
  * @param <type> $name
  * @param <type> $value
  */
 private function RDP_SetVariableValue($op, $name, $value)
 {
     if ($this->RDP_onlyparse) {
         return 1;
     }
     return LimeExpressionManager::SetVariableValue($op, $name, $value);
 }
/**
* Creates an array with details on a particular response for display purposes
* Used in Print answers, Detailed response view and Detailed admin notification email
*
* @param mixed $iSurveyID
* @param mixed $iResponseID
* @param mixed $sLanguageCode
* @param boolean $bHonorConditions Apply conditions
*/
function getFullResponseTable($iSurveyID, $iResponseID, $sLanguageCode, $bHonorConditions = true)
{
    $aFieldMap = createFieldMap($iSurveyID, 'full', false, false, $sLanguageCode);
    //Get response data
    $idrow = SurveyDynamic::model($iSurveyID)->findByAttributes(array('id' => $iResponseID));
    // Create array of non-null values - those are the relevant ones
    $aRelevantFields = array();
    foreach ($aFieldMap as $sKey => $fname) {
        if (LimeExpressionManager::QuestionIsRelevant($fname['qid']) || $bHonorConditions == false) {
            $aRelevantFields[$sKey] = $fname;
        }
    }
    $aResultTable = array();
    $oldgid = 0;
    $oldqid = 0;
    foreach ($aRelevantFields as $sKey => $fname) {
        if (!empty($fname['qid'])) {
            $attributes = getQuestionAttributeValues($fname['qid']);
            if (getQuestionAttributeValue($attributes, 'hidden') == 1) {
                continue;
            }
        }
        $question = $fname['question'];
        $subquestion = '';
        if (isset($fname['gid']) && !empty($fname['gid'])) {
            //Check to see if gid is the same as before. if not show group name
            if ($oldgid !== $fname['gid']) {
                $oldgid = $fname['gid'];
                if (LimeExpressionManager::GroupIsRelevant($fname['gid']) || $bHonorConditions == false) {
                    $aResultTable['gid_' . $fname['gid']] = array($fname['group_name'], QuestionGroup::model()->getGroupDescription($fname['gid'], $sLanguageCode));
                }
            }
        }
        if (!empty($fname['qid'])) {
            if ($oldqid !== $fname['qid']) {
                $oldqid = $fname['qid'];
                if (isset($fname['subquestion']) || isset($fname['subquestion1']) || isset($fname['subquestion2'])) {
                    $aResultTable['qid_' . $fname['sid'] . 'X' . $fname['gid'] . 'X' . $fname['qid']] = array($fname['question'], '', '');
                } else {
                    $answer = getExtendedAnswer($iSurveyID, $fname['fieldname'], $idrow[$fname['fieldname']], $sLanguageCode);
                    $aResultTable[$fname['fieldname']] = array($question, '', $answer);
                    continue;
                }
            }
        } else {
            $answer = getExtendedAnswer($iSurveyID, $fname['fieldname'], $idrow[$fname['fieldname']], $sLanguageCode);
            $aResultTable[$fname['fieldname']] = array($question, '', $answer);
            continue;
        }
        if (isset($fname['subquestion'])) {
            $subquestion = "[{$fname['subquestion']}]";
        }
        if (isset($fname['subquestion1'])) {
            $subquestion = "[{$fname['subquestion1']}]";
        }
        if (isset($fname['subquestion2'])) {
            $subquestion .= "[{$fname['subquestion2']}]";
        }
        $answer = getExtendedAnswer($iSurveyID, $fname['fieldname'], $idrow[$fname['fieldname']], $sLanguageCode);
        $aResultTable[$fname['fieldname']] = array($question, $subquestion, $answer);
    }
    return $aResultTable;
}
background-color:white;
}

.LEMerror
{
color:red;
font-weight:bold;
}

tr.LEMsubq td
{
background-color:lightyellow;
}
</style>
</head>
<body>
EOD;


    SetSurveyLanguage($surveyid, $language);
    LimeExpressionManager::SetDirtyFlag();
    $result = LimeExpressionManager::ShowSurveyLogicFile($surveyid, $gid, $qid,$LEMdebugLevel,$assessments);
    print $result['html'];

    print <<< EOD
</body>
</html>
EOD;
}
?>
Beispiel #23
0
function do_array_dual($ia)
{
    global $thissurvey;
    $aLastMoveResult = LimeExpressionManager::GetLastMoveResult();
    $aMandatoryViolationSubQ = $aLastMoveResult['mandViolation'] && $ia[6] == 'Y' ? explode("|", $aLastMoveResult['unansweredSQs']) : array();
    $repeatheadings = Yii::app()->getConfig("repeatheadings");
    $minrepeatheadings = Yii::app()->getConfig("minrepeatheadings");
    $extraclass = "";
    $answertypeclass = "";
    // Maybe not
    $caption = "";
    // Just leave empty, are replaced after
    $inputnames = array();
    $labelans1 = array();
    $labelans = array();
    $aQuestionAttributes = getQuestionAttributeValues($ia[0]);
    if ($aQuestionAttributes['random_order'] == 1) {
        $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=0 ORDER BY " . dbRandom();
    } else {
        $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=0 ORDER BY question_order";
    }
    $ansresult = dbExecuteAssoc($ansquery);
    //Checked
    $aSubQuestions = $ansresult->readAll();
    $anscount = count($aSubQuestions);
    $lquery = "SELECT * FROM {{answers}} WHERE scale_id=0 AND qid={$ia[0]} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY sortorder, code";
    $lresult = dbExecuteAssoc($lquery);
    //Checked
    $aAnswersScale0 = $lresult->readAll();
    $lquery1 = "SELECT * FROM {{answers}} WHERE scale_id=1 AND qid={$ia[0]} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY sortorder, code";
    $lresult1 = dbExecuteAssoc($lquery1);
    //Checked
    $aAnswersScale1 = $lresult1->readAll();
    if ($aQuestionAttributes['use_dropdown'] == 1) {
        $useDropdownLayout = true;
        $extraclass .= " dropdown-list";
        $answertypeclass .= " dropdown";
        $doDualScaleFunction = "doDualScaleDropDown";
        // javascript funtion to lauch at end of answers
        $caption = gT("An array with sub-question on each line, with 2 answers to provide on each line. You have to select the answer.");
    } else {
        $useDropdownLayout = false;
        $extraclass .= " radio-list";
        $answertypeclass .= " radio";
        $doDualScaleFunction = "doDualScaleRadio";
        $caption = gT("An array with sub-question on each line, with 2 answers to provide on each line. The answers are contained in the table header. ");
    }
    if (ctype_digit(trim($aQuestionAttributes['repeat_headings'])) && trim($aQuestionAttributes['repeat_headings'] != "")) {
        $repeatheadings = intval($aQuestionAttributes['repeat_headings']);
        $minrepeatheadings = 0;
    }
    if (trim($aQuestionAttributes['dualscale_headerA'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') {
        $leftheader = $aQuestionAttributes['dualscale_headerA'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']];
    } else {
        $leftheader = '';
    }
    if (trim($aQuestionAttributes['dualscale_headerB'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') {
        $rightheader = $aQuestionAttributes['dualscale_headerB'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']];
    } else {
        $rightheader = '';
    }
    if (trim($aQuestionAttributes['answer_width']) != '') {
        $answerwidth = $aQuestionAttributes['answer_width'];
    } else {
        $answerwidth = 20;
    }
    // Find if we have rigth and center text
    // TODO move "|" to attribute
    $sQuery = "SELECT count(question) FROM {{questions}} WHERE parent_qid=" . $ia[0] . " and scale_id=0 AND question like '%|%'";
    $rigthCount = Yii::app()->db->createCommand($sQuery)->queryScalar();
    $rightexists = $rigthCount > 0;
    // $right_exists: flag to find out if there are any right hand answer parts. leaving right column but don't force with
    $sQuery = "SELECT count(question) FROM {{questions}} WHERE parent_qid=" . $ia[0] . " and scale_id=0 AND question like '%|%|%'";
    $centerCount = Yii::app()->db->createCommand($sQuery)->queryScalar();
    $centerexists = $centerCount > 0;
    // $center_exists: flag to find out if there are any center hand answer parts. leaving center column but don't force with
    // Label and code for input
    foreach ($aAnswersScale0 as $lrow) {
        $labels0[] = array('code' => $lrow['code'], 'title' => $lrow['answer']);
    }
    foreach ($aAnswersScale1 as $lrow) {
        $labels1[] = array('code' => $lrow['code'], 'title' => $lrow['answer']);
    }
    if (count($aAnswersScale0) > 0 && $anscount) {
        $answer = "";
        $fn = 1;
        // Used by repeat_heading
        if ($useDropdownLayout === false) {
            $columnswidth = 100 - $answerwidth;
            foreach ($aAnswersScale0 as $lrow) {
                $labelans0[] = $lrow['answer'];
                $labelcode0[] = $lrow['code'];
            }
            foreach ($aAnswersScale1 as $lrow) {
                $labelans1[] = $lrow['answer'];
                $labelcode1[] = $lrow['code'];
            }
            $numrows = count($labelans0) + count($labelans1);
            // Add needed row and fill some boolean: shownoanswer, rightexists, centerexists
            $shownoanswer = $ia[6] != "Y" && SHOW_NO_ANSWER == 1;
            if ($shownoanswer) {
                $numrows++;
                $caption .= gT("The last cell are for no answer. ");
            }
            if ($rightexists) {
                $numrows++;
            }
            if ($centerexists) {
                $numrows++;
            }
            $cellwidth = $columnswidth / $numrows;
            //$cellwidth=sprintf("%02d", $cellwidth); // No reason to do this, except to leave place for separator ?  But then table can not be the same in all browser
            // Header row and colgroups
            $mycolumns = "\t<col class=\"col-answers\" width=\"{$answerwidth}%\" />\n";
            $answer_head_line = "\t<th class=\"header_answer_text\">&nbsp;</th>\n\n";
            $mycolumns .= "\t<colgroup class=\"col-responses group-1\">\n";
            $odd_even = '';
            foreach ($labelans0 as $ld) {
                $answer_head_line .= "\t<th>" . $ld . "</th>\n";
                $odd_even = alternation($odd_even);
                $mycolumns .= "<col class=\"{$odd_even}\" width=\"{$cellwidth}%\" />\n";
            }
            $mycolumns .= "\t</colgroup>\n";
            if (count($labelans1) > 0) {
                $separatorwidth = $centerexists ? "width=\"{$cellwidth}%\" " : "";
                $mycolumns .= "\t<col class=\"separator\" {$separatorwidth}/>\n";
                $mycolumns .= "\t<colgroup class=\"col-responses group-2\">\n";
                $answer_head_line .= "\n\t<td class=\"header_separator\">&nbsp;</td>\n\n";
                // Separator : and No answer for accessibility for first colgroup
                foreach ($labelans1 as $ld) {
                    $answer_head_line .= "\t<th>" . $ld . "</th>\n";
                    $odd_even = alternation($odd_even);
                    $mycolumns .= "<col class=\"{$odd_even}\" width=\"{$cellwidth}%\" />\n";
                }
                $mycolumns .= "\t</colgroup>\n";
            }
            if ($shownoanswer || $rightexists) {
                $rigthwidth = $rightexists ? "width=\"{$cellwidth}%\" " : "";
                $mycolumns .= "\t<col class=\"separator rigth_separator\" {$rigthwidth}/>\n";
                $answer_head_line .= "\n\t<td class=\"header_separator rigth_separator\">&nbsp;</td>\n";
            }
            if ($shownoanswer) {
                $mycolumns .= "\t<col class=\"col-no-answer\"  width=\"{$cellwidth}%\" />\n";
                $answer_head_line .= "\n\t<th class=\"header_no_answer\">" . gT('No answer') . "</th>\n";
            }
            $answer_head2 = "\n<tr class=\"array1 header_row dontread\">\n" . $answer_head_line . "</tr>\n";
            // build first row of header if needed
            if ($leftheader != '' || $rightheader != '') {
                $answer_head1 = "<tr class=\"array1 groups header_row\">\n" . "\t<th class=\"header_answer_text\">&nbsp;</th>\n" . "\t<th colspan=\"" . count($labelans0) . "\" class=\"dsheader\">{$leftheader}</th>\n";
                if (count($labelans1) > 0) {
                    $answer_head1 .= "\t<td class=\"header_separator\">&nbsp;</td>\n" . "\t<th colspan=\"" . count($labelans1) . "\" class=\"dsheader\">{$rightheader}</th>\n";
                }
                if ($shownoanswer || $rightexists) {
                    $rigthclass = $rightexists ? " header_answer_text_right" : "";
                    $answer_head1 .= "\t<td class=\"header_separator {$rigthclass}\">&nbsp;</td>\n";
                    if ($shownoanswer) {
                        $answer_head1 .= "\t<th class=\"header_no_answer\">&nbsp;</th>\n";
                    }
                }
                $answer_head1 .= "</tr>\n";
            } else {
                $answer_head1 = "";
            }
            $answer .= "\n<table class=\"question subquestions-list questions-list\" summary=\"{$caption}\">\n" . $mycolumns . "\n\t<thead>\n" . $answer_head1 . $answer_head2 . "\n\t</thead>\n" . "<tbody>\n";
            // And no each line of body
            $trbc = '';
            foreach ($aSubQuestions as $ansrow) {
                // Build repeat headings if needed
                if (isset($repeatheadings) && $repeatheadings > 0 && $fn - 1 > 0 && ($fn - 1) % $repeatheadings == 0) {
                    if ($anscount - $fn + 1 >= $minrepeatheadings) {
                        $answer .= "</tbody>\n<tbody>";
                        // Close actual body and open another one
                        //$answer .= $answer_head1;
                        $answer .= "\n<tr class=\"repeat headings\">\n" . $answer_head_line . "</tr>\n";
                    }
                }
                $trbc = alternation($trbc, 'row');
                $answertext = $ansrow['question'];
                // rigth and center answertext: not explode for ? Why not
                if (strpos($answertext, '|')) {
                    $answertextrigth = substr($answertext, strpos($answertext, '|') + 1);
                    $answertext = substr($answertext, 0, strpos($answertext, '|'));
                } else {
                    $answertextrigth = "";
                }
                if ($centerexists) {
                    $answertextcenter = substr($answertextrigth, 0, strpos($answertextrigth, '|'));
                    $answertextrigth = substr($answertextrigth, strpos($answertextrigth, '|') + 1);
                } else {
                    $answertextcenter = "";
                }
                $myfname = $ia[1] . $ansrow['title'];
                $myfname0 = $ia[1] . $ansrow['title'] . '#0';
                $myfid0 = $ia[1] . $ansrow['title'] . '_0';
                $myfname1 = $ia[1] . $ansrow['title'] . '#1';
                // new multi-scale-answer
                $myfid1 = $ia[1] . $ansrow['title'] . '_1';
                /* Check the Sub Q mandatory violation */
                if ($ia[6] == 'Y' && (in_array($myfname0, $aMandatoryViolationSubQ) || in_array($myfname1, $aMandatoryViolationSubQ))) {
                    $answertext = "<span class='errormandatory'>{$answertext}</span>";
                }
                // Get array_filter stuff
                list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname, $trbc, $myfname, "tr", "{$trbc} answers-list radio-list");
                $answer .= $htmltbody2;
                array_push($inputnames, $myfname0);
                $answer .= "\t<th class=\"answertext\">\n" . $hiddenfield . "{$answertext}\n";
                // Hidden answers used by EM: sure can be added in javascript
                $answer .= "<input type=\"hidden\" disabled=\"disabled\" name=\"java{$myfid0}\" id=\"java{$myfid0}\" value=\"";
                if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0])) {
                    $answer .= $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0];
                }
                $answer .= "\" />\n";
                if (count($labelans1) > 0) {
                    $answer .= "<input type=\"hidden\" disabled=\"disabled\" name=\"java{$myfid1}\" id=\"java{$myfid1}\" value=\"";
                    if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1])) {
                        $answer .= $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1];
                    }
                    $answer .= "\" />\n";
                }
                $answer .= "\t</th>\n";
                $hiddenanswers = '';
                $thiskey = 0;
                foreach ($labelcode0 as $ld) {
                    $answer .= "\t<td class=\"answer_cell_1_00{$ld} answer-item {$answertypeclass}-item\">\n" . "\t<input class=\"radio\" type=\"radio\" name=\"{$myfname0}\" value=\"{$ld}\" id=\"answer{$myfid0}-{$ld}\" ";
                    if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0] == $ld) {
                        $answer .= CHECKED;
                    }
                    $answer .= "  />\n" . "<label class=\"hide read\" for=\"answer{$myfid0}-{$ld}\">{$labelans0[$thiskey]}</label>\n" . "\n\t</td>\n";
                    $thiskey++;
                }
                if (count($labelans1) > 0) {
                    $answer .= "\t<td class=\"dual_scale_separator information-item\">";
                    if ($shownoanswer) {
                        $answer .= "\t<input class='radio jshide read' type='radio' name='{$myfname0}' value='' id='answer{$myfid0}-' ";
                        if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0] == "") {
                            $answer .= CHECKED;
                        }
                        $answer .= " />\n";
                    }
                    $answer .= "<label for='answer{$myfid0}-' class= \"hide read\">" . gT("No answer") . "</label>";
                    $answer .= "\t{$answertextcenter}</td>\n";
                    // separator
                    array_push($inputnames, $myfname1);
                    $thiskey = 0;
                    foreach ($labelcode1 as $ld) {
                        $answer .= "\t<td class=\"answer_cell_2_00{$ld}  answer-item radio-item\">\n" . "\t<input class=\"radio\" type=\"radio\" name=\"{$myfname1}\" value=\"{$ld}\" id=\"answer{$myfid1}-{$ld}\" ";
                        if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1] == $ld) {
                            $answer .= CHECKED;
                        }
                        $answer .= " />\n" . "<label class=\"hide read\" for=\"answer{$myfid1}-{$ld}\">{$labelans1[$thiskey]}</label>\n" . "\t</td>\n";
                        $thiskey++;
                    }
                }
                if ($shownoanswer || $rightexists) {
                    $answer .= "\t<td class=\"answertextright dual_scale_separator information-item\">{$answertextrigth}</td>\n";
                }
                if ($shownoanswer) {
                    $answer .= "\t<td class=\"dual_scale_no_answer answer-item radio-item noanswer-item\">\n";
                    if (count($labelans1) > 0) {
                        $answer .= "\t<input class='radio' type='radio' name='{$myfname1}' value='' id='answer{$myfid1}-' ";
                        if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1] == "") {
                            $answer .= CHECKED;
                        }
                        // --> START NEW FEATURE - SAVE
                        $answer .= " />\n";
                        $answer .= "<label class='hide read' for='answer{$myfid1}-'>" . gT("No answer") . "</label>";
                    } else {
                        $answer .= "\t<input class='radio' type='radio' name='{$myfname0}' value='' id='answer{$myfid0}-' ";
                        if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0] == "") {
                            $answer .= CHECKED;
                        }
                        $answer .= "<label class='hide read' for='answer{$myfid0}-'>" . gT("No answer") . "<label>\n";
                        $answer .= " />\n";
                    }
                    $answer .= "\t</td>\n";
                }
                $answer .= "</tr>\n";
                $fn++;
            }
            $answer .= "</tbody>\n";
            $answer .= "</table>";
        } elseif ($useDropdownLayout === true) {
            $separatorwidth = (100 - $answerwidth) / 10;
            $cellwidth = (100 - $answerwidth - $separatorwidth) / 2;
            $answer = "";
            // Get attributes for Headers and Prefix/Suffix
            if (trim($aQuestionAttributes['dropdown_prepostfix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') {
                list($ddprefix, $ddsuffix) = explode("|", $aQuestionAttributes['dropdown_prepostfix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]);
                $ddprefix = $ddprefix;
                $ddsuffix = $ddsuffix;
            } else {
                $ddprefix = '';
                $ddsuffix = '';
            }
            if (trim($aQuestionAttributes['dropdown_separators']) != '') {
                $aSeparator = explode('|', $aQuestionAttributes['dropdown_separators']);
                if (isset($aSeparator[1])) {
                    $interddSep = $aSeparator[1];
                } else {
                    $interddSep = $aSeparator[0];
                }
            } else {
                $interddSep = '';
            }
            $colspan_1 = '';
            $colspan_2 = '';
            $suffix_cell = '';
            $answer .= "\n<table class=\"question subquestion-list questions-list dropdown-list\" summary=\"{$caption}\">\n" . "\t<col class=\"answertext\" width=\"{$answerwidth}%\" />\n";
            if ($ddprefix != '' || $ddsuffix != '') {
                $answer .= "\t<colgroup width=\"{$cellwidth}%\">\n";
            }
            if ($ddprefix != '') {
                $answer .= "\t\t<col class=\"ddprefix\" />\n";
                $colspan_1 = ' colspan="2"';
            }
            $headcolwidth = $ddprefix != '' || $ddsuffix != '' ? "" : " width=\"{$cellwidth}%\"";
            $answer .= "\t<col class=\"dsheader\"{$headcolwidth} />\n";
            if ($ddsuffix != '') {
                $answer .= "\t<col class=\"ddsuffix\" />\n";
            }
            if ($ddprefix != '' || $ddsuffix != '') {
                $answer .= "\t</colgroup>\n";
            }
            $answer .= "\t<col class=\"ddarrayseparator\" width=\"{$separatorwidth}%\" />\n";
            if ($ddprefix != '' || $ddsuffix != '') {
                $answer .= "\t<colgroup width=\"{$cellwidth}%\">\n";
            }
            if ($ddprefix != '') {
                $answer .= "\t\t<col class=\"ddprefix\" />\n";
            }
            $answer .= "\t<col class=\"dsheader\"{$headcolwidth} />\n";
            if ($ddsuffix != '') {
                $answer .= "\t<col class=\"ddsuffix\" />\n";
            }
            if ($ddprefix != '' || $ddsuffix != '') {
                $answer .= "\t</colgroup>\n";
            }
            // colspan : for header only
            if ($ddprefix != '' && $ddsuffix != '') {
                $colspan = ' colspan="3"';
            } elseif ($ddprefix != '' || $ddsuffix != '') {
                $colspan = ' colspan="2"';
            } else {
                $colspan = "";
            }
            // headers
            $answer .= "\n\t<thead>\n" . "<tr>\n" . "\t<td>&nbsp;</td>\n" . "\t<th{$colspan}>{$leftheader}</th>\n" . "\t<td>&nbsp;</td>\n" . "\t<th{$colspan}>{$rightheader}</th>\n";
            $answer .= "\t</tr>\n" . "\t</thead>\n";
            $answer .= "\n<tbody>\n";
            $trbc = '';
            foreach ($aSubQuestions as $ansrow) {
                $myfname = $ia[1] . $ansrow['title'];
                $myfname0 = $ia[1] . $ansrow['title'] . "#0";
                $myfid0 = $ia[1] . $ansrow['title'] . "_0";
                $myfname1 = $ia[1] . $ansrow['title'] . "#1";
                $myfid1 = $ia[1] . $ansrow['title'] . "_1";
                $sActualAnswer0 = isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0]) ? $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0] : "";
                $sActualAnswer1 = isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1]) ? $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1] : "";
                if ($ia[6] == 'Y' && (in_array($myfname0, $aMandatoryViolationSubQ) || in_array($myfname1, $aMandatoryViolationSubQ))) {
                    $answertext = "<span class='errormandatory'>" . $ansrow['question'] . "</span>";
                } else {
                    $answertext = $ansrow['question'];
                }
                list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname, $trbc, $myfname, "tr", "{$trbc} subquestion-list questions-list dropdown-list");
                $answer .= $htmltbody2;
                $answer .= "\t<th class=\"answertext\">\n" . "<label for=\"answer{$myfid0}\">{$answertext}</label>\n";
                // Hidden answers used by EM: sure can be added in javascript
                $answer .= "<input type=\"hidden\" disabled=\"disabled\" name=\"java{$myfid0}\" id=\"java{$myfid0}\" value=\"{$sActualAnswer0}\" />\n";
                $answer .= "<input type=\"hidden\" disabled=\"disabled\" name=\"java{$myfid1}\" id=\"java{$myfid1}\" value=\"{$sActualAnswer1}\" />\n";
                $answer . "\t</th>\n";
                // Selector 0
                if ($ddprefix != '') {
                    $answer .= "\t<td class=\"ddprefix information-item\">{$ddprefix}</td>\n";
                }
                $answer .= "\t<td class=\"answer-item dropdown-item\">\n" . "<select name=\"{$myfname0}\" id=\"answer{$myfid0}\">\n";
                // Show the 'Please choose' if there are no answer actually
                if ($sActualAnswer0 == '') {
                    $answer .= "\t<option value=\"\" " . SELECTED . ">" . gT('Please choose...') . "</option>\n";
                }
                foreach ($labels0 as $lrow) {
                    $answer .= "\t<option value=\"" . $lrow['code'] . '" ';
                    if ($sActualAnswer0 == $lrow['code']) {
                        $answer .= SELECTED;
                    }
                    $answer .= '>' . flattenText($lrow['title']) . "</option>\n";
                }
                if ($sActualAnswer0 != '' && $ia[6] != 'Y' && SHOW_NO_ANSWER) {
                    $answer .= "\t<option value=\"\">" . gT('No answer') . "</option>\n";
                }
                $answer .= "</select>\n";
                $answer .= "</td>\n";
                if ($ddsuffix != '') {
                    $answer .= "\t<td class=\"ddsuffix information-item\">{$ddsuffix}</td>\n";
                }
                $inputnames[] = $myfname0;
                $answer .= "\t<td class=\"ddarrayseparator information-item\">{$interddSep}</td>\n";
                //Separator
                // Selector 1
                if ($ddprefix != '') {
                    $answer .= "\t<td class='ddprefix information-item'>{$ddprefix}</td>\n";
                }
                $answer .= "\t<td class=\"answer-item dropdown-item\">\n" . "<label class=\"hide read\" for=\"answer{$myfid1}\">{$answertext}</label>" . "<select name=\"{$myfname1}\" id=\"answer{$myfid1}\">\n";
                // Show the 'Please choose' if there are no answer actually
                if ($sActualAnswer1 == '') {
                    $answer .= "\t<option value=\"\" " . SELECTED . ">" . gT('Please choose...') . "</option>\n";
                }
                foreach ($labels1 as $lrow1) {
                    $answer .= "\t<option value=\"" . $lrow1['code'] . '" ';
                    if ($sActualAnswer1 == $lrow1['code']) {
                        $answer .= SELECTED;
                    }
                    $answer .= '>' . flattenText($lrow1['title']) . "</option>\n";
                }
                if ($sActualAnswer1 != '' && $ia[6] != 'Y' && SHOW_NO_ANSWER) {
                    $answer .= "\t<option value=\"\">" . gT('No answer') . "</option>\n";
                }
                $answer .= "</select>\n";
                $answer .= "</td>\n";
                if ($ddsuffix != '') {
                    $answer .= "\t<td class=\"ddsuffix information-item\">{$ddsuffix}</td>\n";
                }
                $inputnames[] = $myfname1;
                $answer .= "</tr>\n";
            }
            $answer .= "\t</tbody>\n";
            $answer .= "</table>\n";
        }
    } else {
        $answer = "<p class='error'>" . gT("Error: There are no answer options for this question and/or they don't exist in this language.") . "</p>\n";
        $inputnames = "";
    }
    Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "dualscale.js");
    $answer .= "<script type='text/javascript'>\n" . "  <!--\n" . " {$doDualScaleFunction}({$ia[0]});\n" . " -->\n" . "</script>\n";
    return array($answer, $inputnames);
}
 /**
  * Evaluates an expression via Expression Manager
  * Uses the current context.
  * @param string $expression
  * @return string
  */
 public function EMevaluateExpression($expression)
 {
     $result = LimeExpressionManager::ProcessString($expression);
     return $result;
 }
Beispiel #25
0
 /**
  * Generate an TSV (tab-separated value) file for the survey structure
  * @param type $surveyid
  */
 private function _exporttsv($surveyid)
 {
     $fn = "limesurvey_survey_{$surveyid}.txt";
     header("Content-Type: text/tab-separated-values charset=UTF-8");
     header("Content-Disposition: attachment; filename={$fn}");
     header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
     // Date in the past
     header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
     header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
     header("Pragma: public");
     // HTTP/1.0
     $data =& LimeExpressionManager::TSVSurveyExport($surveyid);
     $lines = array();
     foreach ($data as $row) {
         $lines[] = implode("\t", str_replace(array("\t", "\n", "\r"), array(" ", " ", " "), $row));
     }
     $output = implode("\n", $lines);
     //        echo "\xEF\xBB\xBF"; // UTF-8 BOM
     echo $output;
     return;
 }
 /**
  * RPC Routine to delete a question of a survey .
  * Returns the id of the deleted question.
  *
  * @access public
  * @param string $sSessionKey Auth credentials
  * @param int iQuestionID Id of the question to delete
  * @return array|int Id of the deleted Question or status
  */
 public function delete_question($sSessionKey, $iQuestionID)
 {
     if ($this->_checkSessionKey($sSessionKey)) {
         $oQuestion = Question::model()->findByAttributes(array('qid' => $iQuestionID));
         if (!isset($oQuestion)) {
             return array('status' => 'Error: Invalid question ID');
         }
         $iSurveyID = $oQuestion['sid'];
         if (Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'delete')) {
             $oSurvey = Survey::model()->findByPk($iSurveyID);
             if ($oSurvey['active'] == 'Y') {
                 return array('status' => 'Survey is active and not editable');
             }
             $iGroupID = $oQuestion['gid'];
             $oCondition = Condition::model()->findAllByAttributes(array('cqid' => $iQuestionID));
             if (count($oCondition) > 0) {
                 return array('status' => 'Cannot delete Question. Others rely on this question');
             }
             LimeExpressionManager::RevertUpgradeConditionsToRelevance(NULL, $iQuestionID);
             try {
                 Condition::model()->deleteAllByAttributes(array('qid' => $iQuestionID));
                 QuestionAttribute::model()->deleteAllByAttributes(array('qid' => $iQuestionID));
                 Answer::model()->deleteAllByAttributes(array('qid' => $iQuestionID));
                 $sCriteria = new CDbCriteria();
                 $sCriteria->addCondition('qid = :qid or parent_qid = :qid');
                 $sCriteria->params[':qid'] = $iQuestionID;
                 Question::model()->deleteAll($sCriteria);
                 DefaultValue::model()->deleteAllByAttributes(array('qid' => $iQuestionID));
                 QuotaMember::model()->deleteAllByAttributes(array('qid' => $iQuestionID));
                 Question::updateSortOrder($iGroupID, $iSurveyID);
                 return (int) $iQuestionID;
             } catch (Exception $e) {
                 return array('status' => 'Error');
             }
         } else {
             return array('status' => 'No permission');
         }
     } else {
         return array('status' => 'Invalid session key');
     }
 }
Beispiel #27
0
/**
* This function imports a LimeSurvey .lss survey XML file
*
* @param mixed $sFullFilepath  The full filepath of the uploaded file
*/
function XMLImportSurvey($sFullFilepath, $sXMLdata = NULL, $sNewSurveyName = NULL, $iDesiredSurveyId = NULL, $bTranslateInsertansTags = true)
{
    Yii::app()->loadHelper('database');
    $clang = Yii::app()->lang;
    $aGIDReplacements = array();
    if ($sXMLdata == NULL) {
        $xml = simplexml_load_file($sFullFilepath);
    } else {
        $xml = simplexml_load_string($sXMLdata);
    }
    if ($xml->LimeSurveyDocType != 'Survey') {
        $results['error'] = $clang->gT("This is not a valid LimeSurvey survey structure XML file.");
        return $results;
    }
    $iDBVersion = (int) $xml->DBVersion;
    $aQIDReplacements = array();
    $aQuotaReplacements = array();
    $results['defaultvalues'] = 0;
    $results['answers'] = 0;
    $results['surveys'] = 0;
    $results['questions'] = 0;
    $results['subquestions'] = 0;
    $results['question_attributes'] = 0;
    $results['groups'] = 0;
    $results['assessments'] = 0;
    $results['quota'] = 0;
    $results['quotals'] = 0;
    $results['quotamembers'] = 0;
    $results['survey_url_parameters'] = 0;
    $results['importwarnings'] = array();
    $aLanguagesSupported = array();
    foreach ($xml->languages->language as $language) {
        $aLanguagesSupported[] = (string) $language;
    }
    $results['languages'] = count($aLanguagesSupported);
    // Import surveys table ====================================================
    foreach ($xml->surveys->rows->row as $row) {
        $insertdata = array();
        foreach ($row as $key => $value) {
            $insertdata[(string) $key] = (string) $value;
        }
        $iOldSID = $results['oldsid'] = $insertdata['sid'];
        if ($iDesiredSurveyId != NULL) {
            $insertdata['wishSID'] = GetNewSurveyID($iDesiredSurveyId);
        }
        if ($iDBVersion <= 143) {
            if (isset($insertdata['private'])) {
                $insertdata['anonymized'] = $insertdata['private'];
            }
            unset($insertdata['private']);
            unset($insertdata['notification']);
        }
        unset($insertdata['expires']);
        unset($insertdata['startdate']);
        //Make sure it is not set active
        $insertdata['active'] = 'N';
        //Set current user to be the owner
        $insertdata['owner_id'] = Yii::app()->session['loginID'];
        if (isset($insertdata['bouncetime']) && $insertdata['bouncetime'] == '') {
            $insertdata['bouncetime'] = NULL;
        }
        if (isset($insertdata['showXquestions'])) {
            $insertdata['showxquestions'] = $insertdata['showXquestions'];
            unset($insertdata['showXquestions']);
        }
        $iNewSID = $results['newsid'] = Survey::model()->insertNewSurvey($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [1]<br />");
        $results['surveys']++;
    }
    // Import survey languagesettings table ===================================================================================
    foreach ($xml->surveys_languagesettings->rows->row as $row) {
        $insertdata = array();
        foreach ($row as $key => $value) {
            $insertdata[(string) $key] = (string) $value;
        }
        if (!in_array($insertdata['surveyls_language'], $aLanguagesSupported)) {
            continue;
        }
        $insertdata['surveyls_survey_id'] = $iNewSID;
        if ($bTranslateInsertansTags) {
            if ($sNewSurveyName == NULL) {
                $insertdata['surveyls_title'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_title']);
            } else {
                $insertdata['surveyls_title'] = translateLinks('survey', $iOldSID, $iNewSID, $sNewSurveyName);
            }
            if (isset($insertdata['surveyls_description'])) {
                $insertdata['surveyls_description'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_description']);
            }
            if (isset($insertdata['surveyls_welcometext'])) {
                $insertdata['surveyls_welcometext'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_welcometext']);
            }
            if (isset($insertdata['surveyls_urldescription'])) {
                $insertdata['surveyls_urldescription'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_urldescription']);
            }
            if (isset($insertdata['surveyls_email_invite'])) {
                $insertdata['surveyls_email_invite'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_invite']);
            }
            if (isset($insertdata['surveyls_email_remind'])) {
                $insertdata['surveyls_email_remind'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_remind']);
            }
            if (isset($insertdata['surveyls_email_register'])) {
                $insertdata['surveyls_email_register'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_register']);
            }
            if (isset($insertdata['surveyls_email_confirm'])) {
                $insertdata['surveyls_email_confirm'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_confirm']);
            }
        }
        $result = Surveys_languagesettings::model()->insertNewSurvey($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [2]<br />");
    }
    // Import groups table ===================================================================================
    if (isset($xml->groups->rows->row)) {
        foreach ($xml->groups->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!in_array($insertdata['language'], $aLanguagesSupported)) {
                continue;
            }
            $iOldSID = $insertdata['sid'];
            $insertdata['sid'] = $iNewSID;
            $oldgid = $insertdata['gid'];
            unset($insertdata['gid']);
            // save the old qid
            // now translate any links
            if ($bTranslateInsertansTags) {
                $insertdata['group_name'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['group_name']);
                $insertdata['description'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['description']);
            }
            // Insert the new group
            if (isset($aGIDReplacements[$oldgid])) {
                switchMSSQLIdentityInsert('groups', true);
                $insertdata['gid'] = $aGIDReplacements[$oldgid];
            }
            $newgid = Groups::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [3]<br />");
            $results['groups']++;
            if (!isset($aGIDReplacements[$oldgid])) {
                $aGIDReplacements[$oldgid] = $newgid;
                // add old and new qid to the mapping array
            } else {
                switchMSSQLIdentityInsert('groups', false);
            }
        }
    }
    // Import questions table ===================================================================================
    // We have to run the question table data two times - first to find all main questions
    // then for subquestions (because we need to determine the new qids for the main questions first)
    if (isset($xml->questions)) {
        foreach ($xml->questions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!in_array($insertdata['language'], $aLanguagesSupported) || $insertdata['gid'] == 0) {
                continue;
            }
            $iOldSID = $insertdata['sid'];
            $insertdata['sid'] = $iNewSID;
            $insertdata['gid'] = $aGIDReplacements[$insertdata['gid']];
            $oldqid = $insertdata['qid'];
            unset($insertdata['qid']);
            // save the old qid
            // now translate any links
            if ($bTranslateInsertansTags) {
                $insertdata['question'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['question']);
                $insertdata['help'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['help']);
            }
            // Insert the new question
            if (isset($aQIDReplacements[$oldqid])) {
                $insertdata['qid'] = $aQIDReplacements[$oldqid];
                switchMSSQLIdentityInsert('questions', true);
            }
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            $newqid = Questions::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [4]<br />");
            if (!isset($aQIDReplacements[$oldqid])) {
                $aQIDReplacements[$oldqid] = $newqid;
                $results['questions']++;
            } else {
                switchMSSQLIdentityInsert('questions', false);
            }
        }
    }
    // Import subquestions -------------------------------------------------------
    if (isset($xml->subquestions)) {
        foreach ($xml->subquestions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!in_array($insertdata['language'], $aLanguagesSupported) || $insertdata['gid'] == 0) {
                continue;
            }
            if (!isset($insertdata['mandatory']) || trim($insertdata['mandatory']) == '') {
                $insertdata['mandatory'] = 'N';
            }
            $insertdata['sid'] = $iNewSID;
            $insertdata['gid'] = $aGIDReplacements[(int) $insertdata['gid']];
            $oldsqid = (int) $insertdata['qid'];
            unset($insertdata['qid']);
            // save the old qid
            $insertdata['parent_qid'] = $aQIDReplacements[(int) $insertdata['parent_qid']];
            // remap the parent_qid
            // now translate any links
            if ($bTranslateInsertansTags) {
                $insertdata['question'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['question']);
                if (isset($insertdata['help'])) {
                    $insertdata['help'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['help']);
                }
            }
            if (isset($aQIDReplacements[$oldsqid])) {
                $insertdata['qid'] = $aQIDReplacements[$oldsqid];
                switchMSSQLIdentityInsert('questions', true);
            }
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            $newsqid = Questions::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [5]<br />");
            if (!isset($insertdata['qid'])) {
                $aQIDReplacements[$oldsqid] = $newsqid;
                // add old and new qid to the mapping array
            } else {
                switchMSSQLIdentityInsert('questions', false);
            }
            $results['subquestions']++;
        }
    }
    // Import answers ------------------------------------------------------------
    if (isset($xml->answers)) {
        foreach ($xml->answers->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!in_array($insertdata['language'], $aLanguagesSupported) || !isset($aQIDReplacements[(int) $insertdata['qid']])) {
                continue;
            }
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the parent_qid
            // now translate any links
            if ($bTranslateInsertansTags) {
                $insertdata['answer'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['answer']);
            }
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            $result = Answers::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['answers']++;
        }
    }
    // Import questionattributes -------------------------------------------------
    if (isset($xml->question_attributes)) {
        $aAllAttributes = questionAttributes(true);
        foreach ($xml->question_attributes->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            unset($insertdata['qaid']);
            if (!isset($aQIDReplacements[(int) $insertdata['qid']])) {
                continue;
            }
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            if ($iDBVersion < 148 && isset($aAllAttributes[$insertdata['attribute']]['i18n']) && $aAllAttributes[$insertdata['attribute']]['i18n']) {
                foreach ($aLanguagesSupported as $sLanguage) {
                    $insertdata['language'] = $sLanguage;
                    if ($insertdata) {
                        XSSFilterArray($insertdata);
                    }
                    $result = Question_attributes::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
                }
            } else {
                $result = Question_attributes::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            }
            $results['question_attributes']++;
        }
    }
    // Import defaultvalues ------------------------------------------------------
    if (isset($xml->defaultvalues)) {
        $results['defaultvalues'] = 0;
        foreach ($xml->defaultvalues->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            if (isset($aQIDReplacements[(int) $insertdata['sqid']])) {
                $insertdata['sqid'] = $aQIDReplacements[(int) $insertdata['sqid']];
            }
            // remap the subquestion id
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            // now translate any links
            $result = Defaultvalues::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['defaultvalues']++;
        }
    }
    $aOldNewFieldmap = reverseTranslateFieldNames($iOldSID, $iNewSID, $aGIDReplacements, $aQIDReplacements);
    // Import conditions ---------------------------------------------------------
    if (isset($xml->conditions)) {
        $results['conditions'] = 0;
        foreach ($xml->conditions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this condition is orphan -> error, skip this record)
            if (isset($aQIDReplacements[$insertdata['qid']])) {
                $insertdata['qid'] = $aQIDReplacements[$insertdata['qid']];
                // remap the qid
            } else {
                continue;
            }
            // a problem with this answer record -> don't consider
            if ($insertdata['cqid'] != 0) {
                if (isset($aQIDReplacements[$insertdata['cqid']])) {
                    $oldcqid = $insertdata['cqid'];
                    //Save for cfield transformation
                    $insertdata['cqid'] = $aQIDReplacements[$insertdata['cqid']];
                    // remap the qid
                } else {
                    continue;
                }
                // a problem with this answer record -> don't consider
                list($oldcsid, $oldcgid, $oldqidanscode) = explode("X", $insertdata["cfieldname"], 3);
                // replace the gid for the new one in the cfieldname(if there is no new gid in the $aGIDReplacements array it means that this condition is orphan -> error, skip this record)
                if (!isset($aGIDReplacements[$oldcgid])) {
                    continue;
                }
            }
            unset($insertdata["cid"]);
            // recreate the cfieldname with the new IDs
            if ($insertdata['cqid'] != 0) {
                if (preg_match("/^\\+/", $oldcsid)) {
                    $newcfieldname = '+' . $iNewSID . "X" . $aGIDReplacements[$oldcgid] . "X" . $insertdata["cqid"] . substr($oldqidanscode, strlen($oldcqid));
                } else {
                    $newcfieldname = $iNewSID . "X" . $aGIDReplacements[$oldcgid] . "X" . $insertdata["cqid"] . substr($oldqidanscode, strlen($oldcqid));
                }
            } else {
                // The cfieldname is a not a previous question cfield but a {XXXX} replacement field
                $newcfieldname = $insertdata["cfieldname"];
            }
            $insertdata["cfieldname"] = $newcfieldname;
            if (trim($insertdata["method"]) == '') {
                $insertdata["method"] = '==';
            }
            // Now process the value and replace @sgqa@ codes
            if (preg_match("/^@(.*)@\$/", $insertdata["value"], $cfieldnameInCondValue)) {
                if (isset($aOldNewFieldmap[$cfieldnameInCondValue[1]])) {
                    $newvalue = '@' . $aOldNewFieldmap[$cfieldnameInCondValue[1]] . '@';
                    $insertdata["value"] = $newvalue;
                }
            }
            // now translate any links
            $result = Conditions::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['conditions']++;
        }
    }
    // TMSW Conditions->Relevance:  Call  LEM->ConvertConditionsToRelevance
    // Import assessments --------------------------------------------------------
    if (isset($xml->assessments)) {
        foreach ($xml->assessments->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if ($insertdata['gid'] > 0) {
                $insertdata['gid'] = $aGIDReplacements[(int) $insertdata['gid']];
                // remap the qid
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            // now translate any links
            $result = Assessment::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['assessments']++;
        }
    }
    // Import quota --------------------------------------------------------------
    if (isset($xml->quota)) {
        foreach ($xml->quota->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            $oldid = $insertdata['id'];
            unset($insertdata['id']);
            // now translate any links
            $result = Quota::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $aQuotaReplacements[$oldid] = Yii::app()->db->getCommandBuilder()->getLastInsertID('{{quota}}');
            $results['quota']++;
        }
    }
    // Import quota_members ------------------------------------------------------
    if (isset($xml->quota_members)) {
        foreach ($xml->quota_members->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            $insertdata['quota_id'] = $aQuotaReplacements[(int) $insertdata['quota_id']];
            // remap the qid
            unset($insertdata['id']);
            // now translate any links
            $result = Quota_members::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['quotamembers']++;
        }
    }
    // Import quota_languagesettings----------------------------------------------
    if (isset($xml->quota_languagesettings)) {
        foreach ($xml->quota_languagesettings->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['quotals_quota_id'] = $aQuotaReplacements[(int) $insertdata['quotals_quota_id']];
            // remap the qid
            unset($insertdata['quotals_id']);
            $result = Quota_languagesettings::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['quotals']++;
        }
    }
    // Import survey_url_parameters ----------------------------------------------
    if (isset($xml->survey_url_parameters)) {
        foreach ($xml->survey_url_parameters->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            if (isset($insertdata['targetsqid']) && $insertdata['targetsqid'] != '') {
                $insertdata['targetsqid'] = $aSQIDReplacements[(int) $insertdata['targetsqid']];
                // remap the qid
            }
            if (isset($insertdata['targetqid']) && $insertdata['targetqid'] != '') {
                $insertdata['targetqid'] = $aQIDReplacements[(int) $insertdata['targetqid']];
                // remap the qid
            }
            unset($insertdata['id']);
            $result = Survey_url_parameters::model()->insertRecord($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['survey_url_parameters']++;
        }
    }
    // Set survey rights
    Survey_permissions::model()->giveAllSurveyPermissions(Yii::app()->session['loginID'], $iNewSID);
    $aOldNewFieldmap = reverseTranslateFieldNames($iOldSID, $iNewSID, $aGIDReplacements, $aQIDReplacements);
    $results['FieldReMap'] = $aOldNewFieldmap;
    LimeExpressionManager::SetSurveyId($iNewSID);
    translateInsertansTags($iNewSID, $iOldSID, $aOldNewFieldmap);
    LimeExpressionManager::RevertUpgradeConditionsToRelevance($iNewSID);
    LimeExpressionManager::UpgradeConditionsToRelevance($iNewSID);
    return $results;
}
Beispiel #28
0
 private function _reorderGroup($iSurveyID)
 {
     $AOrgData = array();
     parse_str($_POST['orgdata'], $AOrgData);
     $grouporder = 0;
     foreach ($AOrgData['list'] as $ID => $parent) {
         if ($parent == 'root' && $ID[0] == 'g') {
             QuestionGroup::model()->updateAll(array('group_order' => $grouporder), 'gid=:gid', array(':gid' => (int) substr($ID, 1)));
             $grouporder++;
         } elseif ($ID[0] == 'q') {
             if (!isset($questionorder[(int) substr($parent, 1)])) {
                 $questionorder[(int) substr($parent, 1)] = 0;
             }
             Question::model()->updateAll(array('question_order' => $questionorder[(int) substr($parent, 1)], 'gid' => (int) substr($parent, 1)), 'qid=:qid', array(':qid' => (int) substr($ID, 1)));
             Question::model()->updateAll(array('gid' => (int) substr($parent, 1)), 'parent_qid=:parent_qid', array(':parent_qid' => (int) substr($ID, 1)));
             $questionorder[(int) substr($parent, 1)]++;
         }
     }
     LimeExpressionManager::SetDirtyFlag();
     // so refreshes syntax highlighting
     Yii::app()->session['flashmessage'] = gT("The new question group/question order was successfully saved.");
     $this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $iSurveyID));
 }
templatereplace(flattenText($surveyinfo['surveyls_welcometext']));
echo LimeExpressionManager::GetLastPrettyPrintExpression();
?>
        </td>
    </tr>
    <tr>
        <td>
            <strong><?php 
$clang->eT("End message:");
?>
</strong>
        </td>
        <td>
            <?php 
templatereplace(flattenText($surveyinfo['surveyls_endtext']));
echo LimeExpressionManager::GetLastPrettyPrintExpression();
?>
        </td>
    </tr>
    <tr>
        <td>
            <strong><?php 
$clang->eT("Administrator:");
?>
</strong>
        </td>
        <td>
            <?php 
echo flattenText("{$surveyinfo['admin']} ({$surveyinfo['adminemail']})");
?>
        </td>
/**
 * @param integer $iOldDBVersion
 */
function db_upgrade_all($iOldDBVersion)
{
    /// This function does anything necessary to upgrade
    /// older versions to match current functionality
    global $modifyoutput;
    Yii::app()->loadHelper('database');
    $sUserTemplateRootDir = Yii::app()->getConfig('usertemplaterootdir');
    $sStandardTemplateRootDir = Yii::app()->getConfig('standardtemplaterootdir');
    $oDB = Yii::app()->getDb();
    Yii::app()->setConfig('Updating', true);
    $oDB->schemaCachingDuration = 0;
    // Deactivate schema caching
    $oTransaction = $oDB->beginTransaction();
    try {
        if ($iOldDBVersion < 111) {
            // Language upgrades from version 110 to 111 because the language names did change
            $aOldNewLanguages = array('german_informal' => 'german-informal', 'cns' => 'cn-Hans', 'cnt' => 'cn-Hant', 'pt_br' => 'pt-BR', 'gr' => 'el', 'jp' => 'ja', 'si' => 'sl', 'se' => 'sv', 'vn' => 'vi');
            foreach ($aOldNewLanguages as $sOldLanguageCode => $sNewLanguageCode) {
                alterLanguageCode($sOldLanguageCode, $sNewLanguageCode);
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 111), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 112) {
            // New size of the username field (it was previously 20 chars wide)
            $oDB->createCommand()->alterColumn('{{users}}', 'users_name', "string(64) NOT NULL");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 112), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 113) {
            //Fixes the collation for the complete DB, tables and columns
            if (Yii::app()->db->driverName == 'mysql') {
                $sDatabaseName = getDBConnectionStringProperty('dbname');
                fixMySQLCollations();
                modifyDatabase("", "ALTER DATABASE `{$sDatabaseName}` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;");
                echo $modifyoutput;
                flush();
                @ob_flush();
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 113), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 114) {
            $oDB->createCommand()->alterColumn('{{saved_control}}', 'email', "string(320) NOT NULL");
            $oDB->createCommand()->alterColumn('{{surveys}}', 'adminemail', "string(320) NOT NULL");
            $oDB->createCommand()->alterColumn('{{users}}', 'email', "string(320) NOT NULL");
            $oDB->createCommand()->insert('{{settings_global}}', array('stg_name' => 'SessionName', 'stg_value' => randomChars(64, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ!"$%&/()=?`+*~#",;.:abcdefghijklmnopqrstuvwxyz123456789')));
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 114), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 126) {
            addColumn('{{surveys}}', 'printanswers', "string(1) default 'N'");
            addColumn('{{surveys}}', 'listpublic', "string(1) default 'N'");
            upgradeSurveyTables126();
            upgradeTokenTables126();
            // Create quota table
            $oDB->createCommand()->createTable('{{quota}}', array('id' => 'pk', 'sid' => 'integer', 'qlimit' => 'integer', 'name' => 'string', 'action' => 'integer', 'active' => 'integer NOT NULL DEFAULT 1'));
            // Create quota_members table
            $oDB->createCommand()->createTable('{{quota_members}}', array('id' => 'pk', 'sid' => 'integer', 'qid' => 'integer', 'quota_id' => 'integer', 'code' => 'string(5)'));
            $oDB->createCommand()->createIndex('sid', '{{quota_members}}', 'sid,qid,quota_id,code', true);
            // Create templates_rights table
            $oDB->createCommand()->createTable('{{templates_rights}}', array('uid' => 'integer NOT NULL', 'folder' => 'string NOT NULL', 'use' => 'integer', 'PRIMARY KEY (uid, folder)'));
            // Create templates table
            $oDB->createCommand()->createTable('{{templates}}', array('folder' => 'string NOT NULL', 'creator' => 'integer NOT NULL', 'PRIMARY KEY (folder)'));
            // Rename Norwegian language codes
            alterLanguageCode('no', 'nb');
            addColumn('{{surveys}}', 'htmlemail', "string(1) default 'N'");
            addColumn('{{surveys}}', 'tokenanswerspersistence', "string(1) default 'N'");
            addColumn('{{surveys}}', 'usecaptcha', "string(1) default 'N'");
            addColumn('{{surveys}}', 'bounce_email', 'text');
            addColumn('{{users}}', 'htmleditormode', "string(7) default 'default'");
            addColumn('{{users}}', 'superadmin', "integer NOT NULL default '0'");
            addColumn('{{questions}}', 'lid1', "integer NOT NULL default '0'");
            alterColumn('{{conditions}}', 'value', "string", false, '');
            alterColumn('{{labels}}', 'title', "text");
            $oDB->createCommand()->update('{{users}}', array('superadmin' => 1), "create_survey=1 AND create_user=1 AND move_user=1 AND delete_user=1 AND configurator=1");
            $oDB->createCommand()->update('{{conditions}}', array('method' => '=='), "(method is null) or method='' or method='0'");
            dropColumn('{{users}}', 'move_user');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 126), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 127) {
            modifyDatabase("", "create index answers_idx2 on {{answers}} (sortorder)");
            echo $modifyoutput;
            modifyDatabase("", "create index assessments_idx2 on {{assessments}} (sid)");
            echo $modifyoutput;
            modifyDatabase("", "create index assessments_idx3 on {{assessments}} (gid)");
            echo $modifyoutput;
            modifyDatabase("", "create index conditions_idx2 on {{conditions}} (qid)");
            echo $modifyoutput;
            modifyDatabase("", "create index conditions_idx3 on {{conditions}} (cqid)");
            echo $modifyoutput;
            modifyDatabase("", "create index groups_idx2 on {{groups}} (sid)");
            echo $modifyoutput;
            modifyDatabase("", "create index question_attributes_idx2 on {{question_attributes}} (qid)");
            echo $modifyoutput;
            modifyDatabase("", "create index questions_idx2 on {{questions}} (sid)");
            echo $modifyoutput;
            modifyDatabase("", "create index questions_idx3 on {{questions}} (gid)");
            echo $modifyoutput;
            modifyDatabase("", "create index questions_idx4 on {{questions}} (type)");
            echo $modifyoutput;
            modifyDatabase("", "create index quota_idx2 on {{quota}} (sid)");
            echo $modifyoutput;
            modifyDatabase("", "create index saved_control_idx2 on {{saved_control}} (sid)");
            echo $modifyoutput;
            modifyDatabase("", "create index user_in_groups_idx1 on {{user_in_groups}} (ugid, uid)");
            echo $modifyoutput;
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 127), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 128) {
            upgradeTokens128();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 128), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 129) {
            addColumn('{{surveys}}', 'startdate', "datetime");
            addColumn('{{surveys}}', 'usestartdate', "string(1) NOT NULL default 'N'");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 129), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 130) {
            addColumn('{{conditions}}', 'scenario', "integer NOT NULL default '1'");
            $oDB->createCommand()->update('{{conditions}}', array('scenario' => '1'), "(scenario is null) or scenario=0");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 130), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 131) {
            addColumn('{{surveys}}', 'publicstatistics', "string(1) NOT NULL default 'N'");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 131), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 132) {
            addColumn('{{surveys}}', 'publicgraphs', "string(1) NOT NULL default 'N'");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 132), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 133) {
            addColumn('{{users}}', 'one_time_pw', 'binary');
            // Add new assessment setting
            addColumn('{{surveys}}', 'assessments', "string(1) NOT NULL default 'N'");
            // add new assessment value fields to answers & labels
            addColumn('{{answers}}', 'assessment_value', "integer NOT NULL default '0'");
            addColumn('{{labels}}', 'assessment_value', "integer NOT NULL default '0'");
            // copy any valid codes from code field to assessment field
            switch (Yii::app()->db->driverName) {
                case 'mysql':
                case 'mysqli':
                    $oDB->createCommand("UPDATE {{answers}} SET assessment_value=CAST(`code` as SIGNED) where `code` REGEXP '^-?[0-9]+\$'")->execute();
                    $oDB->createCommand("UPDATE {{labels}} SET assessment_value=CAST(`code` as SIGNED) where `code` REGEXP '^-?[0-9]+\$'")->execute();
                    // copy assessment link to message since from now on we will have HTML assignment messages
                    $oDB->createCommand("UPDATE {{assessments}} set message=concat(replace(message,'/''',''''),'<br /><a href=\"',link,'\">',link,'</a>')")->execute();
                    break;
                case 'sqlsrv':
                case 'dblib':
                case 'mssql':
                    try {
                        $oDB->createCommand("UPDATE {{answers}} SET assessment_value=CAST([code] as int) WHERE ISNUMERIC([code])=1")->execute();
                        $oDB->createCommand("UPDATE {{labels}} SET assessment_value=CAST([code] as int) WHERE ISNUMERIC([code])=1")->execute();
                    } catch (Exception $e) {
                    }
                    // copy assessment link to message since from now on we will have HTML assignment messages
                    alterColumn('{{assessments}}', 'link', "text", false);
                    alterColumn('{{assessments}}', 'message', "text", false);
                    $oDB->createCommand("UPDATE {{assessments}} set message=replace(message,'/''','''')+'<br /><a href=\"'+link+'\">'+link+'</a>'")->execute();
                    break;
                case 'pgsql':
                    $oDB->createCommand("UPDATE {{answers}} SET assessment_value=CAST(code as integer) where code ~ '^[0-9]+'")->execute();
                    $oDB->createCommand("UPDATE {{labels}} SET assessment_value=CAST(code as integer) where code ~ '^[0-9]+'")->execute();
                    // copy assessment link to message since from now on we will have HTML assignment messages
                    $oDB->createCommand("UPDATE {{assessments}} set message=replace(message,'/''','''')||'<br /><a href=\"'||link||'\">'||link||'</a>'")->execute();
                    break;
                default:
                    die('Unknown database type');
            }
            // activate assessment where assessment rules exist
            $oDB->createCommand("UPDATE {{surveys}} SET assessments='Y' where sid in (SELECT sid FROM {{assessments}} group by sid)")->execute();
            // add language field to assessment table
            addColumn('{{assessments}}', 'language', "string(20) NOT NULL default 'en'");
            // update language field with default language of that particular survey
            $oDB->createCommand("UPDATE {{assessments}} SET language=(select language from {{surveys}} where sid={{assessments}}.sid)")->execute();
            // drop the old link field
            dropColumn('{{assessments}}', 'link');
            // Add new fields to survey language settings
            addColumn('{{surveys_languagesettings}}', 'surveyls_url', "string");
            addColumn('{{surveys_languagesettings}}', 'surveyls_endtext', 'text');
            // copy old URL fields ot language specific entries
            $oDB->createCommand("UPDATE {{surveys_languagesettings}} set surveyls_url=(select url from {{surveys}} where sid={{surveys_languagesettings}}.surveyls_survey_id)")->execute();
            // drop old URL field
            dropColumn('{{surveys}}', 'url');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 133), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 134) {
            // Add new tokens setting
            addColumn('{{surveys}}', 'usetokens', "string(1) NOT NULL default 'N'");
            addColumn('{{surveys}}', 'attributedescriptions', 'text');
            dropColumn('{{surveys}}', 'attribute1');
            dropColumn('{{surveys}}', 'attribute2');
            upgradeTokenTables134();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 134), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 135) {
            alterColumn('{{question_attributes}}', 'value', 'text');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 135), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 136) {
            addColumn('{{quota}}', 'autoload_url', "integer NOT NULL default 0");
            // Create quota table
            $aFields = array('quotals_id' => 'pk', 'quotals_quota_id' => 'integer NOT NULL DEFAULT 0', 'quotals_language' => "string(45) NOT NULL default 'en'", 'quotals_name' => 'string', 'quotals_message' => 'text NOT NULL', 'quotals_url' => 'string', 'quotals_urldescrip' => 'string');
            $oDB->createCommand()->createTable('{{quota_languagesettings}}', $aFields);
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 136), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 137) {
            addColumn('{{surveys_languagesettings}}', 'surveyls_dateformat', "integer NOT NULL default 1");
            addColumn('{{users}}', 'dateformat', "integer NOT NULL default 1");
            $oDB->createCommand()->update('{{surveys}}', array('startdate' => NULL), "usestartdate='N'");
            $oDB->createCommand()->update('{{surveys}}', array('expires' => NULL), "useexpiry='N'");
            dropColumn('{{surveys}}', 'useexpiry');
            dropColumn('{{surveys}}', 'usestartdate');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 137), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 138) {
            alterColumn('{{quota_members}}', 'code', "string(11)");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 138), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 139) {
            upgradeSurveyTables139();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 139), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 140) {
            addColumn('{{surveys}}', 'emailresponseto', 'text');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 140), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 141) {
            addColumn('{{surveys}}', 'tokenlength', 'integer NOT NULL default 15');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 141), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 142) {
            upgradeQuestionAttributes142();
            $oDB->createCommand()->alterColumn('{{surveys}}', 'expires', "datetime");
            $oDB->createCommand()->alterColumn('{{surveys}}', 'startdate', "datetime");
            $oDB->createCommand()->update('{{question_attributes}}', array('value' => 0), "value='false'");
            $oDB->createCommand()->update('{{question_attributes}}', array('value' => 1), "value='true'");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 142), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 143) {
            addColumn('{{questions}}', 'parent_qid', 'integer NOT NULL default 0');
            addColumn('{{answers}}', 'scale_id', 'integer NOT NULL default 0');
            addColumn('{{questions}}', 'scale_id', 'integer NOT NULL default 0');
            addColumn('{{questions}}', 'same_default', 'integer NOT NULL default 0');
            dropPrimaryKey('answers');
            addPrimaryKey('answers', array('qid', 'code', 'language', 'scale_id'));
            $aFields = array('qid' => "integer NOT NULL default 0", 'scale_id' => 'integer NOT NULL default 0', 'sqid' => 'integer  NOT NULL default 0', 'language' => 'string(20) NOT NULL', 'specialtype' => "string(20) NOT NULL default ''", 'defaultvalue' => 'text');
            $oDB->createCommand()->createTable('{{defaultvalues}}', $aFields);
            addPrimaryKey('defaultvalues', array('qid', 'specialtype', 'language', 'scale_id', 'sqid'));
            // -Move all 'answers' that are subquestions to the questions table
            // -Move all 'labels' that are answers to the answers table
            // -Transscribe the default values where applicable
            // -Move default values from answers to questions
            upgradeTables143();
            dropColumn('{{answers}}', 'default_value');
            dropColumn('{{questions}}', 'lid');
            dropColumn('{{questions}}', 'lid1');
            $aFields = array('sesskey' => "string(64) NOT NULL DEFAULT ''", 'expiry' => "datetime NOT NULL", 'expireref' => "string(250) DEFAULT ''", 'created' => "datetime NOT NULL", 'modified' => "datetime NOT NULL", 'sessdata' => 'text');
            $oDB->createCommand()->createTable('{{sessions}}', $aFields);
            addPrimaryKey('sessions', array('sesskey'));
            $oDB->createCommand()->createIndex('sess2_expiry', '{{sessions}}', 'expiry');
            $oDB->createCommand()->createIndex('sess2_expireref', '{{sessions}}', 'expireref');
            // Move all user templates to the new user template directory
            echo "<br>" . sprintf(gT("Moving user templates to new location at %s..."), $sUserTemplateRootDir) . "<br />";
            $hTemplateDirectory = opendir($sStandardTemplateRootDir);
            $aFailedTemplates = array();
            // get each entry
            while ($entryName = readdir($hTemplateDirectory)) {
                if (!in_array($entryName, array('.', '..', '.svn')) && is_dir($sStandardTemplateRootDir . DIRECTORY_SEPARATOR . $entryName) && !isStandardTemplate($entryName)) {
                    if (!rename($sStandardTemplateRootDir . DIRECTORY_SEPARATOR . $entryName, $sUserTemplateRootDir . DIRECTORY_SEPARATOR . $entryName)) {
                        $aFailedTemplates[] = $entryName;
                    }
                }
            }
            if (count($aFailedTemplates) > 0) {
                echo "The following templates at {$sStandardTemplateRootDir} could not be moved to the new location at {$sUserTemplateRootDir}:<br /><ul>";
                foreach ($aFailedTemplates as $sFailedTemplate) {
                    echo "<li>{$sFailedTemplate}</li>";
                }
                echo "</ul>Please move these templates manually after the upgrade has finished.<br />";
            }
            // close directory
            closedir($hTemplateDirectory);
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 143), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 145) {
            addColumn('{{surveys}}', 'savetimings', "string(1) NULL default 'N'");
            addColumn('{{surveys}}', 'showXquestions', "string(1) NULL default 'Y'");
            addColumn('{{surveys}}', 'showgroupinfo', "string(1) NULL default 'B'");
            addColumn('{{surveys}}', 'shownoanswer', "string(1) NULL default 'Y'");
            addColumn('{{surveys}}', 'showqnumcode', "string(1) NULL default 'X'");
            addColumn('{{surveys}}', 'bouncetime', 'integer');
            addColumn('{{surveys}}', 'bounceprocessing', "string(1) NULL default 'N'");
            addColumn('{{surveys}}', 'bounceaccounttype', "string(4)");
            addColumn('{{surveys}}', 'bounceaccounthost', "string(200)");
            addColumn('{{surveys}}', 'bounceaccountpass', "string(100)");
            addColumn('{{surveys}}', 'bounceaccountencryption', "string(3)");
            addColumn('{{surveys}}', 'bounceaccountuser', "string(200)");
            addColumn('{{surveys}}', 'showwelcome', "string(1) default 'Y'");
            addColumn('{{surveys}}', 'showprogress', "string(1) default 'Y'");
            addColumn('{{surveys}}', 'allowjumps', "string(1) default 'N'");
            addColumn('{{surveys}}', 'navigationdelay', "integer default 0");
            addColumn('{{surveys}}', 'nokeyboard', "string(1) default 'N'");
            addColumn('{{surveys}}', 'alloweditaftercompletion', "string(1) default 'N'");
            $aFields = array('sid' => "integer NOT NULL", 'uid' => "integer NOT NULL", 'permission' => 'string(20) NOT NULL', 'create_p' => "integer NOT NULL default 0", 'read_p' => "integer NOT NULL default 0", 'update_p' => "integer NOT NULL default 0", 'delete_p' => "integer NOT NULL default 0", 'import_p' => "integer NOT NULL default 0", 'export_p' => "integer NOT NULL default 0");
            $oDB->createCommand()->createTable('{{survey_permissions}}', $aFields);
            addPrimaryKey('survey_permissions', array('sid', 'uid', 'permission'));
            upgradeSurveyPermissions145();
            // drop the old survey rights table
            $oDB->createCommand()->dropTable('{{surveys_rights}}');
            // Add new fields for email templates
            addColumn('{{surveys_languagesettings}}', 'email_admin_notification_subj', "string");
            addColumn('{{surveys_languagesettings}}', 'email_admin_responses_subj', "string");
            addColumn('{{surveys_languagesettings}}', 'email_admin_notification', "text");
            addColumn('{{surveys_languagesettings}}', 'email_admin_responses', "text");
            //Add index to questions table to speed up subquestions
            $oDB->createCommand()->createIndex('parent_qid_idx', '{{questions}}', 'parent_qid');
            addColumn('{{surveys}}', 'emailnotificationto', "text");
            upgradeSurveys145();
            dropColumn('{{surveys}}', 'notification');
            alterColumn('{{conditions}}', 'method', "string(5)", false, '');
            $oDB->createCommand()->renameColumn('{{surveys}}', 'private', 'anonymized');
            $oDB->createCommand()->update('{{surveys}}', array('anonymized' => 'N'), "anonymized is NULL");
            alterColumn('{{surveys}}', 'anonymized', "string(1)", false, 'N');
            //now we clean up things that were not properly set in previous DB upgrades
            $oDB->createCommand()->update('{{answers}}', array('answer' => ''), "answer is NULL");
            $oDB->createCommand()->update('{{assessments}}', array('scope' => ''), "scope is NULL");
            $oDB->createCommand()->update('{{assessments}}', array('name' => ''), "name is NULL");
            $oDB->createCommand()->update('{{assessments}}', array('message' => ''), "message is NULL");
            $oDB->createCommand()->update('{{assessments}}', array('minimum' => ''), "minimum is NULL");
            $oDB->createCommand()->update('{{assessments}}', array('maximum' => ''), "maximum is NULL");
            $oDB->createCommand()->update('{{groups}}', array('group_name' => ''), "group_name is NULL");
            $oDB->createCommand()->update('{{labels}}', array('code' => ''), "code is NULL");
            $oDB->createCommand()->update('{{labelsets}}', array('label_name' => ''), "label_name is NULL");
            $oDB->createCommand()->update('{{questions}}', array('type' => 'T'), "type is NULL");
            $oDB->createCommand()->update('{{questions}}', array('title' => ''), "title is NULL");
            $oDB->createCommand()->update('{{questions}}', array('question' => ''), "question is NULL");
            $oDB->createCommand()->update('{{questions}}', array('other' => 'N'), "other is NULL");
            alterColumn('{{answers}}', 'answer', "text", false);
            alterColumn('{{answers}}', 'assessment_value', 'integer', false, '0');
            alterColumn('{{assessments}}', 'scope', "string(5)", false, '');
            alterColumn('{{assessments}}', 'name', "text", false);
            alterColumn('{{assessments}}', 'message', "text", false);
            alterColumn('{{assessments}}', 'minimum', "string(50)", false, '');
            alterColumn('{{assessments}}', 'maximum', "string(50)", false, '');
            // change the primary index to include language
            if (Yii::app()->db->driverName == 'mysql') {
                modifyPrimaryKey('assessments', array('id', 'language'));
            } else {
                dropPrimaryKey('assessments');
                addPrimaryKey('assessments', array('id', 'language'));
            }
            alterColumn('{{conditions}}', 'cfieldname', "string(50)", false, '');
            dropPrimaryKey('defaultvalues');
            alterColumn('{{defaultvalues}}', 'specialtype', "string(20)", false, '');
            addPrimaryKey('defaultvalues', array('qid', 'specialtype', 'language', 'scale_id', 'sqid'));
            alterColumn('{{groups}}', 'group_name', "string(100)", false, '');
            alterColumn('{{labels}}', 'code', "string(5)", false, '');
            dropPrimaryKey('labels');
            alterColumn('{{labels}}', 'language', "string(20)", false, 'en');
            addPrimaryKey('labels', array('lid', 'sortorder', 'language'));
            alterColumn('{{labelsets}}', 'label_name', "string(100)", false, '');
            alterColumn('{{questions}}', 'parent_qid', 'integer', false, '0');
            alterColumn('{{questions}}', 'title', "string(20)", false, '');
            alterColumn('{{questions}}', 'question', "text", false);
            try {
                setTransactionBookmark();
                $oDB->createCommand()->dropIndex('questions_idx4', '{{questions}}');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{questions}}', 'type', "string(1)", false, 'T');
            try {
                $oDB->createCommand()->createIndex('questions_idx4', '{{questions}}', 'type');
            } catch (Exception $e) {
            }
            alterColumn('{{questions}}', 'other', "string(1)", false, 'N');
            alterColumn('{{questions}}', 'mandatory', "string(1)");
            alterColumn('{{question_attributes}}', 'attribute', "string(50)");
            alterColumn('{{quota}}', 'qlimit', 'integer');
            $oDB->createCommand()->update('{{saved_control}}', array('identifier' => ''), "identifier is NULL");
            alterColumn('{{saved_control}}', 'identifier', "text", false);
            $oDB->createCommand()->update('{{saved_control}}', array('access_code' => ''), "access_code is NULL");
            alterColumn('{{saved_control}}', 'access_code', "text", false);
            alterColumn('{{saved_control}}', 'email', "string(320)");
            $oDB->createCommand()->update('{{saved_control}}', array('ip' => ''), "ip is NULL");
            alterColumn('{{saved_control}}', 'ip', "text", false);
            $oDB->createCommand()->update('{{saved_control}}', array('saved_thisstep' => ''), "saved_thisstep is NULL");
            alterColumn('{{saved_control}}', 'saved_thisstep', "text", false);
            $oDB->createCommand()->update('{{saved_control}}', array('status' => ''), "status is NULL");
            alterColumn('{{saved_control}}', 'status', "string(1)", false, '');
            $oDB->createCommand()->update('{{saved_control}}', array('saved_date' => '1980-01-01 00:00:00'), "saved_date is NULL");
            alterColumn('{{saved_control}}', 'saved_date', "datetime", false);
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => ''), "stg_value is NULL");
            alterColumn('{{settings_global}}', 'stg_value', "string", false, '');
            alterColumn('{{surveys}}', 'admin', "string(50)");
            $oDB->createCommand()->update('{{surveys}}', array('active' => 'N'), "active is NULL");
            alterColumn('{{surveys}}', 'active', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'startdate', "datetime");
            alterColumn('{{surveys}}', 'adminemail', "string(320)");
            alterColumn('{{surveys}}', 'anonymized', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'faxto', "string(20)");
            alterColumn('{{surveys}}', 'format', "string(1)");
            alterColumn('{{surveys}}', 'language', "string(50)");
            alterColumn('{{surveys}}', 'additional_languages', "string");
            alterColumn('{{surveys}}', 'printanswers', "string(1)", true, 'N');
            alterColumn('{{surveys}}', 'publicstatistics', "string(1)", true, 'N');
            alterColumn('{{surveys}}', 'publicgraphs', "string(1)", true, 'N');
            alterColumn('{{surveys}}', 'assessments', "string(1)", true, 'N');
            alterColumn('{{surveys}}', 'usetokens', "string(1)", true, 'N');
            alterColumn('{{surveys}}', 'bounce_email', "string(320)");
            alterColumn('{{surveys}}', 'tokenlength', 'integer', true, 15);
            $oDB->createCommand()->update('{{surveys_languagesettings}}', array('surveyls_title' => ''), "surveyls_title is NULL");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_title', "string(200)", false);
            alterColumn('{{surveys_languagesettings}}', 'surveyls_endtext', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_url', "string");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_urldescription', "string");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_invite_subj', "string");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_remind_subj', "string");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_register_subj', "string");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_confirm_subj', "string");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_dateformat', 'integer', false, 1);
            $oDB->createCommand()->update('{{users}}', array('users_name' => ''), "users_name is NULL");
            $oDB->createCommand()->update('{{users}}', array('full_name' => ''), "full_name is NULL");
            alterColumn('{{users}}', 'users_name', "string(64)", false, '');
            alterColumn('{{users}}', 'full_name', "string(50)", false);
            alterColumn('{{users}}', 'lang', "string(20)");
            alterColumn('{{users}}', 'email', "string(320)");
            alterColumn('{{users}}', 'superadmin', 'integer', false, 0);
            alterColumn('{{users}}', 'htmleditormode', "string(7)", true, 'default');
            alterColumn('{{users}}', 'dateformat', 'integer', false, 1);
            try {
                setTransactionBookmark();
                $oDB->createCommand()->dropIndex('email', '{{users}}');
            } catch (Exception $e) {
                // do nothing
                rollBackToTransactionBookmark();
            }
            $oDB->createCommand()->update('{{user_groups}}', array('name' => ''), "name is NULL");
            $oDB->createCommand()->update('{{user_groups}}', array('description' => ''), "description is NULL");
            alterColumn('{{user_groups}}', 'name', "string(20)", false);
            alterColumn('{{user_groups}}', 'description', "text", false);
            try {
                $oDB->createCommand()->dropIndex('user_in_groups_idx1', '{{user_in_groups}}');
            } catch (Exception $e) {
            }
            try {
                addPrimaryKey('user_in_groups', array('ugid', 'uid'));
            } catch (Exception $e) {
            }
            addColumn('{{surveys_languagesettings}}', 'surveyls_numberformat', "integer NOT NULL DEFAULT 0");
            $oDB->createCommand()->createTable('{{failed_login_attempts}}', array('id' => "pk", 'ip' => 'string(37) NOT NULL', 'last_attempt' => 'string(20) NOT NULL', 'number_attempts' => "integer NOT NULL"));
            upgradeTokens145();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 145), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 146) {
            upgradeSurveyTimings146();
            // Fix permissions for new feature quick-translation
            try {
                setTransactionBookmark();
                $oDB->createCommand("INSERT into {{survey_permissions}} (sid,uid,permission,read_p,update_p) SELECT sid,owner_id,'translations','1','1' from {{surveys}}")->execute();
                echo $modifyoutput;
                flush();
                @ob_flush();
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 146), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 147) {
            addColumn('{{users}}', 'templateeditormode', "string(7) NOT NULL default 'default'");
            addColumn('{{users}}', 'questionselectormode', "string(7) NOT NULL default 'default'");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 147), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 148) {
            addColumn('{{users}}', 'participant_panel', "integer NOT NULL default 0");
            $oDB->createCommand()->createTable('{{participants}}', array('participant_id' => 'string(50) NOT NULL', 'firstname' => 'string(40) default NULL', 'lastname' => 'string(40) default NULL', 'email' => 'string(80) default NULL', 'language' => 'string(40) default NULL', 'blacklisted' => 'string(1) NOT NULL', 'owner_uid' => "integer NOT NULL"));
            addPrimaryKey('participants', array('participant_id'));
            $oDB->createCommand()->createTable('{{participant_attribute}}', array('participant_id' => 'string(50) NOT NULL', 'attribute_id' => "integer NOT NULL", 'value' => 'string(50) NOT NULL'));
            addPrimaryKey('participant_attribute', array('participant_id', 'attribute_id'));
            $oDB->createCommand()->createTable('{{participant_attribute_names}}', array('attribute_id' => 'autoincrement', 'attribute_type' => 'string(4) NOT NULL', 'visible' => 'string(5) NOT NULL', 'PRIMARY KEY (attribute_id,attribute_type)'));
            $oDB->createCommand()->createTable('{{participant_attribute_names_lang}}', array('attribute_id' => 'integer NOT NULL', 'attribute_name' => 'string(30) NOT NULL', 'lang' => 'string(20) NOT NULL'));
            addPrimaryKey('participant_attribute_names_lang', array('attribute_id', 'lang'));
            $oDB->createCommand()->createTable('{{participant_attribute_values}}', array('attribute_id' => 'integer NOT NULL', 'value_id' => 'pk', 'value' => 'string(20) NOT NULL'));
            $oDB->createCommand()->createTable('{{participant_shares}}', array('participant_id' => 'string(50) NOT NULL', 'share_uid' => 'integer NOT NULL', 'date_added' => 'datetime NOT NULL', 'can_edit' => 'string(5) NOT NULL'));
            addPrimaryKey('participant_shares', array('participant_id', 'share_uid'));
            $oDB->createCommand()->createTable('{{survey_links}}', array('participant_id' => 'string(50) NOT NULL', 'token_id' => 'integer NOT NULL', 'survey_id' => 'integer NOT NULL', 'date_created' => 'datetime NOT NULL'));
            addPrimaryKey('survey_links', array('participant_id', 'token_id', 'survey_id'));
            // Add language field to question_attributes table
            addColumn('{{question_attributes}}', 'language', "string(20)");
            upgradeQuestionAttributes148();
            fixSubquestions();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 148), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 149) {
            $aFields = array('id' => 'integer', 'sid' => 'integer', 'parameter' => 'string(50)', 'targetqid' => 'integer', 'targetsqid' => 'integer');
            $oDB->createCommand()->createTable('{{survey_url_parameters}}', $aFields);
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 149), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 150) {
            addColumn('{{questions}}', 'relevance', 'TEXT');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 150), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 151) {
            addColumn('{{groups}}', 'randomization_group', "string(20) NOT NULL default ''");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 151), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 152) {
            $oDB->createCommand()->createIndex('question_attributes_idx3', '{{question_attributes}}', 'attribute');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 152), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 153) {
            $oDB->createCommand()->createTable('{{expression_errors}}', array('id' => 'pk', 'errortime' => 'string(50)', 'sid' => 'integer', 'gid' => 'integer', 'qid' => 'integer', 'gseq' => 'integer', 'qseq' => 'integer', 'type' => 'string(50)', 'eqn' => 'text', 'prettyprint' => 'text'));
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 153), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 154) {
            $oDB->createCommand()->addColumn('{{groups}}', 'grelevance', "text");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 154), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 155) {
            addColumn('{{surveys}}', 'googleanalyticsstyle', "string(1)");
            addColumn('{{surveys}}', 'googleanalyticsapikey', "string(25)");
            try {
                setTransactionBookmark();
                $oDB->createCommand()->renameColumn('{{surveys}}', 'showXquestions', 'showxquestions');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 155), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 156) {
            try {
                $oDB->createCommand()->dropTable('{{survey_url_parameters}}');
            } catch (Exception $e) {
                // do nothing
            }
            $oDB->createCommand()->createTable('{{survey_url_parameters}}', array('id' => 'pk', 'sid' => 'integer NOT NULL', 'parameter' => 'string(50) NOT NULL', 'targetqid' => 'integer', 'targetsqid' => 'integer'));
            $oDB->createCommand()->dropTable('{{sessions}}');
            if (Yii::app()->db->driverName == 'mysql') {
                $oDB->createCommand()->createTable('{{sessions}}', array('id' => 'string(32) NOT NULL', 'expire' => 'integer', 'data' => 'longtext'));
            } else {
                $oDB->createCommand()->createTable('{{sessions}}', array('id' => 'string(32) NOT NULL', 'expire' => 'integer', 'data' => 'text'));
            }
            addPrimaryKey('sessions', array('id'));
            addColumn('{{surveys_languagesettings}}', 'surveyls_attributecaptions', "TEXT");
            addColumn('{{surveys}}', 'sendconfirmation', "string(1) default 'Y'");
            upgradeSurveys156();
            // If a survey has an deleted owner, re-own the survey to the superadmin
            $oDB->schema->refresh();
            Survey::model()->refreshMetaData();
            $surveys = Survey::model();
            $surveys = $surveys->with(array('owner'))->findAll();
            foreach ($surveys as $row) {
                if (!isset($row->owner->attributes)) {
                    Survey::model()->updateByPk($row->sid, array('owner_id' => 1));
                }
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 156), "stg_name='DBVersion'");
            $oTransaction->commit();
            $oTransaction = $oDB->beginTransaction();
        }
        if ($iOldDBVersion < 157) {
            // MySQL DB corrections
            try {
                setTransactionBookmark();
                $oDB->createCommand()->dropIndex('questions_idx4', '{{questions}}');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{answers}}', 'assessment_value', 'integer', false, '0');
            dropPrimaryKey('answers');
            alterColumn('{{answers}}', 'scale_id', 'integer', false, '0');
            addPrimaryKey('answers', array('qid', 'code', 'language', 'scale_id'));
            alterColumn('{{conditions}}', 'method', "string(5)", false, '');
            alterColumn('{{participants}}', 'owner_uid', 'integer', false);
            alterColumn('{{participant_attribute_names}}', 'visible', 'string(5)', false);
            alterColumn('{{questions}}', 'type', "string(1)", false, 'T');
            alterColumn('{{questions}}', 'other', "string(1)", false, 'N');
            alterColumn('{{questions}}', 'mandatory', "string(1)");
            alterColumn('{{questions}}', 'scale_id', 'integer', false, '0');
            alterColumn('{{questions}}', 'parent_qid', 'integer', false, '0');
            alterColumn('{{questions}}', 'same_default', 'integer', false, '0');
            alterColumn('{{quota}}', 'qlimit', 'integer');
            alterColumn('{{quota}}', 'action', 'integer');
            alterColumn('{{quota}}', 'active', 'integer', false, '1');
            alterColumn('{{quota}}', 'autoload_url', 'integer', false, '0');
            alterColumn('{{saved_control}}', 'status', "string(1)", false, '');
            try {
                setTransactionBookmark();
                alterColumn('{{sessions}}', 'id', "string(32)", false);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{surveys}}', 'active', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'anonymized', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'format', "string(1)");
            alterColumn('{{surveys}}', 'savetimings', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'datestamp', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'usecookie', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'allowregister', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'allowsave', "string(1)", false, 'Y');
            alterColumn('{{surveys}}', 'autonumber_start', 'integer', false, '0');
            alterColumn('{{surveys}}', 'autoredirect', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'allowprev', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'printanswers', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'ipaddr', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'refurl', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'publicstatistics', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'publicgraphs', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'listpublic', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'htmlemail', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'sendconfirmation', "string(1)", false, 'Y');
            alterColumn('{{surveys}}', 'tokenanswerspersistence', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'assessments', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'usecaptcha', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'usetokens', "string(1)", false, 'N');
            alterColumn('{{surveys}}', 'tokenlength', 'integer', false, '15');
            alterColumn('{{surveys}}', 'showxquestions', "string(1)", true, 'Y');
            alterColumn('{{surveys}}', 'showgroupinfo', "string(1) ", true, 'B');
            alterColumn('{{surveys}}', 'shownoanswer', "string(1) ", true, 'Y');
            alterColumn('{{surveys}}', 'showqnumcode', "string(1) ", true, 'X');
            alterColumn('{{surveys}}', 'bouncetime', 'integer');
            alterColumn('{{surveys}}', 'showwelcome', "string(1)", true, 'Y');
            alterColumn('{{surveys}}', 'showprogress', "string(1)", true, 'Y');
            alterColumn('{{surveys}}', 'allowjumps', "string(1)", true, 'N');
            alterColumn('{{surveys}}', 'navigationdelay', 'integer', false, '0');
            alterColumn('{{surveys}}', 'nokeyboard', "string(1)", true, 'N');
            alterColumn('{{surveys}}', 'alloweditaftercompletion', "string(1)", true, 'N');
            alterColumn('{{surveys}}', 'googleanalyticsstyle', "string(1)");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_dateformat', 'integer', false, 1);
            try {
                setTransactionBookmark();
                alterColumn('{{survey_permissions}}', 'sid', "integer", false);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                alterColumn('{{survey_permissions}}', 'uid', "integer", false);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{survey_permissions}}', 'create_p', 'integer', false, '0');
            alterColumn('{{survey_permissions}}', 'read_p', 'integer', false, '0');
            alterColumn('{{survey_permissions}}', 'update_p', 'integer', false, '0');
            alterColumn('{{survey_permissions}}', 'delete_p', 'integer', false, '0');
            alterColumn('{{survey_permissions}}', 'import_p', 'integer', false, '0');
            alterColumn('{{survey_permissions}}', 'export_p', 'integer', false, '0');
            alterColumn('{{survey_url_parameters}}', 'targetqid', 'integer');
            alterColumn('{{survey_url_parameters}}', 'targetsqid', 'integer');
            alterColumn('{{templates_rights}}', 'use', 'integer', false);
            alterColumn('{{users}}', 'create_survey', 'integer', false, '0');
            alterColumn('{{users}}', 'create_user', 'integer', false, '0');
            alterColumn('{{users}}', 'participant_panel', 'integer', false, '0');
            alterColumn('{{users}}', 'delete_user', 'integer', false, '0');
            alterColumn('{{users}}', 'superadmin', 'integer', false, '0');
            alterColumn('{{users}}', 'configurator', 'integer', false, '0');
            alterColumn('{{users}}', 'manage_template', 'integer', false, '0');
            alterColumn('{{users}}', 'manage_label', 'integer', false, '0');
            alterColumn('{{users}}', 'dateformat', 'integer', false, 1);
            alterColumn('{{users}}', 'participant_panel', 'integer', false, '0');
            alterColumn('{{users}}', 'parent_id', 'integer', false);
            try {
                setTransactionBookmark();
                alterColumn('{{surveys_languagesettings}}', 'surveyls_survey_id', "integer", false);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{user_groups}}', 'owner_id', "integer", false);
            dropPrimaryKey('user_in_groups');
            alterColumn('{{user_in_groups}}', 'ugid', "integer", false);
            alterColumn('{{user_in_groups}}', 'uid', "integer", false);
            // Additional corrections for Postgres
            try {
                setTransactionBookmark();
                $oDB->createCommand()->createIndex('questions_idx3', '{{questions}}', 'gid');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->createIndex('conditions_idx3', '{{conditions}}', 'cqid');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->createIndex('questions_idx4', '{{questions}}', 'type');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->dropIndex('user_in_groups_idx1', '{{user_in_groups}}');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->dropIndex('{{user_name_key}}', '{{users}}');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->createIndex('users_name', '{{users}}', 'users_name', true);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                addPrimaryKey('user_in_groups', array('ugid', 'uid'));
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{participant_attribute}}', 'value', "string(50)", false);
            try {
                setTransactionBookmark();
                alterColumn('{{participant_attribute_names}}', 'attribute_type', "string(4)", false);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                dropColumn('{{participant_attribute_names_lang}}', 'id');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                addPrimaryKey('participant_attribute_names_lang', array('attribute_id', 'lang'));
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->renameColumn('{{participant_shares}}', 'shared_uid', 'share_uid');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{participant_shares}}', 'date_added', "datetime", false);
            alterColumn('{{participants}}', 'firstname', "string(40)");
            alterColumn('{{participants}}', 'lastname', "string(40)");
            alterColumn('{{participants}}', 'email', "string(80)");
            alterColumn('{{participants}}', 'language', "string(40)");
            alterColumn('{{quota_languagesettings}}', 'quotals_name', "string");
            try {
                setTransactionBookmark();
                alterColumn('{{survey_permissions}}', 'sid', 'integer', false);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                alterColumn('{{survey_permissions}}', 'uid', 'integer', false);
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            alterColumn('{{users}}', 'htmleditormode', "string(7)", true, 'default');
            // Sometimes the survey_links table was deleted before this step, if so
            // we recreate it (copied from line 663)
            if (!tableExists('{survey_links}')) {
                $oDB->createCommand()->createTable('{{survey_links}}', array('participant_id' => 'string(50) NOT NULL', 'token_id' => 'integer NOT NULL', 'survey_id' => 'integer NOT NULL', 'date_created' => 'datetime NOT NULL'));
                addPrimaryKey('survey_links', array('participant_id', 'token_id', 'survey_id'));
            }
            alterColumn('{{survey_links}}', 'date_created', "datetime", true);
            alterColumn('{{saved_control}}', 'identifier', "text", false);
            alterColumn('{{saved_control}}', 'email', "string(320)");
            alterColumn('{{surveys}}', 'adminemail', "string(320)");
            alterColumn('{{surveys}}', 'bounce_email', "string(320)");
            alterColumn('{{users}}', 'email', "string(320)");
            try {
                setTransactionBookmark();
                $oDB->createCommand()->dropIndex('assessments_idx', '{{assessments}}');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->createIndex('assessments_idx3', '{{assessments}}', 'gid');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->dropIndex('ixcode', '{{labels}}');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->dropIndex('{{labels_ixcode_idx}}', '{{labels}}');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            try {
                setTransactionBookmark();
                $oDB->createCommand()->createIndex('labels_code_idx', '{{labels}}', 'code');
            } catch (Exception $e) {
                rollBackToTransactionBookmark();
            }
            if (Yii::app()->db->driverName == 'pgsql') {
                try {
                    setTransactionBookmark();
                    $oDB->createCommand("ALTER TABLE ONLY {{user_groups}} ADD PRIMARY KEY (ugid); ")->execute;
                } catch (Exception $e) {
                    rollBackToTransactionBookmark();
                }
                try {
                    setTransactionBookmark();
                    $oDB->createCommand("ALTER TABLE ONLY {{users}} ADD PRIMARY KEY (uid); ")->execute;
                } catch (Exception $e) {
                    rollBackToTransactionBookmark();
                }
            }
            // Additional corrections for MSSQL
            alterColumn('{{answers}}', 'answer', "text", false);
            alterColumn('{{assessments}}', 'name', "text", false);
            alterColumn('{{assessments}}', 'message', "text", false);
            alterColumn('{{defaultvalues}}', 'defaultvalue', "text");
            alterColumn('{{expression_errors}}', 'eqn', "text");
            alterColumn('{{expression_errors}}', 'prettyprint', "text");
            alterColumn('{{groups}}', 'description', "text");
            alterColumn('{{groups}}', 'grelevance', "text");
            alterColumn('{{labels}}', 'title', "text");
            alterColumn('{{question_attributes}}', 'value', "text");
            alterColumn('{{questions}}', 'preg', "text");
            alterColumn('{{questions}}', 'help', "text");
            alterColumn('{{questions}}', 'relevance', "text");
            alterColumn('{{questions}}', 'question', "text", false);
            alterColumn('{{quota_languagesettings}}', 'quotals_quota_id', "integer", false);
            alterColumn('{{quota_languagesettings}}', 'quotals_message', "text", false);
            alterColumn('{{saved_control}}', 'refurl', "text");
            alterColumn('{{saved_control}}', 'access_code', "text", false);
            alterColumn('{{saved_control}}', 'ip', "text", false);
            alterColumn('{{saved_control}}', 'saved_thisstep', "text", false);
            alterColumn('{{saved_control}}', 'saved_date', "datetime", false);
            alterColumn('{{surveys}}', 'attributedescriptions', "text");
            alterColumn('{{surveys}}', 'emailresponseto', "text");
            alterColumn('{{surveys}}', 'emailnotificationto', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_description', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_welcometext', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_invite', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_remind', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_register', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_email_confirm', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_attributecaptions', "text");
            alterColumn('{{surveys_languagesettings}}', 'email_admin_notification', "text");
            alterColumn('{{surveys_languagesettings}}', 'email_admin_responses', "text");
            alterColumn('{{surveys_languagesettings}}', 'surveyls_endtext', "text");
            alterColumn('{{user_groups}}', 'description', "text", false);
            alterColumn('{{conditions}}', 'value', 'string', false, '');
            alterColumn('{{participant_shares}}', 'can_edit', "string(5)", false);
            alterColumn('{{users}}', 'password', "binary", false);
            dropColumn('{{users}}', 'one_time_pw');
            addColumn('{{users}}', 'one_time_pw', 'binary');
            $oDB->createCommand()->update('{{question_attributes}}', array('value' => '1'), "attribute = 'random_order' and value = '2'");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 157), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 158) {
            LimeExpressionManager::UpgradeConditionsToRelevance();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 158), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 159) {
            alterColumn('{{failed_login_attempts}}', 'ip', "string(40)", false);
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 159), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 160) {
            alterLanguageCode('it', 'it-informal');
            alterLanguageCode('it-formal', 'it');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 160), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 161) {
            addColumn('{{survey_links}}', 'date_invited', 'datetime NULL default NULL');
            addColumn('{{survey_links}}', 'date_completed', 'datetime NULL default NULL');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 161), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 162) {
            /* Fix participant db types */
            alterColumn('{{participant_attribute}}', 'value', "text", false);
            alterColumn('{{participant_attribute_names_lang}}', 'attribute_name', "string(255)", false);
            alterColumn('{{participant_attribute_values}}', 'value', "text", false);
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 162), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 163) {
            //Replace  by <script type="text/javascript" src="{TEMPLATEURL}template.js"></script> by {TEMPLATEJS}
            $replacedTemplate = replaceTemplateJS();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 163), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 164) {
            upgradeTokens148();
            // this should have bee done in 148 - that's why it is named this way
            // fix survey tables for missing or incorrect token field
            upgradeSurveyTables164();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 164), "stg_name='DBVersion'");
            // Not updating settings table as upgrade process takes care of that step now
        }
        if ($iOldDBVersion < 165) {
            $oDB->createCommand()->createTable('{{plugins}}', array('id' => 'pk', 'name' => 'string NOT NULL', 'active' => 'boolean'));
            $oDB->createCommand()->createTable('{{plugin_settings}}', array('id' => 'pk', 'plugin_id' => 'integer NOT NULL', 'model' => 'string', 'model_id' => 'integer', 'key' => 'string', 'value' => 'text'));
            alterColumn('{{surveys_languagesettings}}', 'surveyls_url', "text");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 165), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 166) {
            $oDB->createCommand()->renameTable('{{survey_permissions}}', '{{permissions}}');
            dropPrimaryKey('permissions');
            alterColumn('{{permissions}}', 'permission', "string(100)", false);
            $oDB->createCommand()->renameColumn('{{permissions}}', 'sid', 'entity_id');
            alterColumn('{{permissions}}', 'entity_id', "string(100)", false);
            addColumn('{{permissions}}', 'entity', "string(50)");
            $oDB->createCommand("update {{permissions}} set entity='survey'")->query();
            addColumn('{{permissions}}', 'id', 'pk');
            $oDB->createCommand()->createIndex('idxPermissions', '{{permissions}}', 'entity_id,entity,permission,uid', true);
            upgradePermissions166();
            dropColumn('{{users}}', 'create_survey');
            dropColumn('{{users}}', 'create_user');
            dropColumn('{{users}}', 'delete_user');
            dropColumn('{{users}}', 'superadmin');
            dropColumn('{{users}}', 'configurator');
            dropColumn('{{users}}', 'manage_template');
            dropColumn('{{users}}', 'manage_label');
            dropColumn('{{users}}', 'participant_panel');
            $oDB->createCommand()->dropTable('{{templates_rights}}');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 166), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 167) {
            addColumn('{{surveys_languagesettings}}', 'attachments', 'text');
            addColumn('{{users}}', 'created', 'datetime');
            addColumn('{{users}}', 'modified', 'datetime');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 167), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 168) {
            addColumn('{{participants}}', 'created', 'datetime');
            addColumn('{{participants}}', 'modified', 'datetime');
            addColumn('{{participants}}', 'created_by', 'integer');
            $oDB->createCommand('update {{participants}} set created_by=owner_uid')->query();
            alterColumn('{{participants}}', 'created_by', "integer", false);
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 168), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 169) {
            // Add new column for question index options.
            addColumn('{{surveys}}', 'questionindex', 'integer not null default 0');
            // Set values for existing surveys.
            $oDB->createCommand("update {{surveys}} set questionindex = 0 where allowjumps <> 'Y'")->query();
            $oDB->createCommand("update {{surveys}} set questionindex = 1 where allowjumps = 'Y'")->query();
            // Remove old column.
            dropColumn('{{surveys}}', 'allowjumps');
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 169), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 170) {
            // renamed advanced attributes fields dropdown_dates_year_min/max
            $oDB->createCommand()->update('{{question_attributes}}', array('attribute' => 'date_min'), "attribute='dropdown_dates_year_min'");
            $oDB->createCommand()->update('{{question_attributes}}', array('attribute' => 'date_max'), "attribute='dropdown_dates_year_max'");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 170), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 171) {
            try {
                dropColumn('{{sessions}}', 'data');
            } catch (Exception $e) {
            }
            switch (Yii::app()->db->driverName) {
                case 'mysql':
                case 'mysqli':
                    addColumn('{{sessions}}', 'data', 'longbinary');
                    break;
                case 'sqlsrv':
                case 'dblib':
                case 'mssql':
                    addColumn('{{sessions}}', 'data', 'VARBINARY(MAX)');
                    break;
                case 'pgsql':
                    addColumn('{{sessions}}', 'data', 'BYTEA');
                    break;
                default:
                    die('Unknown database type');
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 171), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 172) {
            switch (Yii::app()->db->driverName) {
                case 'pgsql':
                    // Special treatment for Postgres as it is too dumb to convert a string to a number without explicit being told to do so ... seriously?
                    alterColumn('{{permissions}}', 'entity_id', "INTEGER USING (entity_id::integer)", false);
                    break;
                case 'sqlsrv':
                case 'dblib':
                case 'mssql':
                    try {
                        setTransactionBookmark();
                        $oDB->createCommand()->dropIndex('permissions_idx2', '{{permissions}}');
                    } catch (Exception $e) {
                        rollBackToTransactionBookmark();
                    }
                    try {
                        setTransactionBookmark();
                        $oDB->createCommand()->dropIndex('idxPermissions', '{{permissions}}');
                    } catch (Exception $e) {
                        rollBackToTransactionBookmark();
                    }
                    alterColumn('{{permissions}}', 'entity_id', "INTEGER", false);
                    $oDB->createCommand()->createIndex('permissions_idx2', '{{permissions}}', 'entity_id,entity,permission,uid', true);
                    break;
                default:
                    alterColumn('{{permissions}}', 'entity_id', "INTEGER", false);
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 172), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 173) {
            addColumn('{{participant_attribute_names}}', 'defaultname', "string(50) NOT NULL default ''");
            upgradeCPDBAttributeDefaultNames173();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 173), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 174) {
            alterColumn('{{participants}}', 'email', "string(254)");
            alterColumn('{{saved_control}}', 'email', "string(254)");
            alterColumn('{{surveys}}', 'adminemail', "string(254)");
            alterColumn('{{surveys}}', 'bounce_email', "string(254)");
            switch (Yii::app()->db->driverName) {
                case 'sqlsrv':
                case 'dblib':
                case 'mssql':
                    dropUniqueKeyMSSQL('email', '{{users}}');
            }
            alterColumn('{{users}}', 'email', "string(254)");
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 174), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 175) {
            switch (Yii::app()->db->driverName) {
                case 'pgsql':
                    // Special treatment for Postgres as it is too dumb to convert a boolean to a number without explicit being told to do so
                    alterColumn('{{plugins}}', 'active', "INTEGER USING (active::integer)", false);
                    break;
                default:
                    alterColumn('{{plugins}}', 'active', "integer", false, '0');
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 175), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 176) {
            upgradeTokens176();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 176), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 177) {
            if (Yii::app()->getConfig('auth_webserver') === true) {
                // using auth webserver, now activate the plugin with default settings.
                if (!class_exists('Authwebserver', false)) {
                    $plugin = Plugin::model()->findByAttributes(array('name' => 'Authwebserver'));
                    if (!$plugin) {
                        $plugin = new Plugin();
                        $plugin->name = 'Authwebserver';
                        $plugin->active = 1;
                        $plugin->save();
                        $plugin = App()->getPluginManager()->loadPlugin('Authwebserver', $plugin->id);
                        $aPluginSettings = $plugin->getPluginSettings(true);
                        $aDefaultSettings = array();
                        foreach ($aPluginSettings as $key => $settings) {
                            if (is_array($settings) && array_key_exists('current', $settings)) {
                                $aDefaultSettings[$key] = $settings['current'];
                            }
                        }
                        $plugin->saveSettings($aDefaultSettings);
                    } else {
                        $plugin->active = 1;
                        $plugin->save();
                    }
                }
            }
            upgradeSurveys177();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 177), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 178) {
            if (Yii::app()->db->driverName == 'mysql' || Yii::app()->db->driverName == 'mysqli') {
                modifyPrimaryKey('questions', array('qid', 'language'));
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 178), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 179) {
            upgradeSurveys177();
            // Needs to be run again to make sure
            upgradeTokenTables179();
            alterColumn('{{participants}}', 'email', "string(254)", false);
            alterColumn('{{participants}}', 'firstname', "string(150)", false);
            alterColumn('{{participants}}', 'lastname', "string(150)", false);
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 179), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 180) {
            $aUsers = User::model()->findAll();
            $aPerm = array('entity_id' => 0, 'entity' => 'global', 'uid' => 0, 'permission' => 'auth_db', 'create_p' => 0, 'read_p' => 1, 'update_p' => 0, 'delete_p' => 0, 'import_p' => 0, 'export_p' => 0);
            foreach ($aUsers as $oUser) {
                if (!Permission::model()->hasGlobalPermission('auth_db', 'read', $oUser->uid)) {
                    $oPermission = new Permission();
                    foreach ($aPerm as $k => $v) {
                        $oPermission->{$k} = $v;
                    }
                    $oPermission->uid = $oUser->uid;
                    $oPermission->save();
                }
            }
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 180), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 181) {
            upgradeTokenTables181();
            upgradeSurveyTables181();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 181), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 183) {
            upgradeSurveyTables183();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 183), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 184) {
            fixKCFinder184();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 184), "stg_name='DBVersion'");
        }
        // LS 2.5 table start at 250
        if ($iOldDBVersion < 250) {
            createBoxes250();
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 250), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 251) {
            upgradeSurveyTables251();
            // Update DBVersion
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 251), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 252) {
            Yii::app()->db->createCommand()->addColumn('{{questions}}', 'modulename', 'string');
            // Update DBVersion
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 252), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 253) {
            upgradeSurveyTables253();
            // Update DBVersion
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 253), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 254) {
            upgradeSurveyTables254();
            // Update DBVersion
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 254), "stg_name='DBVersion'");
        }
        if ($iOldDBVersion < 255) {
            upgradeSurveyTables255();
            // Update DBVersion
            $oDB->createCommand()->update('{{settings_global}}', array('stg_value' => 255), "stg_name='DBVersion'");
        }
        $oTransaction->commit();
        // Activate schema caching
        $oDB->schemaCachingDuration = 3600;
        // Load all tables of the application in the schema
        $oDB->schema->getTables();
        // clear the cache of all loaded tables
        $oDB->schema->refresh();
    } catch (Exception $e) {
        Yii::app()->setConfig('Updating', false);
        $oTransaction->rollback();
        // Activate schema caching
        $oDB->schemaCachingDuration = 3600;
        // Load all tables of the application in the schema
        $oDB->schema->getTables();
        // clear the cache of all loaded tables
        $oDB->schema->refresh();
        echo '<br /><br />' . gT('An non-recoverable error happened during the update. Error details:') . "<p>" . htmlspecialchars($e->getMessage()) . '</p><br />';
        return false;
    }
    fixLanguageConsistencyAllSurveys();
    Yii::app()->setConfig('Updating', false);
    return true;
}