Exemplo n.º 1
0
 function limesurvey_lang($langcode)
 {
     global $rootdir;
     $langcode = sanitize_languagecode($langcode);
     $streamer = new FileReader($rootdir . '/locale/' . $langcode . '/LC_MESSAGES/' . $langcode . '.mo');
     $this->gettextclass = new gettext_reader($streamer);
     $this->langcode = $langcode;
 }
 public function actionPublicList($lang = null)
 {
     if (!empty($lang)) {
         App()->setLanguage(sanitize_languagecode($lang));
     } else {
         App()->setLanguage(App()->getConfig('defaultlang'));
     }
     $this->render('publicSurveyList', array('publicSurveys' => Survey::model()->active()->open()->public()->with('languagesettings')->findAll(), 'futureSurveys' => Survey::model()->active()->registration()->public()->with('languagesettings')->findAll()));
 }
 function limesurvey_lang($sLanguageCode)
 {
     if (empty($sLanguageCode)) {
         trigger_error('langcode param is undefined ', E_USER_WARNING);
     }
     Yii::app()->loadHelper('sanitize');
     $sLanguageCode = sanitize_languagecode($sLanguageCode);
     $streamer = new FileReader(getcwd() . DIRECTORY_SEPARATOR . 'locale' . DIRECTORY_SEPARATOR . $sLanguageCode . DIRECTORY_SEPARATOR . 'LC_MESSAGES' . DIRECTORY_SEPARATOR . $sLanguageCode . '.mo');
     $this->gettextclass = new gettext_reader($streamer);
     $this->langcode = $sLanguageCode;
 }
Exemplo n.º 4
0
 function actionLocal($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($this->getController()->createUrl('/'));
     }
     $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) {
         $baselang = Survey::model()->findByPk($iSurveyID)->language;
         Yii::import('application.libraries.Limesurvey_lang', true);
         $clang = new Limesurvey_lang($baselang);
     } else {
         $sLanguageCode = sanitize_languagecode($sLanguageCode);
         Yii::import('application.libraries.Limesurvey_lang', true);
         $clang = new Limesurvey_lang($sLanguageCode);
         $baselang = $sLanguageCode;
     }
     Yii::app()->lang = $clang;
     $thissurvey = getSurveyInfo($iSurveyID, $baselang);
     if ($thissurvey == false || Yii::app()->db->schema->getTable("{{tokens_{$iSurveyID}}}") == null) {
         $html = $clang->gT('This survey does not seem to exist.');
     } else {
         $row = Tokens_dynamic::getEmailStatus($iSurveyID, $sToken);
         if ($row == false) {
             $html = $clang->gT('You are not a participant in this survey.');
         } else {
             $usresult = $row['emailstatus'];
             if ($usresult == 'OptOut') {
                 $usresult = Tokens_dynamic::updateEmailStatus($iSurveyID, $sToken, 'OK');
                 $html = $clang->gT('You have been successfully added back to this survey.');
             } else {
                 if ($usresult == 'OK') {
                     $html = $clang->gT('You are already a part of this survey.');
                 } else {
                     $html = $clang->gT('You have been already removed from this survey.');
                 }
             }
         }
     }
     //PRINT COMPLETED PAGE
     if (!$thissurvey['templatedir']) {
         $thistpl = getTemplatePath(Yii::app()->getConfig("defaulttemplate"));
     } else {
         $thistpl = getTemplatePath($thissurvey['templatedir']);
     }
     $this->_renderHtml($html, $thistpl, $clang);
 }
Exemplo n.º 5
0
 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;
         Yii::import('application.libraries.Limesurvey_lang', true);
         $clang = new Limesurvey_lang($sBaseLanguage);
     } else {
         $sLanguageCode = sanitize_languagecode($sLanguageCode);
         Yii::import('application.libraries.Limesurvey_lang', true);
         $clang = new Limesurvey_lang($sLanguageCode);
         $sBaseLanguage = $sLanguageCode;
     }
     Yii::app()->lang = $clang;
     $aSurveyInfo = getSurveyInfo($iSurveyID, $sBaseLanguage);
     if ($aSurveyInfo == false || !tableExists("{{tokens_{$iSurveyID}}}")) {
         $sMessage = $clang->gT('This survey does not seem to exist.');
     } else {
         $oToken = Token::model($iSurveyID)->findByAttributes(array('token' => $token));
         if (!isset($oToken)) {
             $sMessage = $clang->gT('You are not a participant in this survey.');
         } else {
             if ($oToken->emailstatus == 'OptOut') {
                 $oToken->emailstatus = 'OK';
                 $oToken->save();
                 $sMessage = $clang->gT('You have been successfully added back to this survey.');
             } elseif ($oToken->emailstatus == 'OK') {
                 $sMessage = $clang->gT('You are already a part of this survey.');
             } else {
                 $sMessage = $clang->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, $clang, $aSurveyInfo);
 }
Exemplo n.º 6
0
function globalsettingssave()
{
    global $action, $editsurvey, $connect, $scriptname, $clang;
    if (isset($action) && $action == "globalsettingssave") {
        if ($_SESSION['USER_RIGHT_SUPERADMIN'] == 1) {
            if (sanitize_int($_POST['maxemails']) < 1) {
                $_POST['maxemails'] = 1;
            }
            setGlobalSetting('sitename', strip_tags($_POST['sitename']));
            setGlobalSetting('updatecheckperiod', (int) $_POST['updatecheckperiod']);
            setGlobalSetting('addTitleToLinks', sanitize_paranoid_string($_POST['addTitleToLinks']));
            setGlobalSetting('defaultlang', sanitize_languagecode($_POST['defaultlang']));
            setGlobalSetting('defaulthtmleditormode', sanitize_paranoid_string($_POST['defaulthtmleditormode']));
            setGlobalSetting('defaulttemplate', sanitize_paranoid_string($_POST['defaulttemplate']));
            setGlobalSetting('emailmethod', strip_tags($_POST['emailmethod']));
            setGlobalSetting('emailsmtphost', strip_tags(returnglobal('emailsmtphost')));
            if (returnglobal('emailsmtppassword') != 'somepassword') {
                setGlobalSetting('emailsmtppassword', strip_tags(returnglobal('emailsmtppassword')));
            }
            setGlobalSetting('emailsmtpssl', sanitize_paranoid_string(returnglobal('emailsmtpssl')));
            setGlobalSetting('emailsmtpdebug', sanitize_int(returnglobal('emailsmtpdebug')));
            setGlobalSetting('emailsmtpuser', strip_tags(returnglobal('emailsmtpuser')));
            setGlobalSetting('filterxsshtml', strip_tags($_POST['filterxsshtml']));
            setGlobalSetting('siteadminbounce', strip_tags($_POST['siteadminbounce']));
            setGlobalSetting('siteadminemail', strip_tags($_POST['siteadminemail']));
            setGlobalSetting('siteadminname', strip_tags($_POST['siteadminname']));
            setGlobalSetting('shownoanswer', sanitize_int($_POST['shownoanswer']));
            $repeatheadingstemp = (int) $_POST['repeatheadings'];
            if ($repeatheadingstemp == 0) {
                $repeatheadingstemp = 25;
            }
            setGlobalSetting('repeatheadings', $repeatheadingstemp);
            setGlobalSetting('maxemails', sanitize_int($_POST['maxemails']));
            $sessionlifetimetemp = (int) $_POST['sessionlifetime'];
            if ($sessionlifetimetemp == 0) {
                $sessionlifetimetemp = 3600;
            }
            setGlobalSetting('sessionlifetime', $sessionlifetimetemp);
            setGlobalSetting('surveyPreview_require_Auth', strip_tags($_POST['surveyPreview_require_Auth']));
            $savetime = trim(strip_tags((double) $_POST['timeadjust']) . ' hours');
            //makes sure it is a number, at least 0
            if (substr($savetime, 0, 1) != '-' && substr($savetime, 0, 1) != '+') {
                $savetime = '+' . $savetime;
            }
            setGlobalSetting('timeadjust', $savetime);
            setGlobalSetting('usepdfexport', strip_tags($_POST['usepdfexport']));
            setGlobalSetting('usercontrolSameGroupPolicy', strip_tags($_POST['usercontrolSameGroupPolicy']));
            $editsurvey .= "<div class='header'>" . $clang->gT("Global settings") . "</div>\n" . "<div class=\"messagebox\">\n" . "<br /><div class=\"successheader\">" . $clang->gT("Global settings were saved.") . "</div>\n" . "<br/><input type=\"submit\" onclick=\"window.open('admin.php', '_top')\" value=\"" . $clang->gT("Continue") . "\"/>\n" . "</div>\n";
        }
    }
}
Exemplo n.º 7
0
 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);
 }
Exemplo n.º 8
0
 function __construct($sLanguageCode, $bForceRefresh = false)
 {
     if (empty($sLanguageCode)) {
         trigger_error('langcode param is undefined ', E_USER_WARNING);
     }
     static $aClassCache = array();
     Yii::app()->loadHelper('sanitize');
     $sLanguageCode = sanitize_languagecode($sLanguageCode);
     if (isset($aClassCache[$sLanguageCode]) && !$bForceRefresh) {
         $this->gettextclass = $aClassCache[$sLanguageCode];
     } else {
         $streamer = new FileReader(getcwd() . DIRECTORY_SEPARATOR . 'locale' . DIRECTORY_SEPARATOR . $sLanguageCode . DIRECTORY_SEPARATOR . 'LC_MESSAGES' . DIRECTORY_SEPARATOR . $sLanguageCode . '.mo');
         $this->gettextclass = $aClassCache[$sLanguageCode] = new gettext_reader($streamer);
     }
     $this->langcode = $sLanguageCode;
 }
Exemplo n.º 9
0
    else
    {
        $datetimeobj = new Date_Time_Converter(trim($_POST['validuntil']), $dateformatdetails['phpdate'].' H:i');
        $_POST['validuntil'] =$datetimeobj->convert('Y-m-d H:i:s');
    }

    $santitizedtoken='';

    $tokenoutput .= "\t<div class='header ui-widget-header'>".$clang->gT("Add dummy tokens")."</div>\n"
    ."\t<div class='messagebox ui-corner-all'>\n";
    $data = array('firstname' => $_POST['firstname'],
    'lastname' => $_POST['lastname'],
    'email' => sanitize_email($_POST['email']),
    'emailstatus' => 'OK',
    'token' => $santitizedtoken,
    'language' => sanitize_languagecode($_POST['language']),
        'sent' => 'N',
    'remindersent' => 'N',
    'completed' => 'N',
    'usesleft' => $_POST['usesleft'],
    'validfrom' => $_POST['validfrom'],
    'validuntil' => $_POST['validuntil']);

    // add attributes
    $attrfieldnames=GetAttributeFieldnames($surveyid);
    foreach ($attrfieldnames as $attr_name)
    {
        $data[$attr_name]=$_POST[$attr_name];
    }
    $tblInsert=db_table_name('tokens_'.$surveyid);
    $amount = sanitize_int($_POST['amount']);
Exemplo n.º 10
0
 function actionparticipants()
 {
     $surveyid = Yii::app()->request->getQuery('surveyid');
     $langcode = Yii::app()->request->getQuery('langcode');
     $token = Yii::app()->request->getQuery('token');
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('sanitize');
     $sLanguageCode = $langcode;
     $iSurveyID = $surveyid;
     $sToken = $token;
     $sToken = sanitize_token($sToken);
     if (!$iSurveyID) {
         $this->redirect(Yii::app()->getController()->createUrl('/'));
     }
     $iSurveyID = (int) $iSurveyID;
     //Make sure it's an integer (protect from SQL injects)
     //Check that there is a SID
     // Get passed language from form, so that we dont lose this!
     if (!isset($sLanguageCode) || $sLanguageCode == "" || !$sLanguageCode) {
         $baselang = Survey::model()->findByPk($iSurveyID)->language;
         Yii::import('application.libraries.Limesurvey_lang', true);
         $clang = new Limesurvey_lang($baselang);
     } else {
         $sLanguageCode = sanitize_languagecode($sLanguageCode);
         Yii::import('application.libraries.Limesurvey_lang', true);
         $clang = new Limesurvey_lang($sLanguageCode);
         $baselang = $sLanguageCode;
     }
     Yii::app()->lang = $clang;
     $thissurvey = getSurveyInfo($iSurveyID, $baselang);
     if ($thissurvey == false || !tableExists("{{tokens_{$iSurveyID}}}")) {
         $html = $clang->gT('This survey does not seem to exist.');
     } else {
         $row = Tokens_dynamic::getEmailStatus($iSurveyID, $sToken);
         $datas = Tokens_dynamic::model($iSurveyID)->find('token = :token', array(":token" => $sToken));
         if ($row == false) {
             $html = $clang->gT('You are not a participant in this survey.');
         } else {
             $usresult = $row['emailstatus'];
             if ($usresult == 'OK') {
                 $usresult = Tokens_dynamic::updateEmailStatus($iSurveyID, $sToken, 'OptOut');
                 $html = $clang->gT('You have been successfully removed from this survey.');
             } else {
                 $html = $clang->gT('You have been already removed from this survey.');
             }
             if (!empty($datas->participant_id) && $datas->participant_id != "") {
                 //Participant also exists in central db
                 $cpdb = Participants::model()->find('participant_id = :participant_id', array(":participant_id" => $datas->participant_id));
                 if ($cpdb->blacklisted == "Y") {
                     $html .= "<br />";
                     $html .= $clang->gt("You have already been removed from the central participants list for this site");
                 } else {
                     $cpdb->blacklisted = 'Y';
                     $cpdb->save();
                     $html .= "<br />";
                     $html .= $clang->gT("You have been removed from the central participants list for this site");
                 }
             }
         }
     }
     //PRINT COMPLETED PAGE
     if (!$thissurvey['templatedir']) {
         $thistpl = getTemplatePath(Yii::app()->getConfig("defaulttemplate"));
     } else {
         $thistpl = getTemplatePath($thissurvey['templatedir']);
     }
     $this->_renderHtml($html, $thistpl);
 }
Exemplo n.º 11
0
 protected function postLogin()
 {
     $user = $this->getUser();
     App()->user->login($this);
     // Check for default password
     if ($this->password === 'password') {
         Yii::app()->setFlashMessage(gT("Warning: You are still using the default password ('password'). Please change your password and re-login again."), 'warning');
     }
     if ((int) App()->request->getPost('width', '1280') < 1280) {
         Yii::app()->setFlashMessage(gT("Your browser screen size is too small to use the administration properly. The minimum size required is 1280*1024 px."), 'error');
     }
     // Do session setup
     Yii::app()->session['loginID'] = (int) $user->uid;
     Yii::app()->session['user'] = $user->users_name;
     Yii::app()->session['full_name'] = $user->full_name;
     Yii::app()->session['htmleditormode'] = $user->htmleditormode;
     Yii::app()->session['templateeditormode'] = $user->templateeditormode;
     Yii::app()->session['questionselectormode'] = $user->questionselectormode;
     Yii::app()->session['dateformat'] = $user->dateformat;
     Yii::app()->session['session_hash'] = hash('sha256', getGlobalSetting('SessionName') . $user->users_name . $user->uid);
     // Perform language settings
     if (App()->request->getPost('loginlang', 'default') != 'default') {
         $user->lang = sanitize_languagecode(App()->request->getPost('loginlang'));
         $user->save();
         $sLanguage = $user->lang;
     } else {
         if ($user->lang == 'auto' || $user->lang == '') {
             $sLanguage = getBrowserLanguage();
         } else {
             $sLanguage = $user->lang;
         }
     }
     Yii::app()->session['adminlang'] = $sLanguage;
     App()->setLanguage($sLanguage);
 }
Exemplo n.º 12
0
 function graph()
 {
     Yii::app()->loadHelper('admin/statistics');
     Yii::app()->loadHelper("surveytranslator");
     // Initialise PCHART
     require_once Yii::app()->basePath . '/third_party/pchart/pchart/pChart.class';
     require_once Yii::app()->basePath . '/third_party/pchart/pchart/pData.class';
     require_once Yii::app()->basePath . '/third_party/pchart/pchart/pCache.class';
     Yii::import('application.third_party.ar-php.Arabic', true);
     $tempdir = Yii::app()->getConfig("tempdir");
     $MyCache = new pCache($tempdir . '/');
     $aData['success'] = 1;
     $sStatisticsLanguage = sanitize_languagecode($_POST['sStatisticsLanguage']);
     $oStatisticsLanguage = new Limesurvey_lang($sStatisticsLanguage);
     if (isset($_POST['cmd']) && isset($_POST['id'])) {
         list($qsid, $qgid, $qqid) = explode("X", substr($_POST['id'], 0), 3);
         if (!is_numeric(substr($qsid, 0, 1))) {
             // Strip first char when not numeric (probably T or D)
             $qsid = substr($qsid, 1);
         }
         $aFieldmap = createFieldMap($qsid, 'full', false, false, $sStatisticsLanguage);
         $qtype = $aFieldmap[$_POST['id']]['type'];
         $qqid = $aFieldmap[$_POST['id']]['qid'];
         $aattr = getQuestionAttributeValues($qqid);
         $field = substr($_POST['id'], 1);
         switch ($_POST['cmd']) {
             case 'showmap':
                 if (isset($aattr['location_mapservice'])) {
                     $aData['mapdata'] = array("coord" => getQuestionMapData($field, $qsid), "zoom" => $aattr['location_mapzoom'], "width" => $aattr['location_mapwidth'], "height" => $aattr['location_mapheight']);
                     QuestionAttribute::model()->setQuestionAttribute($qqid, 'statistics_showmap', 1);
                 } else {
                     $aData['success'] = 0;
                 }
                 break;
             case 'hidemap':
                 if (isset($aattr['location_mapservice'])) {
                     $aData['success'] = 1;
                     QuestionAttribute::model()->setQuestionAttribute($qqid, 'statistics_showmap', 0);
                 } else {
                     $aData['success'] = 0;
                 }
                 break;
             case 'showgraph':
                 if (isset($aattr['location_mapservice'])) {
                     $aData['mapdata'] = array("coord" => getQuestionMapData($field, $qsid), "zoom" => $aattr['location_mapzoom'], "width" => $aattr['location_mapwidth'], "height" => $aattr['location_mapheight']);
                 }
                 $bChartType = $qtype != "M" && $qtype != "P" && $aattr["statistics_graphtype"] == "1";
                 $adata = Yii::app()->session['stats'][$_POST['id']];
                 $aData['chartdata'] = createChart($qqid, $qsid, $bChartType, $adata['lbl'], $adata['gdata'], $adata['grawdata'], $MyCache, $oStatisticsLanguage, $qtype);
                 QuestionAttribute::model()->setQuestionAttribute($qqid, 'statistics_showgraph', 1);
                 break;
             case 'hidegraph':
                 QuestionAttribute::model()->setQuestionAttribute($qqid, 'statistics_showgraph', 0);
                 break;
             case 'showbar':
                 if ($qtype == "M" || $qtype == "P") {
                     $aData['success'] = 0;
                     break;
                 }
                 QuestionAttribute::model()->setQuestionAttribute($qqid, 'statistics_graphtype', 0);
                 $adata = Yii::app()->session['stats'][$_POST['id']];
                 $aData['chartdata'] = createChart($qqid, $qsid, 0, $adata['lbl'], $adata['gdata'], $adata['grawdata'], $MyCache, $oStatisticsLanguage, $qtype);
                 break;
             case 'showpie':
                 if ($qtype == "M" || $qtype == "P") {
                     $aData['success'] = 0;
                     break;
                 }
                 QuestionAttribute::model()->setQuestionAttribute($qqid, 'statistics_graphtype', 1);
                 $adata = Yii::app()->session['stats'][$_POST['id']];
                 $aData['chartdata'] = createChart($qqid, $qsid, 1, $adata['lbl'], $adata['gdata'], $adata['grawdata'], $MyCache, $oStatisticsLanguage, $qtype);
                 break;
             default:
                 $aData['success'] = 0;
                 break;
         }
     } else {
         $aData['success'] = 0;
     }
     //$this->_renderWrappedTemplate('export', 'statistics_graph_view', $aData);
     $this->getController()->renderPartial('export/statistics_graph_view', $aData);
 }
 //Fix up dates and match to database format
 if (trim($_POST['validfrom']) == '') {
     $_POST['validfrom'] = null;
 } else {
     $datetimeobj = new Date_Time_Converter(trim($_POST['validfrom']), $dateformatdetails['phpdate'] . ' H:i');
     $_POST['validfrom'] = $datetimeobj->convert('Y-m-d H:i:s');
 }
 if (trim($_POST['validuntil']) == '') {
     $_POST['validuntil'] = null;
 } else {
     $datetimeobj = new Date_Time_Converter(trim($_POST['validuntil']), $dateformatdetails['phpdate'] . ' H:i');
     $_POST['validuntil'] = $datetimeobj->convert('Y-m-d H:i:s');
 }
 $santitizedtoken = '';
 $tokenoutput .= "\t<div class='header ui-widget-header'>" . $clang->gT("Add dummy tokens") . "</div>\n" . "\t<div class='messagebox ui-corner-all'>\n";
 $data = array('firstname' => $_POST['firstname'], 'lastname' => $_POST['lastname'], 'email' => sanitize_email($_POST['email']), 'emailstatus' => 'OK', 'token' => $santitizedtoken, 'language' => sanitize_languagecode($_POST['language']), 'sent' => 'N', 'remindersent' => 'N', 'completed' => 'N', 'usesleft' => $_POST['usesleft'], 'validfrom' => $_POST['validfrom'], 'validuntil' => $_POST['validuntil']);
 // add attributes
 $attrfieldnames = GetAttributeFieldnames($surveyid);
 foreach ($attrfieldnames as $attr_name) {
     $data[$attr_name] = $_POST[$attr_name];
 }
 $tblInsert = db_table_name('tokens_' . $surveyid);
 $amount = sanitize_int($_POST['amount']);
 $tokenlength = sanitize_int($_POST['tokenlen']);
 for ($i = 0; $i < $amount; $i++) {
     $dataToInsert = $data;
     $dataToInsert['firstname'] = str_replace('{TOKEN_COUNTER}', "{$i}", $dataToInsert['firstname']);
     $dataToInsert['lastname'] = str_replace('{TOKEN_COUNTER}', "{$i}", $dataToInsert['lastname']);
     $dataToInsert['email'] = str_replace('{TOKEN_COUNTER}', "{$i}", $dataToInsert['email']);
     $isvalidtoken = false;
     while ($isvalidtoken == false) {
Exemplo n.º 14
0
 /**
  * Export Dialog
  *
  */
 public function exportdialog($iSurveyId)
 {
     $surveyinfo = Survey::model()->findByPk($iSurveyId)->surveyinfo;
     $aData = array();
     $aData["surveyinfo"] = $surveyinfo;
     $aData['title_bar']['title'] = $surveyinfo['surveyls_title'] . "(" . gT("ID") . ":" . $iSurveyId . ")";
     $aData['sidemenu']["token_menu"] = true;
     $aData['sidemenu']['state'] = false;
     $aData['token_bar']['exportbutton']['form'] = true;
     $aData['token_bar']['closebutton']['url'] = 'admin/tokens/sa/index/surveyid/' . $iSurveyId;
     // Close button
     // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY
     $iSurveyId = sanitize_int($iSurveyId);
     if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'export')) {
         Yii::app()->session['flashmessage'] = gT("You do not have permission to access this page.");
         $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}"));
     }
     $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}');
     if (!$bTokenExists) {
         self::_newtokentable($iSurveyId);
     }
     if (!is_null(Yii::app()->request->getPost('submit'))) {
         Yii::app()->loadHelper("export");
         tokensExport($iSurveyId);
     } else {
         //$aData['resultr'] = Token::model($iSurveyId)->findAll(array('select' => 'language', 'group' => 'language'));
         $aData['surveyid'] = $iSurveyId;
         $aData['thissurvey'] = getSurveyInfo($iSurveyId);
         // For tokenbar view
         $aData['sAction'] = App()->createUrl("admin/tokens", array("sa" => "exportdialog", "surveyid" => $iSurveyId));
         $aData['aButtons'] = array(gT('Export tokens') => array('type' => 'submit', 'name' => 'submit'));
         $oSurvey = Survey::model()->findByPk($iSurveyId);
         $aOptionsStatus = array('0' => gT('All tokens'), '1' => gT('Completed'), '2' => gT('Not completed'));
         if ($oSurvey->anonymized == 'N' && $oSurvey->active == 'Y') {
             $aOptionsStatus['3'] = gT('Not started');
             $aOptionsStatus['4'] = gT('Started but not yet completed');
         }
         $oTokenLanguages = Token::model($iSurveyId)->findAll(array('select' => 'language', 'group' => 'language'));
         $aFilterByLanguage = array('' => gT('All'));
         foreach ($oTokenLanguages as $oTokenLanguage) {
             $sLanguageCode = sanitize_languagecode($oTokenLanguage->language);
             $aFilterByLanguage[$sLanguageCode] = getLanguageNameFromCode($sLanguageCode, false);
         }
         $aData['aSettings'] = array('tokenstatus' => array('type' => 'select', 'label' => gT('Survey status:'), 'options' => $aOptionsStatus), 'invitationstatus' => array('type' => 'select', 'label' => gT('Invitation status:'), 'options' => array('0' => gT('All'), '1' => gT('Invited'), '2' => gT('Not invited'))), 'reminderstatus' => array('type' => 'select', 'label' => gT('Reminder status:'), 'options' => array('0' => gT('All'), '1' => gT('Reminder(s) sent'), '2' => gT('No reminder(s) sent'))), 'tokenlanguage' => array('type' => 'select', 'label' => gT('Filter by language:'), 'options' => $aFilterByLanguage), 'filteremail' => array('type' => 'string', 'label' => gT('Filter by email address:'), 'help' => gT('Only export entries which contain this string in the email address.')), 'tokendeleteexported' => array('type' => 'checkbox', 'label' => gT('Delete exported tokens:'), 'help' => 'Attention: If selected the exported tokens are deleted permanently from the token table.'));
         $this->_renderWrappedTemplate('token', array('exportdialog'), $aData);
     }
 }
Exemplo n.º 15
0
    if (isset($_REQUEST['assessments']))
    {
        $assessments = ($_REQUEST['assessments'] == 'Y');
    }
    else
    {
        $assessments = ($surveyInfo[1] == 'Y');
    }
    $LEMdebugLevel = (
            ((isset($_REQUEST['LEM_DEBUG_TIMING']) && $_REQUEST['LEM_DEBUG_TIMING'] == 'Y') ? LEM_DEBUG_TIMING : 0) +
            ((isset($_REQUEST['LEM_DEBUG_VALIDATION_SUMMARY']) && $_REQUEST['LEM_DEBUG_VALIDATION_SUMMARY'] == 'Y') ? LEM_DEBUG_VALIDATION_SUMMARY : 0) +
            ((isset($_REQUEST['LEM_DEBUG_VALIDATION_DETAIL']) && $_REQUEST['LEM_DEBUG_VALIDATION_DETAIL'] == 'Y') ? LEM_DEBUG_VALIDATION_DETAIL : 0) +
            ((isset($_REQUEST['LEM_PRETTY_PRINT_ALL_SYNTAX']) && $_REQUEST['LEM_PRETTY_PRINT_ALL_SYNTAX'] == 'Y') ? LEM_PRETTY_PRINT_ALL_SYNTAX : 0)
            );

    $language = (isset($_REQUEST['lang']) ? sanitize_languagecode($_REQUEST['lang']) : NULL);
    $gid = (isset($_REQUEST['gid']) ? sanitize_int($_REQUEST['gid']) : NULL);
    $qid = (isset($_REQUEST['qid']) ? sanitize_int($_REQUEST['qid']) : NULL);

    print <<< EOD
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Logic File - Survey #$surveyid</title>
<style type="text/css">
tr.LEMgroup td
{
background-color:lightgrey;
}

tr.LEMquestion
Exemplo n.º 16
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);
     }
 }
Exemplo n.º 17
0
/**
* This function generates an array containing the fieldcode, and matching data in the same order as the activate script
*
* @param string $surveyid The Survey ID
* @param mixed $style 'short' (default) or 'full' - full creates extra information like default values
* @param mixed $force_refresh - Forces to really refresh the array, not just take the session copy
* @param int $questionid Limit to a certain qid only (for question preview) - default is false
* @param string $sQuestionLanguage The language to use
* @return array
*/
function createTimingsFieldMap($surveyid, $style = 'full', $force_refresh = false, $questionid = false, $sQuestionLanguage = null)
{
    global $aDuplicateQIDs;
    static $timingsFieldMap;
    $sLanguage = sanitize_languagecode($sQuestionLanguage);
    $surveyid = sanitize_int($surveyid);
    $sOldLanguage = App()->language;
    App()->setLanguage($sLanguage);
    //checks to see if fieldmap has already been built for this page.
    if (isset($timingsFieldMap[$surveyid][$style][$sLanguage]) && $force_refresh == false) {
        return $timingsFieldMap[$surveyid][$style][$sLanguage];
    }
    //do something
    $fields = createFieldMap($surveyid, $style, $force_refresh, $questionid, $sQuestionLanguage);
    $fieldmap['interviewtime'] = array('fieldname' => 'interviewtime', 'type' => 'interview_time', 'sid' => $surveyid, 'gid' => '', 'qid' => '', 'aid' => '', 'question' => gT('Total time'), 'title' => 'interviewtime');
    foreach ($fields as $field) {
        if (!empty($field['gid'])) {
            // field for time spent on page
            $fieldname = "{$field['sid']}X{$field['gid']}time";
            if (!isset($fieldmap[$fieldname])) {
                $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => "page_time", 'sid' => $surveyid, "gid" => $field['gid'], "group_name" => $field['group_name'], "qid" => '', 'aid' => '', 'title' => 'groupTime' . $field['gid'], 'question' => gT('Group time') . ": " . $field['group_name']);
            }
            // field for time spent on answering a question
            $fieldname = "{$field['sid']}X{$field['gid']}X{$field['qid']}time";
            if (!isset($fieldmap[$fieldname])) {
                $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => "answer_time", 'sid' => $surveyid, "gid" => $field['gid'], "group_name" => $field['group_name'], "qid" => $field['qid'], 'aid' => '', "title" => $field['title'] . 'Time', "question" => gT('Question time') . ": " . $field['title']);
            }
        }
    }
    $timingsFieldMap[$surveyid][$style][$sLanguage] = $fieldmap;
    App()->setLanguage($sOldLanguage);
    return $timingsFieldMap[$surveyid][$style][$sLanguage];
}
 /**
  * Sets the language settings for the user
  * @param CActiveRecord $user
  */
 private function _setLanguageSettings($user)
 {
     if (Yii::app()->request->getPost('loginlang', 'default') != 'default') {
         $user->lang = sanitize_languagecode(Yii::app()->request->getPost('loginlang'));
         $user->save();
         $sLanguage = $user->lang;
     } else {
         if ($user->lang == 'auto' || $user->lang == '') {
             $sLanguage = getBrowserLanguage();
         } else {
             $sLanguage = $user->lang;
         }
     }
     Yii::app()->session['adminlang'] = $sLanguage;
     $this->getController()->lang = new limesurvey_lang($sLanguage);
 }
Exemplo n.º 19
0
/**
* This function generates an array containing the fieldcode, and matching data in the same order as the activate script
*
* @param string $surveyid The Survey ID
* @param mixed $style 'short' (default) or 'full' - full creates extra information like default values
* @param mixed $force_refresh - Forces to really refresh the array, not just take the session copy
* @param int $questionid Limit to a certain qid only (for question preview) - default is false
* @return array
*/
function createFieldMap($surveyid, $style = 'short', $force_refresh = false, $questionid = false, $sLanguage)
{
    global $aDuplicateQIDs;
    $sLanguage = sanitize_languagecode($sLanguage);
    $surveyid = sanitize_int($surveyid);
    $clang = new Limesurvey_lang($sLanguage);
    //checks to see if fieldmap has already been built for this page.
    if (isset(Yii::app()->session['fieldmap-' . $surveyid . $sLanguage]) && !$force_refresh && $questionid == false) {
        return Yii::app()->session['fieldmap-' . $surveyid . $sLanguage];
    }
    $fieldmap["id"] = array("fieldname" => "id", 'sid' => $surveyid, 'type' => "id", "gid" => "", "qid" => "", "aid" => "");
    if ($style == "full") {
        $fieldmap["id"]['title'] = "";
        $fieldmap["id"]['question'] = $clang->gT("Response ID");
        $fieldmap["id"]['group_name'] = "";
    }
    $fieldmap["submitdate"] = array("fieldname" => "submitdate", 'type' => "submitdate", 'sid' => $surveyid, "gid" => "", "qid" => "", "aid" => "");
    if ($style == "full") {
        $fieldmap["submitdate"]['title'] = "";
        $fieldmap["submitdate"]['question'] = $clang->gT("Date submitted");
        $fieldmap["submitdate"]['group_name'] = "";
    }
    $fieldmap["lastpage"] = array("fieldname" => "lastpage", 'sid' => $surveyid, 'type' => "lastpage", "gid" => "", "qid" => "", "aid" => "");
    if ($style == "full") {
        $fieldmap["lastpage"]['title'] = "";
        $fieldmap["lastpage"]['question'] = $clang->gT("Last page");
        $fieldmap["lastpage"]['group_name'] = "";
    }
    $fieldmap["startlanguage"] = array("fieldname" => "startlanguage", 'sid' => $surveyid, 'type' => "startlanguage", "gid" => "", "qid" => "", "aid" => "");
    if ($style == "full") {
        $fieldmap["startlanguage"]['title'] = "";
        $fieldmap["startlanguage"]['question'] = $clang->gT("Start language");
        $fieldmap["startlanguage"]['group_name'] = "";
    }
    // Select which question IDs have default values
    $_aDefaultValues = Defaultvalues::model()->with(array('question' => array('condition' => 'question.sid=' . $surveyid)))->findAll();
    $aDefaultValues = array();
    foreach ($_aDefaultValues as $k => $v) {
        $aDefaultValues[] = $v->qid;
    }
    //Check for any additional fields for this survey and create necessary fields (token and datestamp and ipaddr)
    $prow = Survey::model()->findByPk($surveyid)->getAttributes();
    //Checked
    if ($prow['anonymized'] == "N") {
        $fieldmap["token"] = array("fieldname" => "token", 'sid' => $surveyid, 'type' => "token", "gid" => "", "qid" => "", "aid" => "");
        if ($style == "full") {
            $fieldmap["token"]['title'] = "";
            $fieldmap["token"]['question'] = $clang->gT("Token");
            $fieldmap["token"]['group_name'] = "";
        }
    }
    if ($prow['datestamp'] == "Y") {
        $fieldmap["startdate"] = array("fieldname" => "startdate", 'type' => "startdate", 'sid' => $surveyid, "gid" => "", "qid" => "", "aid" => "");
        if ($style == "full") {
            $fieldmap["startdate"]['title'] = "";
            $fieldmap["startdate"]['question'] = $clang->gT("Date started");
            $fieldmap["startdate"]['group_name'] = "";
        }
        $fieldmap["datestamp"] = array("fieldname" => "datestamp", 'type' => "datestamp", 'sid' => $surveyid, "gid" => "", "qid" => "", "aid" => "");
        if ($style == "full") {
            $fieldmap["datestamp"]['title'] = "";
            $fieldmap["datestamp"]['question'] = $clang->gT("Date last action");
            $fieldmap["datestamp"]['group_name'] = "";
        }
    }
    if ($prow['ipaddr'] == "Y") {
        $fieldmap["ipaddr"] = array("fieldname" => "ipaddr", 'type' => "ipaddress", 'sid' => $surveyid, "gid" => "", "qid" => "", "aid" => "");
        if ($style == "full") {
            $fieldmap["ipaddr"]['title'] = "";
            $fieldmap["ipaddr"]['question'] = $clang->gT("IP address");
            $fieldmap["ipaddr"]['group_name'] = "";
        }
    }
    // Add 'refurl' to fieldmap.
    if ($prow['refurl'] == "Y") {
        $fieldmap["refurl"] = array("fieldname" => "refurl", 'type' => "url", 'sid' => $surveyid, "gid" => "", "qid" => "", "aid" => "");
        if ($style == "full") {
            $fieldmap["refurl"]['title'] = "";
            $fieldmap["refurl"]['question'] = $clang->gT("Referrer URL");
            $fieldmap["refurl"]['group_name'] = "";
        }
    }
    // Collect all default values once so don't need separate query for each question with defaults
    // First collect language specific defaults
    $defaultsQuery = "SELECT a.qid, a.sqid, a.scale_id, a.specialtype, a.defaultvalue" . " FROM {{defaultvalues}} as a, {{questions}} as b" . " WHERE a.qid = b.qid" . " AND a.language = b.language" . " AND a.language = '{$sLanguage}'" . " AND b.same_default=0" . " AND b.sid = " . $surveyid;
    $defaultResults = Yii::app()->db->createCommand($defaultsQuery)->queryAll();
    $defaultValues = array();
    // indexed by question then subquestion
    foreach ($defaultResults as $dv) {
        if ($dv['specialtype'] != '') {
            $sq = $dv['specialtype'];
        } else {
            $sq = $dv['sqid'];
        }
        $defaultValues[$dv['qid'] . '~' . $sq] = $dv['defaultvalue'];
    }
    // Now overwrite language-specific defaults (if any) base language values for each question that uses same_defaults=1
    $baseLanguage = getBaseLanguageFromSurveyID($surveyid);
    $defaultsQuery = "SELECT a.qid, a.sqid, a.scale_id, a.specialtype, a.defaultvalue" . " FROM {{defaultvalues}} as a, {{questions}} as b" . " WHERE a.qid = b.qid" . " AND a.language = b.language" . " AND a.language = '{$baseLanguage}'" . " AND b.same_default=1" . " AND b.sid = " . $surveyid;
    $defaultResults = Yii::app()->db->createCommand($defaultsQuery)->queryAll();
    foreach ($defaultResults as $dv) {
        if ($dv['specialtype'] != '') {
            $sq = $dv['specialtype'];
        } else {
            $sq = $dv['sqid'];
        }
        $defaultValues[$dv['qid'] . '~' . $sq] = $dv['defaultvalue'];
    }
    $qtypes = getQuestionTypeList('', 'array');
    $aquery = "SELECT * " . " FROM {{questions}} as questions, {{groups}} as groups" . " WHERE questions.gid=groups.gid AND " . " questions.sid={$surveyid} AND " . " questions.language='{$sLanguage}' AND " . " questions.parent_qid=0 AND " . " groups.language='{$sLanguage}' ";
    if ($questionid !== false) {
        $aquery .= " and questions.qid={$questionid} ";
    }
    $aquery .= " ORDER BY group_order, question_order";
    $aresult = Yii::app()->db->createCommand($aquery)->queryAll();
    $questionSeq = -1;
    // this is incremental question sequence across all groups
    $groupSeq = -1;
    $_groupOrder = -1;
    foreach ($aresult as $arow) {
        ++$questionSeq;
        // fix fact taht group_order may have gaps
        if ($_groupOrder != $arow['group_order']) {
            $_groupOrder = $arow['group_order'];
            ++$groupSeq;
        }
        // Conditions indicators are obsolete with EM.  However, they are so tightly coupled into LS code that easider to just set values to 'N' for now and refactor later.
        $conditions = 'N';
        $usedinconditions = 'N';
        // Field identifier
        // GXQXSXA
        // G=Group  Q=Question S=Subquestion A=Answer Option
        // If S or A don't exist then set it to 0
        // Implicit (subqestion intermal to a question type ) or explicit qubquestions/answer count starts at 1
        // Types "L", "!", "O", "D", "G", "N", "X", "Y", "5", "S", "T", "U"
        $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}";
        if ($qtypes[$arow['type']]['subquestions'] == 0 && $arow['type'] != "R" && $arow['type'] != "|") {
            if (isset($fieldmap[$fieldname])) {
                $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
            }
            $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => "{$arow['type']}", 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => "");
            if ($style == "full") {
                $fieldmap[$fieldname]['title'] = $arow['title'];
                $fieldmap[$fieldname]['question'] = $arow['question'];
                $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                $fieldmap[$fieldname]['hasconditions'] = $conditions;
                $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                if (isset($defaultValues[$arow['qid'] . '~0'])) {
                    $fieldmap[$fieldname]['defaultvalue'] = $defaultValues[$arow['qid'] . '~0'];
                }
            }
            switch ($arow['type']) {
                case "L":
                    //RADIO LIST
                //RADIO LIST
                case "!":
                    //DROPDOWN LIST
                    if ($arow['other'] == "Y") {
                        $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}other";
                        if (isset($fieldmap[$fieldname])) {
                            $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                        }
                        $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => "other");
                        // dgk bug fix line above. aid should be set to "other" for export to append to the field name in the header line.
                        if ($style == "full") {
                            $fieldmap[$fieldname]['title'] = $arow['title'];
                            $fieldmap[$fieldname]['question'] = $arow['question'];
                            $fieldmap[$fieldname]['subquestion'] = $clang->gT("Other");
                            $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                            $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                            $fieldmap[$fieldname]['hasconditions'] = $conditions;
                            $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                            $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                            $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                            if (isset($defaultValues[$arow['qid'] . '~other'])) {
                                $fieldmap[$fieldname]['defaultvalue'] = $defaultValues[$arow['qid'] . '~other'];
                            }
                        }
                    }
                    break;
                case "O":
                    //DROPDOWN LIST WITH COMMENT
                    $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}comment";
                    if (isset($fieldmap[$fieldname])) {
                        $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                    }
                    $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => "comment");
                    // dgk bug fix line below. aid should be set to "comment" for export to append to the field name in the header line. Also needed set the type element correctly.
                    if ($style == "full") {
                        $fieldmap[$fieldname]['title'] = $arow['title'];
                        $fieldmap[$fieldname]['question'] = $arow['question'];
                        $fieldmap[$fieldname]['subquestion'] = $clang->gT("Comment");
                        $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                        $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                        $fieldmap[$fieldname]['hasconditions'] = $conditions;
                        $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                        $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                        $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                    }
                    break;
            }
        } elseif ($qtypes[$arow['type']]['subquestions'] == 2 && $qtypes[$arow['type']]['answerscales'] == 0) {
            //MULTI FLEXI
            $abrows = getSubQuestions($surveyid, $arow['qid'], $sLanguage);
            //Now first process scale=1
            $answerset = array();
            $answerList = array();
            foreach ($abrows as $key => $abrow) {
                if ($abrow['scale_id'] == 1) {
                    $answerset[] = $abrow;
                    $answerList[] = array('code' => $abrow['title'], 'answer' => $abrow['question']);
                    unset($abrows[$key]);
                }
            }
            reset($abrows);
            foreach ($abrows as $abrow) {
                foreach ($answerset as $answer) {
                    $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['title']}_{$answer['title']}";
                    if (isset($fieldmap[$fieldname])) {
                        $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                    }
                    $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => $abrow['title'] . "_" . $answer['title'], "sqid" => $abrow['qid']);
                    if ($abrow['other'] == "Y") {
                        $alsoother = "Y";
                    }
                    if ($style == "full") {
                        $fieldmap[$fieldname]['title'] = $arow['title'];
                        $fieldmap[$fieldname]['question'] = $arow['question'];
                        $fieldmap[$fieldname]['subquestion1'] = $abrow['question'];
                        $fieldmap[$fieldname]['subquestion2'] = $answer['question'];
                        $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                        $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                        $fieldmap[$fieldname]['hasconditions'] = $conditions;
                        $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                        $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                        $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                        $fieldmap[$fieldname]['preg'] = $arow['preg'];
                        $fieldmap[$fieldname]['answerList'] = $answerList;
                    }
                }
            }
            unset($answerset);
        } elseif ($arow['type'] == "1") {
            $abrows = getSubQuestions($surveyid, $arow['qid'], $sLanguage);
            foreach ($abrows as $abrow) {
                $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['title']}#0";
                if (isset($fieldmap[$fieldname])) {
                    $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                }
                $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => $abrow['title'], "scale_id" => 0);
                if ($style == "full") {
                    $fieldmap[$fieldname]['title'] = $arow['title'];
                    $fieldmap[$fieldname]['question'] = $arow['question'];
                    $fieldmap[$fieldname]['subquestion'] = $abrow['question'];
                    $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                    $fieldmap[$fieldname]['scale'] = $clang->gT('Scale 1');
                    $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                    $fieldmap[$fieldname]['hasconditions'] = $conditions;
                    $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                    $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                    $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                }
                $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['title']}#1";
                if (isset($fieldmap[$fieldname])) {
                    $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                }
                $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => $abrow['title'], "scale_id" => 1);
                if ($style == "full") {
                    $fieldmap[$fieldname]['title'] = $arow['title'];
                    $fieldmap[$fieldname]['question'] = $arow['question'];
                    $fieldmap[$fieldname]['subquestion'] = $abrow['question'];
                    $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                    $fieldmap[$fieldname]['scale'] = $clang->gT('Scale 2');
                    $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                    $fieldmap[$fieldname]['hasconditions'] = $conditions;
                    $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                    $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                    $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                }
            }
        } elseif ($arow['type'] == "R") {
            //MULTI ENTRY
            $data = Answers::model()->findAllByAttributes(array('qid' => $arow['qid'], 'language' => $sLanguage));
            $data = count($data);
            $slots = $data;
            for ($i = 1; $i <= $slots; $i++) {
                $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$i}";
                if (isset($fieldmap[$fieldname])) {
                    $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                }
                $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => $i);
                if ($style == "full") {
                    $fieldmap[$fieldname]['title'] = $arow['title'];
                    $fieldmap[$fieldname]['question'] = $arow['question'];
                    $fieldmap[$fieldname]['subquestion'] = sprintf($clang->gT('Rank %s'), $i);
                    $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                    $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                    $fieldmap[$fieldname]['hasconditions'] = $conditions;
                    $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                    $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                    $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                }
            }
        } elseif ($arow['type'] == "|") {
            $qidattributes = getQuestionAttributeValues($arow['qid']);
            $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}";
            $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => '');
            if ($style == "full") {
                $fieldmap[$fieldname]['title'] = $arow['title'];
                $fieldmap[$fieldname]['question'] = $arow['question'];
                $fieldmap[$fieldname]['max_files'] = $qidattributes['max_num_of_files'];
                $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                $fieldmap[$fieldname]['hasconditions'] = $conditions;
                $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
            }
            $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}" . "_filecount";
            $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => "filecount");
            if ($style == "full") {
                $fieldmap[$fieldname]['title'] = $arow['title'];
                $fieldmap[$fieldname]['question'] = "filecount - " . $arow['question'];
                $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                $fieldmap[$fieldname]['hasconditions'] = $conditions;
                $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
            }
        } else {
            //MULTI ENTRY
            $abrows = getSubQuestions($surveyid, $arow['qid'], $sLanguage);
            foreach ($abrows as $abrow) {
                $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['title']}";
                if (isset($fieldmap[$fieldname])) {
                    $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                }
                $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, 'gid' => $arow['gid'], 'qid' => $arow['qid'], 'aid' => $abrow['title'], 'sqid' => $abrow['qid']);
                if ($style == "full") {
                    $fieldmap[$fieldname]['title'] = $arow['title'];
                    $fieldmap[$fieldname]['question'] = $arow['question'];
                    $fieldmap[$fieldname]['subquestion'] = $abrow['question'];
                    $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                    $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                    $fieldmap[$fieldname]['hasconditions'] = $conditions;
                    $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                    $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                    $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                    $fieldmap[$fieldname]['preg'] = $arow['preg'];
                    if (isset($defaultValues[$arow['qid'] . '~' . $abrow['qid']])) {
                        $fieldmap[$fieldname]['defaultvalue'] = $defaultValues[$arow['qid'] . '~' . $abrow['qid']];
                    }
                }
                if ($arow['type'] == "P") {
                    $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['title']}comment";
                    if (isset($fieldmap[$fieldname])) {
                        $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                    }
                    $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => $abrow['title'] . "comment");
                    if ($style == "full") {
                        $fieldmap[$fieldname]['title'] = $arow['title'];
                        $fieldmap[$fieldname]['question'] = $arow['question'];
                        $fieldmap[$fieldname]['subquestion'] = $clang->gT('Comment');
                        $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                        $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                        $fieldmap[$fieldname]['hasconditions'] = $conditions;
                        $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                        $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                        $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                    }
                }
            }
            if ($arow['other'] == "Y" && ($arow['type'] == "M" || $arow['type'] == "P")) {
                $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}other";
                if (isset($fieldmap[$fieldname])) {
                    $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                }
                $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => "other");
                if ($style == "full") {
                    $fieldmap[$fieldname]['title'] = $arow['title'];
                    $fieldmap[$fieldname]['question'] = $arow['question'];
                    $fieldmap[$fieldname]['subquestion'] = $clang->gT('Other');
                    $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                    $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                    $fieldmap[$fieldname]['hasconditions'] = $conditions;
                    $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                    $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                    $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                    $fieldmap[$fieldname]['other'] = $arow['other'];
                }
                if ($arow['type'] == "P") {
                    $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}othercomment";
                    if (isset($fieldmap[$fieldname])) {
                        $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']);
                    }
                    $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => "othercomment");
                    if ($style == "full") {
                        $fieldmap[$fieldname]['title'] = $arow['title'];
                        $fieldmap[$fieldname]['question'] = $arow['question'];
                        $fieldmap[$fieldname]['subquestion'] = $clang->gT('Other comment');
                        $fieldmap[$fieldname]['group_name'] = $arow['group_name'];
                        $fieldmap[$fieldname]['mandatory'] = $arow['mandatory'];
                        $fieldmap[$fieldname]['hasconditions'] = $conditions;
                        $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions;
                        $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
                        $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
                        $fieldmap[$fieldname]['other'] = $arow['other'];
                    }
                }
            }
        }
        if (isset($fieldmap[$fieldname])) {
            $fieldmap[$fieldname]['relevance'] = $arow['relevance'];
            $fieldmap[$fieldname]['grelevance'] = $arow['grelevance'];
            $fieldmap[$fieldname]['questionSeq'] = $questionSeq;
            $fieldmap[$fieldname]['groupSeq'] = $groupSeq;
            $fieldmap[$fieldname]['preg'] = $arow['preg'];
            $fieldmap[$fieldname]['other'] = $arow['other'];
            $fieldmap[$fieldname]['help'] = $arow['help'];
        } else {
            --$questionSeq;
            // didn't generate a valid $fieldmap entry, so decrement the question counter to ensure they are sequential
        }
    }
    if (isset($fieldmap)) {
        if ($questionid == false) {
            // If the fieldmap was randomized, the master will contain the proper order.  Copy that fieldmap with the new language settings.
            if (isset(Yii::app()->session['fieldmap-' . $surveyid . '-randMaster'])) {
                $masterFieldmap = Yii::app()->session['fieldmap-' . $surveyid . '-randMaster'];
                $mfieldmap = Yii::app()->session[$masterFieldmap];
                foreach ($mfieldmap as $fieldname => $mf) {
                    if (isset($fieldmap[$fieldname])) {
                        $f = $fieldmap[$fieldname];
                        if (isset($f['question'])) {
                            $mf['question'] = $f['question'];
                        }
                        if (isset($f['subquestion'])) {
                            $mf['subquestion'] = $f['subquestion'];
                        }
                        if (isset($f['subquestion1'])) {
                            $mf['subquestion1'] = $f['subquestion1'];
                        }
                        if (isset($f['subquestion2'])) {
                            $mf['subquestion2'] = $f['subquestion2'];
                        }
                        if (isset($f['group_name'])) {
                            $mf['group_name'] = $f['group_name'];
                        }
                        if (isset($f['answerList'])) {
                            $mf['answerList'] = $f['answerList'];
                        }
                        if (isset($f['defaultvalue'])) {
                            $mf['defaultvalue'] = $f['defaultvalue'];
                        }
                        if (isset($f['help'])) {
                            $mf['help'] = $f['help'];
                        }
                    }
                    $mfieldmap[$fieldname] = $mf;
                }
                $fieldmap = $mfieldmap;
            }
            Yii::app()->session['fieldmap-' . $surveyid . $sLanguage] = $fieldmap;
        }
        return $fieldmap;
    }
}
Exemplo n.º 20
0
 */
// Security Checked: POST, GET, SESSION, REQUEST, returnglobal, DB
if (isset($_REQUEST['homedir'])) {
    die('You cannot start this script directly');
}
include_once "login_check.php";
//Login Check dies also if the script is started directly
require_once $homedir . "/classes/core/sha256.php";
if (isset($_POST['user'])) {
    $postuser = sanitize_user($_POST['user']);
}
if (isset($_POST['email'])) {
    $postemail = sanitize_email($_POST['email']);
}
if (isset($_POST['loginlang'])) {
    $postloginlang = sanitize_languagecode($_POST['loginlang']);
}
if (isset($_POST['new_user'])) {
    $postnew_user = sanitize_user($_POST['new_user']);
}
if (isset($_POST['new_email'])) {
    $postnew_email = sanitize_email($_POST['new_email']);
}
if (isset($_POST['new_full_name'])) {
    $postnew_full_name = sanitize_userfullname($_POST['new_full_name']);
}
if (isset($_POST['uid'])) {
    $postuserid = sanitize_int($_POST['uid']);
}
if (isset($_POST['full_name'])) {
    $postfull_name = sanitize_userfullname($_POST['full_name']);
Exemplo n.º 21
0
 function actionparticipants()
 {
     $iSurveyID = Yii::app()->request->getQuery('surveyid');
     $sLanguageCode = Yii::app()->request->getQuery('langcode');
     $sToken = sanitize_token(Yii::app()->request->getQuery('token'));
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('sanitize');
     if (!$iSurveyID) {
         $this->redirect(array('/'));
     }
     $iSurveyID = (int) $iSurveyID;
     //Make sure it's an integer (protect from SQL injects)
     //Check that there is a SID
     // Get passed language from form, so that we dont lose this!
     if (!isset($sLanguageCode) || $sLanguageCode == "" || !$sLanguageCode) {
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
         Yii::import('application.libraries.Limesurvey_lang', true);
         $clang = new Limesurvey_lang($sBaseLanguage);
     } else {
         $sLanguageCode = sanitize_languagecode($sLanguageCode);
         Yii::import('application.libraries.Limesurvey_lang', true);
         $clang = new Limesurvey_lang($sLanguageCode);
         $sBaseLanguage = $sLanguageCode;
     }
     Yii::app()->lang = $clang;
     $aSurveyInfo = getSurveyInfo($iSurveyID, $sBaseLanguage);
     if ($aSurveyInfo == false || !tableExists("{{tokens_{$iSurveyID}}}")) {
         $sMessage = $clang->gT('This survey does not seem to exist.');
     } else {
         $oToken = Token::model($iSurveyID)->findByAttributes(array('token' => $sToken));
         if (!isset($oToken)) {
             $sMessage = $clang->gT('You are not a participant in this survey.');
         } else {
             if (substr($oToken->emailstatus, 0, strlen('OptOut')) !== 'OptOut') {
                 $oToken->emailstatus = 'OptOut';
                 $oToken->save();
                 $sMessage = $clang->gT('You have been successfully removed from this survey.');
             } else {
                 $sMessage = $clang->gT('You have been already removed from this survey.');
             }
             if (!empty($oToken->participant_id)) {
                 //Participant also exists in central db
                 $oParticipant = Participant::model()->findByPk($oToken->participant_id);
                 if ($oParticipant->blacklisted == "Y") {
                     $sMessage .= "<br />";
                     $sMessage .= $clang->gT("You have already been removed from the central participants list for this site");
                 } else {
                     $oParticipant->blacklisted = 'Y';
                     $oParticipant->save();
                     $sMessage .= "<br />";
                     $sMessage .= $clang->gT("You have been removed from the central participants list for this site");
                 }
             }
         }
     }
     //PRINT COMPLETED PAGE
     if (!$aSurveyInfo['templatedir']) {
         $sTemplate = getTemplatePath(Yii::app()->getConfig("defaulttemplate"));
     } else {
         $sTemplate = getTemplatePath($aSurveyInfo['templatedir']);
     }
     $this->_renderHtml($sMessage, $sTemplate, $aSurveyInfo);
 }
 function actionAction($surveyid, $language = null)
 {
     $sLanguage = $language;
     ob_start(function ($buffer, $phase) {
         App()->getClientScript()->render($buffer);
         App()->getClientScript()->reset();
         return $buffer;
     });
     ob_implicit_flush(false);
     $iSurveyID = (int) $surveyid;
     //$postlang = returnglobal('lang');
     Yii::import('application.libraries.admin.progressbar', true);
     Yii::app()->loadHelper("admin/statistics");
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('surveytranslator');
     App()->getClientScript()->registerPackage('jqueryui');
     App()->getClientScript()->registerPackage('jquery-touch-punch');
     App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "survey_runtime.js");
     $data = array();
     if (!isset($iSurveyID)) {
         $iSurveyID = returnGlobal('sid');
     } else {
         $iSurveyID = (int) $iSurveyID;
     }
     if (!$iSurveyID) {
         //This next line ensures that the $iSurveyID value is never anything but a number.
         safeDie('You have to provide a valid survey ID.');
     }
     if ($iSurveyID) {
         $actresult = Survey::model()->findAll('sid = :sid AND active = :active', array(':sid' => $iSurveyID, ':active' => 'Y'));
         //Checked
         if (count($actresult) == 0) {
             safeDie('You have to provide a valid survey ID.');
         } else {
             $surveyinfo = getSurveyInfo($iSurveyID);
             // CHANGE JSW_NZ - let's get the survey title for display
             $thisSurveyTitle = $surveyinfo["name"];
             // CHANGE JSW_NZ - let's get css from individual template.css - so define path
             $thisSurveyCssPath = getTemplateURL($surveyinfo["template"]);
             if ($surveyinfo['publicstatistics'] != 'Y') {
                 safeDie('The public statistics for this survey are deactivated.');
             }
             //check if graphs should be shown for this survey
             if ($surveyinfo['publicgraphs'] == 'Y') {
                 $publicgraphs = 1;
             } else {
                 $publicgraphs = 0;
             }
         }
     }
     //we collect all the output within this variable
     $statisticsoutput = '';
     //for creating graphs we need some more scripts which are included here
     //True -> include
     //False -> forget about charts
     if (isset($publicgraphs) && $publicgraphs == 1) {
         require_once APPPATH . 'third_party/pchart/pchart/pChart.class';
         require_once APPPATH . 'third_party/pchart/pchart/pData.class';
         require_once APPPATH . 'third_party/pchart/pchart/pCache.class';
         $MyCache = new pCache(Yii::app()->getConfig("tempdir") . DIRECTORY_SEPARATOR);
         //$currentuser is created as prefix for pchart files
         if (isset($_SERVER['REDIRECT_REMOTE_USER'])) {
             $currentuser = $_SERVER['REDIRECT_REMOTE_USER'];
         } else {
             if (session_id()) {
                 $currentuser = substr(session_id(), 0, 15);
             } else {
                 $currentuser = "******";
             }
         }
     }
     // Set language for questions and labels to base language of this survey
     if ($sLanguage == null || !in_array($sLanguage, Survey::model()->findByPk($iSurveyID)->getAllLanguages())) {
         $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
     } else {
         $sLanguage = sanitize_languagecode($sLanguage);
     }
     //set survey language for translations
     SetSurveyLanguage($iSurveyID, $sLanguage);
     //Create header
     sendCacheHeaders();
     $condition = false;
     $sitename = Yii::app()->getConfig("sitename");
     $data['surveylanguage'] = $sLanguage;
     $data['sitename'] = $sitename;
     $data['condition'] = $condition;
     $data['thisSurveyCssPath'] = $thisSurveyCssPath;
     /*
      * only show questions where question attribute "public_statistics" is set to "1"
      */
     $query = "SELECT q.* , group_name, group_order FROM {{questions}} q, {{groups}} g, {{question_attributes}} qa\n                    WHERE g.gid = q.gid AND g.language = :lang1 AND q.language = :lang2 AND q.sid = :surveyid AND q.qid = qa.qid AND q.parent_qid = 0 AND qa.attribute = 'public_statistics'";
     $databasetype = Yii::app()->db->getDriverName();
     if ($databasetype == 'mssql' || $databasetype == "sqlsrv" || $databasetype == "dblib") {
         $query .= " AND CAST(CAST(qa.value as varchar) as int)='1'\n";
     } else {
         $query .= " AND qa.value='1'\n";
     }
     //execute query
     $result = Yii::app()->db->createCommand($query)->bindParam(":lang1", $sLanguage, PDO::PARAM_STR)->bindParam(":lang2", $sLanguage, PDO::PARAM_STR)->bindParam(":surveyid", $iSurveyID, PDO::PARAM_INT)->queryAll();
     //store all the data in $rows
     $rows = $result;
     //SORT IN NATURAL ORDER!
     usort($rows, 'groupOrderThenQuestionOrder');
     //put the question information into the filter array
     foreach ($rows as $row) {
         //store some column names in $filters array
         $filters[] = array($row['qid'], $row['gid'], $row['type'], $row['title'], $row['group_name'], flattenText($row['question']));
     }
     //number of records for this survey
     $totalrecords = 0;
     //count number of answers
     $query = "SELECT count(*) FROM {{survey_" . intval($iSurveyID) . "}}";
     //if incompleted answers should be filtert submitdate has to be not null
     //this setting is taken from config-defaults.php
     if (Yii::app()->getConfig("filterout_incomplete_answers") == true) {
         $query .= " WHERE {{survey_" . intval($iSurveyID) . "}}.submitdate is not null";
     }
     $result = Yii::app()->db->createCommand($query)->queryAll();
     //$totalrecords = total number of answers
     foreach ($result as $row) {
         $totalrecords = reset($row);
     }
     //this is the array which we need later...
     $summary = array();
     //...while this is the array from copy/paste which we don't want to replace because this is a nasty source of error
     $allfields = array();
     //---------- CREATE SGQA OF ALL QUESTIONS WHICH USE "PUBLIC_STATISTICS" ----------
     /*
              * let's go through the filter array which contains
              *     ['qid'],
              ['gid'],
              ['type'],
              ['title'],
              ['group_name'],
              ['question'];
     */
     $currentgroup = '';
     // use to check if there are any question with public statistics
     if (isset($filters)) {
         foreach ($filters as $flt) {
             //SGQ identifier
             $myfield = "{$iSurveyID}X{$flt[1]}X{$flt[0]}";
             //let's switch through the question type for each question
             switch ($flt[2]) {
                 case "K":
                     // Multiple Numerical
                 // Multiple Numerical
                 case "Q":
                     // Multiple Short Text
                     //get answers
                     $query = "SELECT title as code, question as answer FROM {{questions}} WHERE parent_qid=:flt_0 AND language = :lang ORDER BY question_order";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     //go through all the (multiple) answers
                     foreach ($result as $row) {
                         $myfield2 = $flt[2] . $myfield . reset($row);
                         $allfields[] = $myfield2;
                     }
                     break;
                 case "A":
                     // ARRAY OF 5 POINT CHOICE QUESTIONS
                 // ARRAY OF 5 POINT CHOICE QUESTIONS
                 case "B":
                     // ARRAY OF 10 POINT CHOICE QUESTIONS
                 // ARRAY OF 10 POINT CHOICE QUESTIONS
                 case "C":
                     // ARRAY OF YES\No\gT("Uncertain") QUESTIONS
                 // ARRAY OF YES\No\gT("Uncertain") QUESTIONS
                 case "E":
                     // ARRAY OF Increase/Same/Decrease QUESTIONS
                 // ARRAY OF Increase/Same/Decrease QUESTIONS
                 case "F":
                     // FlEXIBLE ARRAY
                 // FlEXIBLE ARRAY
                 case "H":
                     // ARRAY (By Column)
                     //get answers
                     $query = "SELECT title as code, question as answer FROM {{questions}} WHERE parent_qid=:flt_0 AND language = :lang ORDER BY question_order";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     //go through all the (multiple) answers
                     foreach ($result as $row) {
                         $myfield2 = $myfield . reset($row);
                         $allfields[] = $myfield2;
                     }
                     break;
                     // all "free text" types (T, U, S)  get the same prefix ("T")
                 // all "free text" types (T, U, S)  get the same prefix ("T")
                 case "T":
                     // Long free text
                 // Long free text
                 case "U":
                     // Huge free text
                 // Huge free text
                 case "S":
                     // Short free text
                     $myfield = "T{$myfield}";
                     $allfields[] = $myfield;
                     break;
                 case ";":
                     //ARRAY (Multi Flex) (Text)
                 //ARRAY (Multi Flex) (Text)
                 case ":":
                     //ARRAY (Multi Flex) (Numbers)
                     $query = "SELECT title, question FROM {{questions}} WHERE parent_qid=:flt_0 AND language=:lang AND scale_id = 0 ORDER BY question_order";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     foreach ($result as $row) {
                         $fquery = "SELECT * FROM {{questions}} WHERE parent_qid = :flt_0 AND language = :lang AND scale_id = 1 ORDER BY question_order, title";
                         $fresult = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                         foreach ($fresult as $frow) {
                             $myfield2 = $myfield . reset($row) . "_" . $frow['title'];
                             $allfields[] = $myfield2;
                         }
                     }
                     break;
                 case "R":
                     //RANKING
                     //get some answers
                     $query = "SELECT code, answer FROM {{answers}} WHERE qid = :flt_0 AND language = :lang ORDER BY sortorder, answer";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     //get number of answers
                     $count = count($result);
                     //loop through all answers. if there are 3 items to rate there will be 3 statistics
                     for ($i = 1; $i <= $count; $i++) {
                         $myfield2 = "R" . $myfield . $i . "-" . strlen($i);
                         $allfields[] = $myfield2;
                     }
                     break;
                     //Boilerplate questions are only used to put some text between other questions -> no analysis needed
                 //Boilerplate questions are only used to put some text between other questions -> no analysis needed
                 case "X":
                     //This is a boilerplate question and it has no business in this script
                     break;
                 case "1":
                     // MULTI SCALE
                     //get answers
                     $query = "SELECT title, question FROM {{questions}} WHERE parent_qid = :flt_0 AND language = :lang ORDER BY question_order";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->queryAll();
                     //loop through answers
                     foreach ($result as $row) {
                         //----------------- LABEL 1 ---------------------
                         $myfield2 = $myfield . $row['title'] . "#0";
                         $allfields[] = $myfield2;
                         //----------------- LABEL 2 ---------------------
                         $myfield2 = $myfield . $row['title'] . "#1";
                         $allfields[] = $myfield2;
                     }
                     //end WHILE -> loop through all answers
                     break;
                 case "P":
                     //P - Multiple choice with comments
                 //P - Multiple choice with comments
                 case "M":
                     //M - Multiple choice
                 //M - Multiple choice
                 case "N":
                     //N - Numerical input
                 //N - Numerical input
                 case "D":
                     //D - Date
                     $myfield2 = $flt[2] . $myfield;
                     $allfields[] = $myfield2;
                     break;
                 default:
                     //Default settings
                     $allfields[] = $myfield;
                     break;
             }
             //end switch -> check question types and create filter forms
         }
         //end foreach -> loop through all questions with "public_statistics" enabled
     }
     // end if -> for removing the error message in case there are no filters
     $summary = $allfields;
     // Get the survey inforamtion
     $thissurvey = getSurveyInfo($surveyid, $sLanguage);
     //SET THE TEMPLATE DIRECTORY
     $data['sTemplatePath'] = $surveyinfo['template'];
     // surveyinfo=getSurveyInfo and if survey don't exist : stop before.
     //---------- CREATE STATISTICS ----------
     $redata = compact(array_keys(get_defined_vars()));
     doHeader();
     echo templatereplace(file_get_contents(getTemplatePath($data['sTemplatePath']) . DIRECTORY_SEPARATOR . "startpage.pstpl"), array(), $redata);
     //some progress bar stuff
     // Create progress bar which is shown while creating the results
     $prb = new ProgressBar();
     $prb->pedding = 2;
     // Bar Pedding
     $prb->brd_color = "#404040 #dfdfdf #dfdfdf #404040";
     // Bar Border Color
     $prb->setFrame();
     // set ProgressBar Frame
     $prb->frame['left'] = 50;
     // Frame position from left
     $prb->frame['top'] = 80;
     // Frame position from top
     $prb->addLabel('text', 'txt1', gT("Please wait ..."));
     // add Text as Label 'txt1' and value 'Please wait'
     $prb->addLabel('percent', 'pct1');
     // add Percent as Label 'pct1'
     $prb->addButton('btn1', gT('Go back'), '?action=statistics&amp;sid=' . $iSurveyID);
     // add Button as Label 'btn1' and action '?restart=1'
     //progress bar starts with 35%
     $process_status = 35;
     $prb->show();
     // show the ProgressBar
     // 1: Get list of questions with answers chosen
     //"Getting Questions and Answer ..." is shown above the bar
     $prb->setLabelValue('txt1', gT('Getting questions and answers ...'));
     $prb->moveStep(5);
     // creates array of post variable names
     for (reset($_POST); $key = key($_POST); next($_POST)) {
         $postvars[] = $key;
     }
     $data['thisSurveyTitle'] = $thisSurveyTitle;
     $data['totalrecords'] = $totalrecords;
     $data['summary'] = $summary;
     //show some main data at the beginnung
     // CHANGE JSW_NZ - let's allow html formatted questions to show
     //push progress bar from 35 to 40
     $process_status = 40;
     //Show Summary results
     if (isset($summary) && $summary) {
         //"Generating Summaries ..." is shown above the progress bar
         $prb->setLabelValue('txt1', gT('Generating summaries ...'));
         $prb->moveStep($process_status);
         //let's run through the survey // Fixed bug 3053 with array_unique
         $runthrough = array_unique($summary);
         //loop through all selected questions
         foreach ($runthrough as $rt) {
             //update progress bar
             if ($process_status < 100) {
                 $process_status++;
             }
             $prb->moveStep($process_status);
         }
         // end foreach -> loop through all questions
         $helper = new statistics_helper();
         $statisticsoutput .= $helper->generate_statistics($iSurveyID, $summary, $summary, $publicgraphs, 'html', null, $sLanguage, false);
     }
     //end if -> show summary results
     $data['statisticsoutput'] = $statisticsoutput;
     //done! set progress bar to 100%
     if (isset($prb)) {
         $prb->setLabelValue('txt1', gT('Completed'));
         $prb->moveStep(100);
         $prb->hide();
     }
     $redata = compact(array_keys(get_defined_vars()));
     $data['redata'] = $redata;
     Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . 'statistics_user.js');
     $this->renderPartial('/statistics_user_view', $data);
     //output footer
     echo getFooter();
     //Delete all Session Data
     Yii::app()->session['finished'] = true;
 }
/**
* This function replaces keywords in a text and is mainly intended for templates
* If you use this functions put your replacement strings into the $replacements variable
* instead of using global variables
* NOTE - Don't do any embedded replacements in this function.  Create the array of replacement values and
* they will be done in batch at the end
*
* @param mixed $line Text to search in
* @param mixed $replacements Array of replacements:  Array( <stringtosearch>=><stringtoreplacewith>
* @param boolean $anonymized Determines if token data is being used or just replaced with blanks
* @param questionNum - needed to support dynamic JavaScript-based tailoring within questions
* @param bStaticReplacement - Default off, forces non-dynamic replacements without <SPAN> tags (e.g. for the Completed page)
* @return string  Text with replaced strings
*/
function templatereplace($line, $replacements = array(), &$redata = array(), $debugSrc = 'Unspecified', $anonymized = false, $questionNum = NULL, $registerdata = array(), $bStaticReplacement = false)
{
    /*
    global $clienttoken,$token,$sitename,$move,$showxquestions,$showqnumcode,$questioncode;
    global $s_lang,$errormsg,$saved_id, $languagechanger,$captchapath,$loadname;
    */
    /*
    $allowedvars = array('surveylist', 'sitename', 'clienttoken', 'rooturl', 'thissurvey', 'imageurl', 'defaulttemplate',
    'percentcomplete', 'move', 'groupname', 'groupdescription', 'question', 'showxquestions',
    'showgroupinfo', 'showqnumcode', 'questioncode', 'answer', 'navigator', 'help', 'totalquestions',
    'surveyformat', 'completed', 'notanswered', 'privacy', 'surveyid', 'publicurl',
    'templatedir', 'token', 'assessments', 's_lang', 'errormsg', 'clang', 'saved_id', 'usertemplaterootdir',
    'languagechanger', 'printoutput', 'captchapath', 'loadname');
    */
    $allowedvars = array('answer', 'assessments', 'captchapath', 'clienttoken', 'completed', 'errormsg', 'groupdescription', 'groupname', 'help', 'imageurl', 'languagechanger', 'loadname', 'move', 'navigator', 'percentcomplete', 'privacy', 'question', 's_lang', 'saved_id', 'showgroupinfo', 'showqnumcode', 'showxquestions', 'sitename', 'surveylist', 'templatedir', 'thissurvey', 'token', 'totalBoilerplatequestions', 'totalquestions');
    $varsPassed = array();
    foreach ($allowedvars as $var) {
        if (isset($redata[$var])) {
            ${$var} = $redata[$var];
            $varsPassed[] = $var;
        }
    }
    //    if (count($varsPassed) > 0) {
    //        log_message('debug', 'templatereplace() called from ' . $debugSrc . ' contains: ' . implode(', ', $varsPassed));
    //    }
    //    if (isset($redata['question'])) {
    //        LimeExpressionManager::ShowStackTrace('has QID and/or SGA',$allowedvars);
    //    }
    //    extract($redata);   // creates variables for each of the keys in the array
    // Local over-rides in case not set above
    if (!isset($showgroupinfo)) {
        $showgroupinfo = Yii::app()->getConfig('showgroupinfo');
    }
    if (!isset($showqnumcode)) {
        $showqnumcode = Yii::app()->getConfig('showqnumcode');
    }
    $_surveyid = Yii::app()->getConfig('surveyID');
    if (!isset($showxquestions)) {
        $showxquestions = Yii::app()->getConfig('showxquestions');
    }
    if (!isset($s_lang)) {
        $s_lang = isset(Yii::app()->session['survey_' . $_surveyid]['s_lang']) ? Yii::app()->session['survey_' . $_surveyid]['s_lang'] : 'en';
    }
    if ($_surveyid && !isset($thissurvey)) {
        $thissurvey = getSurveyInfo($_surveyid, $s_lang);
    }
    if (!isset($captchapath)) {
        $captchapath = '';
    }
    if (!isset($sitename)) {
        $sitename = Yii::app()->getConfig('sitename');
    }
    if (!isset($saved_id) && isset(Yii::app()->session['survey_' . $_surveyid]['srid'])) {
        $saved_id = Yii::app()->session['survey_' . $_surveyid]['srid'];
    }
    $clang = Yii::app()->lang;
    Yii::app()->loadHelper('surveytranslator');
    if (isset($thissurvey['sid'])) {
        $surveyid = $thissurvey['sid'];
    }
    // lets sanitize the survey template
    if (isset($thissurvey['templatedir'])) {
        $templatename = $thissurvey['templatedir'];
    } else {
        $templatename = Yii::app()->getConfig('defaulttemplate');
    }
    if (!isset($templatedir)) {
        $templatedir = getTemplatePath($templatename);
    }
    if (!isset($templateurl)) {
        $templateurl = getTemplateURL($templatename) . "/";
    }
    if (!$anonymized && isset($thissurvey['anonymized'])) {
        $anonymized = $thissurvey['anonymized'] == "Y";
    }
    // TEMPLATECSS
    $_templatecss = "";
    if (stripos($line, "{TEMPLATECSS}")) {
        if (file_exists($templatedir . DIRECTORY_SEPARATOR . 'jquery-ui-custom.css')) {
            Yii::app()->getClientScript()->registerCssFile("{$templateurl}jquery-ui-custom.css");
        } elseif (file_exists($templatedir . DIRECTORY_SEPARATOR . 'jquery-ui.css')) {
            Yii::app()->getClientScript()->registerCssFile("{$templateurl}jquery-ui.css");
        } else {
            Yii::app()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl') . "jquery-ui.css");
        }
        Yii::app()->getClientScript()->registerCssFile("{$templateurl}template.css");
        if (getLanguageRTL($clang->langcode)) {
            Yii::app()->getClientScript()->registerCssFile("{$templateurl}template-rtl.css");
        }
    }
    // surveyformat
    if (isset($thissurvey['format'])) {
        $surveyformat = str_replace(array("A", "S", "G"), array("allinone", "questionbyquestion", "groupbygroup"), $thissurvey['format']);
    } else {
        $surveyformat = "";
    }
    if (isset(Yii::app()->session['step']) && Yii::app()->session['step'] % 2 && $surveyformat != "allinone") {
        $surveyformat .= " page-odd";
    }
    if (isset($thissurvey['questionindex']) && $thissurvey['questionindex'] > 0 && $surveyformat != "allinone" && (isset(Yii::app()->session['step']) && Yii::app()->session['step'] > 0)) {
        $surveyformat .= " withindex";
    }
    if (isset($thissurvey['showprogress']) && $thissurvey['showprogress'] == "Y") {
        $surveyformat .= " showprogress";
    }
    if (isset($thissurvey['showqnumcode'])) {
        $surveyformat .= " showqnumcode-" . $thissurvey['showqnumcode'];
    }
    // real survey contact
    if (isset($surveylist) && isset($surveylist['contact'])) {
        $surveycontact = $surveylist['contact'];
    } elseif (isset($surveylist) && isset($thissurvey['admin']) && $thissurvey['admin'] != "") {
        $surveycontact = sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['admin'], $thissurvey['adminemail']);
    } else {
        $surveycontact = "";
    }
    // If there are non-bracketed replacements to be made do so above this line.
    // Only continue in this routine if there are bracketed items to replace {}
    if (strpos($line, "{") === false) {
        // process string anyway so that it can be pretty-printed
        return LimeExpressionManager::ProcessString($line, $questionNum, NULL, false, 1, 1, true);
    }
    if ($showgroupinfo == 'both' || $showgroupinfo == 'name' || $showgroupinfo == 'choose' && !isset($thissurvey['showgroupinfo']) || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'B' || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'N') {
        $_groupname = isset($groupname) ? $groupname : '';
    } else {
        $_groupname = '';
    }
    if ($showgroupinfo == 'both' || $showgroupinfo == 'description' || $showgroupinfo == 'choose' && !isset($thissurvey['showgroupinfo']) || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'B' || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'D') {
        $_groupdescription = isset($groupdescription) ? $groupdescription : '';
    } else {
        $_groupdescription = '';
    }
    if (isset($question) && is_array($question)) {
        $_question = $question['all'];
        $_question_text = $question['text'];
        $_question_help = $question['help'];
        $_question_mandatory = $question['mandatory'];
        $_question_man_message = $question['man_message'];
        $_question_valid_message = $question['valid_message'];
        $_question_file_valid_message = $question['file_valid_message'];
        $question['sgq'] = isset($question['sgq']) ? $question['sgq'] : '';
        $_question_essentials = $question['essentials'];
        $_getQuestionClass = $question['class'];
        $_question_man_class = $question['man_class'];
        $_question_input_error_class = $question['input_error_class'];
        $_question_number = $question['number'];
        $_question_code = $question['code'];
        $_question_type = $question['type'];
        if ($question['sgq']) {
            // Not sure it can happen today ? But if set : allways sXgXq
            list($question['sid'], $question['gid'], $question['qid']) = explode("X", $question['sgq']);
        } else {
            list($question['sid'], $question['gid'], $question['qid']) = array('', '', '');
        }
        $question['aid'] = isset($question['aid']) ? $question['aid'] : '';
    } else {
        $_question = isset($question) ? $question : '';
        $_question_text = '';
        $_question_help = '';
        $_question_mandatory = '';
        $_question_man_message = '';
        $_question_valid_message = '';
        $_question_file_valid_message = '';
        $_question_essentials = '';
        $_getQuestionClass = '';
        $_question_man_class = '';
        $_question_input_error_class = '';
        $_question_number = '';
        $_question_code = '';
        $_question_type = '';
        $question = array_fill_keys(array('sid', 'gid', 'qid', 'aid', 'sgq'), '');
    }
    if ($_question_type == '*') {
        $_question_text = '<div class="em_equation">' . $_question_text . '</div>';
    }
    if (!($showqnumcode == 'both' || $showqnumcode == 'number' || $showqnumcode == 'choose' && !isset($thissurvey['showqnumcode']) || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'B' || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'N')) {
        $_question_number = '';
    }
    if (!($showqnumcode == 'both' || $showqnumcode == 'code' || $showqnumcode == 'choose' && !isset($thissurvey['showqnumcode']) || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'B' || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'C')) {
        $_question_code = '';
    }
    if (!isset($totalquestions)) {
        $totalquestions = 0;
    }
    $_totalquestionsAsked = $totalquestions;
    if ($showxquestions == 'show' || $showxquestions == 'choose' && !isset($thissurvey['showxquestions']) || $showxquestions == 'choose' && $thissurvey['showxquestions'] == 'Y') {
        if ($_totalquestionsAsked < 1) {
            $_therearexquestions = $clang->gT("There are no questions in this survey");
            // Singular
        } elseif ($_totalquestionsAsked == 1) {
            $_therearexquestions = $clang->gT("There is 1 question in this survey");
            //Singular
        } else {
            $_therearexquestions = $clang->gT("There are {NUMBEROFQUESTIONS} questions in this survey.");
            //Note this line MUST be before {NUMBEROFQUESTIONS}
        }
    } else {
        $_therearexquestions = '';
    }
    if (isset($token)) {
        $_token = $token;
    } elseif (isset($clienttoken)) {
        $_token = htmlentities($clienttoken, ENT_QUOTES, 'UTF-8');
        // or should it be URL-encoded?
    } else {
        $_token = '';
    }
    // Expiry
    if (isset($thissurvey['expiry'])) {
        $dateformatdetails = getDateFormatData($thissurvey['surveyls_dateformat']);
        Yii::import('application.libraries.Date_Time_Converter', true);
        $datetimeobj = new Date_Time_Converter($thissurvey['expiry'], "Y-m-d");
        $_dateoutput = $datetimeobj->convert($dateformatdetails['phpdate']);
    } else {
        $_dateoutput = '-';
    }
    $_submitbutton = "<input class='submit' type='submit' value=' " . $clang->gT("Submit") . " ' name='move2' onclick=\"javascript:document.limesurvey.move.value = 'movesubmit';\" />";
    if (isset($thissurvey['surveyls_url']) and $thissurvey['surveyls_url'] != "") {
        if (trim($thissurvey['surveyls_urldescription']) != '') {
            $_linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_urldescription']}</a>";
        } else {
            $_linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_url']}</a>";
        }
    } else {
        $_linkreplace = '';
    }
    if (isset($thissurvey['sid']) && isset($_SESSION['survey_' . $thissurvey['sid']]['srid']) && $thissurvey['active'] == 'Y') {
        $iscompleted = SurveyDynamic::model($surveyid)->isCompleted($_SESSION['survey_' . $thissurvey['sid']]['srid']);
    } else {
        $iscompleted = false;
    }
    if (isset($surveyid) && !$iscompleted) {
        $_clearall = CHtml::htmlButton($clang->gT("Exit and clear survey"), array('type' => 'submit', 'id' => "clearall", 'value' => 'clearall', 'name' => 'clearall', 'class' => 'clearall button', 'data-confirmedby' => 'confirm-clearall', 'title' => $clang->gT("This action need confirmation.")));
        $_clearall .= CHtml::checkBox("confirm-clearall", false, array('id' => 'confirm-clearall', 'value' => 'confirm', 'class' => 'hide jshide'));
        $_clearall .= CHtml::label($clang->gT("Are you sure you want to clear all your responses?"), 'confirm-clearall', array('class' => 'hide jshide'));
    } else {
        $_clearall = "";
    }
    if (isset(Yii::app()->session['datestamp'])) {
        $_datestamp = Yii::app()->session['datestamp'];
    } else {
        $_datestamp = '-';
    }
    if (isset($thissurvey['allowsave']) and $thissurvey['allowsave'] == "Y") {
        $_saveall = doHtmlSaveAll(isset($move) ? $move : NULL);
    } else {
        $_saveall = "";
    }
    if (!isset($help)) {
        $help = "";
    }
    if (flattenText($help, true, true) != '') {
        if (!isset($helpicon)) {
            if (file_exists($templatedir . '/help.gif')) {
                $helpicon = $templateurl . 'help.gif';
            } elseif (file_exists($templatedir . '/help.png')) {
                $helpicon = $templateurl . 'help.png';
            } else {
                $helpicon = Yii::app()->getConfig('imageurl') . "/help.gif";
            }
        }
        $_questionhelp = "<img src='{$helpicon}' alt='Help' align='left' />" . $help;
    } else {
        $_questionhelp = $help;
    }
    if (isset($thissurvey['allowprev']) && $thissurvey['allowprev'] == "N") {
        $_strreview = "";
    } else {
        $_strreview = $clang->gT("If you want to check any of the answers you have made, and/or change them, you can do that now by clicking on the [<< prev] button and browsing through your responses.");
    }
    if (isset($surveyid)) {
        $restartparam = array();
        if ($_token) {
            $restartparam['token'] = sanitize_token($_token);
        }
        // urlencode with needed with sanitize_token
        if (Yii::app()->request->getQuery('lang')) {
            $restartparam['lang'] = sanitize_languagecode(Yii::app()->request->getQuery('lang'));
        } elseif ($s_lang) {
            $restartparam['lang'] = $s_lang;
        }
        $restartparam['newtest'] = "Y";
        $restarturl = Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}", $restartparam);
        $_restart = "<a href='{$restarturl}'>" . $clang->gT("Restart this Survey") . "</a>";
    } else {
        $_restart = "";
    }
    if (isset($thissurvey['anonymized']) && $thissurvey['anonymized'] == 'Y') {
        $_savealert = $clang->gT("To remain anonymous please use a pseudonym as your username, also an email address is not required.");
    } else {
        $_savealert = "";
    }
    if (isset($surveyid)) {
        if ($_token) {
            $returnlink = Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}", array('token' => sanitize_token($_token)));
        } else {
            $returnlink = Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}");
        }
        $_return_to_survey = "<a href='{$returnlink}'>" . $clang->gT("Return to survey") . "</a>";
    } else {
        $_return_to_survey = "";
    }
    // Save Form
    $_saveform = "<table class='save-survey-form'><tr class='save-survey-row save-survey-name'><td class='save-survey-label label-cell' align='right'><label for='savename'>" . $clang->gT("Name") . "</label>:</td><td class='save-survey-input input-cell'><input type='text' name='savename' id='savename' value='";
    if (isset($_POST['savename'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['savename']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr class='save-survey-row save-survey-password-1'><td class='save-survey-label label-cell' align='right'><label for='savepass'>" . $clang->gT("Password") . "</label>:</td><td class='save-survey-input input-cell'><input type='password' id='savepass' name='savepass' value='";
    if (isset($_POST['savepass'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['savepass']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr class='save-survey-row save-survey-password-2'><td class='save-survey-label label-cell' align='right'><label for='savepass2'>" . $clang->gT("Repeat password") . "</label>:</td><td class='save-survey-input input-cell'><input type='password' id='savepass2' name='savepass2' value='";
    if (isset($_POST['savepass2'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['savepass2']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr class='save-survey-row save-survey-email'><td class='save-survey-label label-cell' align='right'><label for='saveemail'>" . $clang->gT("Your email address") . "</label>:</td><td class='save-survey-input input-cell'><input type='text' id='saveemail' name='saveemail' value='";
    if (isset($_POST['saveemail'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['saveemail']));
    }
    $_saveform .= "' /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
        $_saveform .= "<tr class='save-survey-row save-survey-captcha'><td class='save-survey-label label-cell' align='right'><label for='loadsecurity'>" . $clang->gT("Security question") . "</label>:</td><td class='save-survey-input input-cell'><table class='captcha-table'><tr><td class='captcha-image' valign='middle'><img alt='' src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . (isset($surveyid) ? $surveyid : '')) . "' /></td><td class='captcha-input' valign='middle' style='text-align:left'><input type='text' size='5' maxlength='3' id='loadsecurity' name='loadsecurity' value='' /></td></tr></table></td></tr>\n";
    }
    $_saveform .= "<tr><td align='right'></td><td></td></tr>\n" . "<tr class='save-survey-row save-survey-submit'><td class='save-survey-label label-cell'><label class='hide jshide' for='savebutton'>" . $clang->gT("Save Now") . "</label></td><td class='save-survey-input input-cell'><input type='submit' id='savebutton' name='savesubmit' class='button' value='" . $clang->gT("Save Now") . "' /></td></tr>\n" . "</table>";
    // Load Form
    $_loadform = "<table class='load-survey-form'><tr class='load-survey-row load-survey-name'><td class='load-survey-label label-cell' align='right'><label for='loadname'>" . $clang->gT("Saved name") . "</label>:</td><td class='load-survey-input input-cell'><input type='text' id='loadname' name='loadname' value='";
    if (isset($loadname)) {
        $_loadform .= HTMLEscape(autoUnescape($loadname));
    }
    $_loadform .= "' /></td></tr>\n" . "<tr class='load-survey-row load-survey-password'><td class='load-survey-label label-cell' align='right'><label for='loadpass'>" . $clang->gT("Password") . "</label>:</td><td class='load-survey-input input-cell'><input type='password' id='loadpass' name='loadpass' value='";
    if (isset($loadpass)) {
        $_loadform .= HTMLEscape(autoUnescape($loadpass));
    }
    $_loadform .= "' /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
        $_loadform .= "<tr class='load-survey-row load-survey-captcha'><td class='load-survey-label label-cell' align='right'><label for='loadsecurity'>" . $clang->gT("Security question") . "</label>:</td><td class='load-survey-input input-cell'><table class='captcha-table'><tr><td class='captcha-image' valign='middle'><img src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . (isset($surveyid) ? $surveyid : '')) . "' alt='' /></td><td class='captcha-input' valign='middle'><input type='text' size='5' maxlength='3' id='loadsecurity' name='loadsecurity' value='' alt=''/></td></tr></table></td></tr>\n";
    }
    $_loadform .= "<tr class='load-survey-row load-survey-submit'><td class='load-survey-label label-cell'><label class='hide jshide' for='loadbutton'>" . $clang->gT("Load now") . "</label></td><td class='load-survey-input input-cell'><input type='submit' id='loadbutton' class='button' value='" . $clang->gT("Load now") . "' /></td></tr></table>\n";
    // Registration Form
    if (isset($surveyid) || isset($registerdata) && $debugSrc == 'register.php') {
        if (isset($surveyid)) {
            $tokensid = $surveyid;
        } else {
            $tokensid = $registerdata['sid'];
        }
        $_registerform = CHtml::form(array("/register/index/surveyid/{$tokensid}"), 'post');
        if (!isset($_REQUEST['lang'])) {
            $_reglang = Survey::model()->findByPk($tokensid)->language;
        } else {
            $_reglang = returnGlobal('lang');
        }
        $_registerform .= "\n<input type='hidden' name='lang' value='" . $_reglang . "' />\n";
        $_registerform .= "<input type='hidden' name='sid' value='{$tokensid}' id='sid' />\n";
        $_registerform .= "<table class='register register-form-table' summary='Registrationform'>\n" . "<tr class='register-form-row register-form-fname'><td class='register-form-label label-cell' align='right'><label for='register_firstname'>" . $clang->gT("First name") . "</label>:</td>" . "<td class='register-form-input input-cell' align='left'><input class='text' type='text' id='register_firstname' name='register_firstname'";
        if (isset($_POST['register_firstname'])) {
            $_registerform .= " value='" . htmlentities(returnGlobal('register_firstname'), ENT_QUOTES, 'UTF-8') . "'";
        }
        $_registerform .= " /></td></tr>" . "<tr class='register-form-row register-form-lname'><td class='register-form-label label-cell' align='right'><label for='register_lastname'>" . $clang->gT("Last name") . "</label>:</td>\n" . "<td class='register-form-input input-cell' align='left'><input class='text' type='text' id='register_lastname' name='register_lastname'";
        if (isset($_POST['register_lastname'])) {
            $_registerform .= " value='" . htmlentities(returnGlobal('register_lastname'), ENT_QUOTES, 'UTF-8') . "'";
        }
        $_registerform .= " /></td></tr>\n" . "<tr class='register-form-row register-form-email'><td class='register-form-label label-cell' align='right'><label for='register_email'>" . $clang->gT("Email address") . "</label>:</td>\n" . "<td class='register-form-input input-cell' align='left'><input class='text' type='text' id='register_email' name='register_email'";
        if (isset($_POST['register_email'])) {
            $_registerform .= " value='" . htmlentities(returnGlobal('register_email'), ENT_QUOTES, 'UTF-8') . "'";
        }
        $_registerform .= " /></td></tr>\n";
        foreach ($thissurvey['attributedescriptions'] as $field => $attribute) {
            if (empty($attribute['show_register']) || $attribute['show_register'] != 'Y') {
                continue;
            }
            $_registerform .= '
            <tr class="register-form-row register-form-attribute">
            <td class="register-form-label label-cell" align="right"><label for="register_' . $field . '">' . $thissurvey['attributecaptions'][$field] . ($attribute['mandatory'] == 'Y' ? '*' : '') . '</label>:</td>
            <td class="register-form-input input-cell" align="left"><input class="text" type="text" id="register_' . $field . '" name="register_' . $field . '" /></td>
            </tr>';
        }
        if ((count($registerdata) > 1 || isset($thissurvey['usecaptcha'])) && function_exists("ImageCreate") && isCaptchaEnabled('registrationscreen', $thissurvey['usecaptcha'])) {
            $_registerform .= "<tr class='register-form-row register-form-captcha'><td class='register-form-label label-cell' align='right'><label for='loadsecurity'>" . $clang->gT("Security Question") . "</label>:</td><td class='register-form-input input-cell'><table><tr><td valign='middle'><img src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='' /></td><td valign='middle'><input type='text' size='5' maxlength='3' id='loadsecurity' name='loadsecurity' value='' /></td></tr></table></td></tr>\n";
        }
        $_registerform .= "<tr class='register-form-row register-form-submit'><td class='register-form-label label-cell'><label class='hide jshide' for='registercontinue'>" . $clang->gT("Continue") . "</label></td><td class='register-form-input input-cell' align='left'><input id='registercontinue' class='submit button' type='submit' value='" . $clang->gT("Continue") . "' />" . "</td></tr>\n" . "</table>\n";
        if (count($registerdata) > 1 && $registerdata['sid'] != NULL && $debugSrc == 'register.php') {
            $_registerform .= "<input name='startdate' type ='hidden' value='" . $registerdata['startdate'] . "' />";
            $_registerform .= "<input name='enddate' type ='hidden' value='" . $registerdata['enddate'] . "' />";
        }
        $_registerform .= "</form>\n";
    } else {
        $_registerform = "";
    }
    // Assessments
    $assessmenthtml = "";
    if (isset($surveyid) && !is_null($surveyid) && function_exists('doAssessment')) {
        $assessmentdata = doAssessment($surveyid, true);
        $_assessment_current_total = $assessmentdata['total'];
        if (stripos($line, "{ASSESSMENTS}")) {
            $assessmenthtml = doAssessment($surveyid, false);
        }
    } else {
        $_assessment_current_total = '';
    }
    if (isset($thissurvey['googleanalyticsapikey']) && trim($thissurvey['googleanalyticsapikey']) != '') {
        $_googleAnalyticsAPIKey = trim($thissurvey['googleanalyticsapikey']);
    } else {
        $_googleAnalyticsAPIKey = trim(getGlobalSetting('googleanalyticsapikey'));
    }
    $_googleAnalyticsStyle = isset($thissurvey['googleanalyticsstyle']) ? $thissurvey['googleanalyticsstyle'] : '0';
    $_googleAnalyticsJavaScript = '';
    if ($_googleAnalyticsStyle != '' && $_googleAnalyticsStyle != 0 && $_googleAnalyticsAPIKey != '') {
        switch ($_googleAnalyticsStyle) {
            case '1':
                // Default Google Tracking
                $_googleAnalyticsJavaScript = <<<EOD
<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', '{$_googleAnalyticsAPIKey}']);
  _gaq.push(['_trackPageview']);

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

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
</script>
EOD;
                break;
        }
    }
    $_endtext = '';
    if (isset($thissurvey['surveyls_endtext']) && trim($thissurvey['surveyls_endtext']) != '') {
        $_endtext = $thissurvey['surveyls_endtext'];
    }
    if (isset($surveyid) && isset($_SESSION['survey_' . $surveyid]) && isset($_SESSION['survey_' . $surveyid]['register_errormsg'])) {
        $register_errormsg = $_SESSION['survey_' . $surveyid]['register_errormsg'];
    }
    // Set the array of replacement variables here - don't include curly braces
    $coreReplacements = array();
    $coreReplacements['ACTIVE'] = isset($thissurvey['active']) && !($thissurvey['active'] != "Y");
    $coreReplacements['AID'] = $question['aid'];
    $coreReplacements['ANSWER'] = isset($answer) ? $answer : '';
    // global
    $coreReplacements['ANSWERSCLEARED'] = $clang->gT("Answers cleared");
    $coreReplacements['ASSESSMENTS'] = $assessmenthtml;
    $coreReplacements['ASSESSMENT_CURRENT_TOTAL'] = $_assessment_current_total;
    $coreReplacements['ASSESSMENT_HEADING'] = $clang->gT("Your assessment");
    $coreReplacements['CHECKJAVASCRIPT'] = "<noscript><span class='warningjs'>" . $clang->gT("Caution: JavaScript execution is disabled in your browser. You may not be able to answer all questions in this survey. Please, verify your browser parameters.") . "</span></noscript>";
    $coreReplacements['CLEARALL'] = $_clearall;
    $coreReplacements['CLOSEWINDOW'] = "<a href='javascript:%20self.close()'>" . $clang->gT("Close this window") . "</a>";
    $coreReplacements['COMPLETED'] = isset($redata['completed']) ? $redata['completed'] : '';
    // global
    $coreReplacements['DATESTAMP'] = $_datestamp;
    $coreReplacements['ENDTEXT'] = $_endtext;
    $coreReplacements['EXPIRY'] = $_dateoutput;
    $coreReplacements['GID'] = $question['gid'] ? $question['gid'] : Yii::app()->getConfig('gid', '');
    // Use the gid of the question, except if we are not in question (Randomization group name)
    $coreReplacements['GOOGLE_ANALYTICS_API_KEY'] = $_googleAnalyticsAPIKey;
    $coreReplacements['GOOGLE_ANALYTICS_JAVASCRIPT'] = $_googleAnalyticsJavaScript;
    $coreReplacements['GROUPDESCRIPTION'] = $_groupdescription;
    $coreReplacements['GROUPNAME'] = $_groupname;
    $coreReplacements['LANG'] = $clang->getlangcode();
    $coreReplacements['LANGUAGECHANGER'] = isset($languagechanger) ? $languagechanger : '';
    // global
    $coreReplacements['LOADERROR'] = isset($errormsg) ? $errormsg : '';
    // global
    $coreReplacements['LOADFORM'] = $_loadform;
    $coreReplacements['LOADHEADING'] = $clang->gT("Load a previously saved survey");
    $coreReplacements['LOADMESSAGE'] = $clang->gT("You can load a survey that you have previously saved from this screen.") . "<br />" . $clang->gT("Type in the 'name' you used to save the survey, and the password.") . "<br />";
    $coreReplacements['NAVIGATOR'] = isset($navigator) ? $navigator : '';
    // global
    $coreReplacements['NOSURVEYID'] = isset($surveylist) ? $surveylist['nosid'] : '';
    $coreReplacements['NUMBEROFQUESTIONS'] = $_totalquestionsAsked;
    $coreReplacements['PERCENTCOMPLETE'] = isset($percentcomplete) ? $percentcomplete : '';
    // global
    $coreReplacements['PRIVACY'] = isset($privacy) ? $privacy : '';
    // global
    $coreReplacements['PRIVACYMESSAGE'] = "<span style='font-weight:bold; font-style: italic;'>" . $clang->gT("A Note On Privacy") . "</span><br />" . $clang->gT("This survey is anonymous.") . "<br />" . $clang->gT("The record of your survey responses does not contain any identifying information about you, unless a specific survey question explicitly asked for it.") . ' ' . $clang->gT("If you used an identifying token to access this survey, please rest assured that this token will not be stored together with your responses. It is managed in a separate database and will only be updated to indicate whether you did (or did not) complete this survey. There is no way of matching identification tokens with survey responses.");
    $coreReplacements['QID'] = $question['qid'];
    $coreReplacements['QUESTION'] = $_question;
    $coreReplacements['QUESTIONHELP'] = $_questionhelp;
    $coreReplacements['QUESTIONHELPPLAINTEXT'] = strip_tags(addslashes($help));
    // global
    $coreReplacements['QUESTION_CLASS'] = $_getQuestionClass;
    $coreReplacements['QUESTION_CODE'] = $_question_code;
    $coreReplacements['QUESTION_ESSENTIALS'] = $_question_essentials;
    $coreReplacements['QUESTION_FILE_VALID_MESSAGE'] = $_question_file_valid_message;
    $coreReplacements['QUESTION_HELP'] = $_question_help;
    $coreReplacements['QUESTION_INPUT_ERROR_CLASS'] = $_question_input_error_class;
    $coreReplacements['QUESTION_MANDATORY'] = $_question_mandatory;
    $coreReplacements['QUESTION_MAN_CLASS'] = $_question_man_class;
    $coreReplacements['QUESTION_MAN_MESSAGE'] = $_question_man_message;
    $coreReplacements['QUESTION_NUMBER'] = $_question_number;
    $coreReplacements['QUESTION_TEXT'] = $_question_text;
    $coreReplacements['QUESTION_VALID_MESSAGE'] = $_question_valid_message;
    $coreReplacements['REGISTERERROR'] = isset($register_errormsg) ? $register_errormsg : '';
    // global
    $coreReplacements['REGISTERFORM'] = $_registerform;
    $coreReplacements['REGISTERMESSAGE1'] = $clang->gT("You must be registered to complete this survey");
    $coreReplacements['REGISTERMESSAGE2'] = $clang->gT("You may register for this survey if you wish to take part.") . "<br />\n" . $clang->gT("Enter your details below, and an email containing the link to participate in this survey will be sent immediately.");
    $coreReplacements['RESTART'] = $_restart;
    $coreReplacements['RETURNTOSURVEY'] = $_return_to_survey;
    $coreReplacements['SAVE'] = $_saveall;
    $coreReplacements['SAVEALERT'] = $_savealert;
    $coreReplacements['SAVEDID'] = isset($saved_id) ? $saved_id : '';
    // global
    $coreReplacements['SAVEERROR'] = isset($errormsg) ? $errormsg : '';
    // global - same as LOADERROR
    $coreReplacements['SAVEFORM'] = $_saveform;
    $coreReplacements['SAVEHEADING'] = $clang->gT("Save your unfinished survey");
    $coreReplacements['SAVEMESSAGE'] = $clang->gT("Enter a name and password for this survey and click save below.") . "<br />\n" . $clang->gT("Your survey will be saved using that name and password, and can be completed later by logging in with the same name and password.") . "<br /><br />\n" . $clang->gT("If you give an email address, an email containing the details will be sent to you.") . "<br /><br />\n" . $clang->gT("After having clicked the save button you can either close this browser window or continue filling out the survey.");
    $coreReplacements['SGQ'] = $question['sgq'];
    $coreReplacements['SID'] = Yii::app()->getConfig('surveyID', '');
    // Allways use surveyID from config
    $coreReplacements['SITENAME'] = isset($sitename) ? $sitename : '';
    // global
    $coreReplacements['SUBMITBUTTON'] = $_submitbutton;
    $coreReplacements['SUBMITCOMPLETE'] = "<strong>" . $clang->gT("Thank you!") . "<br /><br />" . $clang->gT("You have completed answering the questions in this survey.") . "</strong><br /><br />" . $clang->gT("Click on 'Submit' now to complete the process and save your answers.");
    $coreReplacements['SUBMITREVIEW'] = $_strreview;
    $coreReplacements['SURVEYCONTACT'] = $surveycontact;
    $coreReplacements['SURVEYDESCRIPTION'] = isset($thissurvey['description']) ? $thissurvey['description'] : '';
    $coreReplacements['SURVEYFORMAT'] = isset($surveyformat) ? $surveyformat : '';
    // global
    $coreReplacements['SURVEYLANGAGE'] = $clang->langcode;
    $coreReplacements['SURVEYLANGUAGE'] = $clang->langcode;
    $coreReplacements['SURVEYLIST'] = isset($surveylist) ? $surveylist['list'] : '';
    $coreReplacements['SURVEYLISTHEADING'] = isset($surveylist) ? $surveylist['listheading'] : '';
    $coreReplacements['SURVEYNAME'] = isset($thissurvey['name']) ? $thissurvey['name'] : '';
    $coreReplacements['TEMPLATECSS'] = $_templatecss;
    $coreReplacements['TEMPLATEJS'] = CHtml::tag('script', array('type' => 'text/javascript', 'src' => $templateurl . 'template.js'), '');
    $coreReplacements['TEMPLATEURL'] = $templateurl;
    $coreReplacements['THEREAREXQUESTIONS'] = $_therearexquestions;
    $coreReplacements['TOKEN'] = !$anonymized ? $_token : '';
    // Silently replace TOKEN by empty string
    $coreReplacements['URL'] = $_linkreplace;
    $coreReplacements['WELCOME'] = isset($thissurvey['welcome']) ? $thissurvey['welcome'] : '';
    if (!is_null($replacements) && is_array($replacements)) {
        $doTheseReplacements = array_merge($coreReplacements, $replacements);
        // so $replacements overrides core values
    } else {
        $doTheseReplacements = $coreReplacements;
    }
    // Now do all of the replacements - In rare cases, need to do 3 deep recursion, that that is default
    $line = LimeExpressionManager::ProcessString($line, $questionNum, $doTheseReplacements, false, 3, 1, false, true, $bStaticReplacement);
    return $line;
}
/**
* This function returns GET/POST/REQUEST vars, for some vars like SID and others they are also sanitized
*
* @param mixed $stringname
*/
function returnglobal($stringname)
{
    global $useWebserverAuth;
    if (isset($useWebserverAuth) && $useWebserverAuth === true || $stringname == 'sid') {
        if (isset($_GET[$stringname])) {
            $urlParam = $_GET[$stringname];
        }
        if (isset($_POST[$stringname])) {
            $urlParam = $_POST[$stringname];
        }
    } elseif (isset($_REQUEST[$stringname])) {
        $urlParam = $_REQUEST[$stringname];
    }
    if (isset($urlParam)) {
        if ($stringname == 'sid' || $stringname == "gid" || $stringname == "oldqid" || $stringname == "qid" || $stringname == "tid" || $stringname == "lid" || $stringname == "ugid" || $stringname == "thisstep" || $stringname == "scenario" || $stringname == "cqid" || $stringname == "cid" || $stringname == "qaid" || $stringname == "scid" || $stringname == "loadsecurity") {
            return sanitize_int($urlParam);
        } elseif ($stringname == "lang" || $stringname == "adminlang") {
            return sanitize_languagecode($urlParam);
        } elseif ($stringname == "htmleditormode" || $stringname == "subaction") {
            return sanitize_paranoid_string($urlParam);
        } elseif ($stringname == "cquestions") {
            return sanitize_cquestions($urlParam);
        }
        return $urlParam;
    } else {
        return NULL;
    }
}
Exemplo n.º 25
0
 /**
  * Add dummy tokens form
  */
 function addDummies($iSurveyId, $subaction = '')
 {
     $iSurveyId = sanitize_int($iSurveyId);
     $clang = $this->getController()->lang;
     if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'create')) {
         Yii::app()->session['flashmessage'] = $clang->gT("You do not have sufficient rights to access this page.");
         $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}"));
     }
     $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}');
     if (!$bTokenExists) {
         self::_newtokentable($iSurveyId);
     }
     $this->getController()->loadHelper("surveytranslator");
     if (!empty($subaction) && $subaction == 'add') {
         $this->getController()->loadLibrary('Date_Time_Converter');
         $dateformatdetails = getDateFormatData(Yii::app()->session['dateformat']);
         //Fix up dates and match to database format
         if (trim(Yii::app()->request->getPost('validfrom')) == '') {
             $_POST['validfrom'] = null;
         } else {
             $datetimeobj = new Date_Time_Converter(trim(Yii::app()->request->getPost('validfrom')), $dateformatdetails['phpdate'] . ' H:i');
             $_POST['validfrom'] = $datetimeobj->convert('Y-m-d H:i:s');
         }
         if (trim(Yii::app()->request->getPost('validuntil')) == '') {
             $_POST['validuntil'] = null;
         } else {
             $datetimeobj = new Date_Time_Converter(trim(Yii::app()->request->getPost('validuntil')), $dateformatdetails['phpdate'] . ' H:i');
             $_POST['validuntil'] = $datetimeobj->convert('Y-m-d H:i:s');
         }
         $santitizedtoken = '';
         $aData = array('firstname' => Yii::app()->request->getPost('firstname'), 'lastname' => Yii::app()->request->getPost('lastname'), 'email' => Yii::app()->request->getPost('email'), 'emailstatus' => 'OK', 'token' => $santitizedtoken, 'language' => sanitize_languagecode(Yii::app()->request->getPost('language')), 'sent' => 'N', 'remindersent' => 'N', 'completed' => 'N', 'usesleft' => Yii::app()->request->getPost('usesleft'), 'validfrom' => Yii::app()->request->getPost('validfrom'), 'validuntil' => Yii::app()->request->getPost('validuntil'));
         // add attributes
         $attrfieldnames = getTokenFieldsAndNames($iSurveyId, true);
         foreach ($attrfieldnames as $attr_name => $desc) {
             $value = Yii::app()->request->getPost($attr_name);
             if ($desc['mandatory'] == 'Y' && trim($value) == '') {
                 $this->getController()->error(sprintf($clang->gT('%s cannot be left empty'), $desc['description']));
             }
             $aData[$attr_name] = Yii::app()->request->getPost($attr_name);
         }
         $amount = sanitize_int(Yii::app()->request->getPost('amount'));
         $tokenlength = sanitize_int(Yii::app()->request->getPost('tokenlen'));
         // Fill an array with all existing tokens
         $existingtokens = array();
         $tokenModel = Token::model($iSurveyId);
         $criteria = $tokenModel->getDbCriteria();
         $criteria->select = 'token';
         $criteria->distinct = true;
         $command = $tokenModel->getCommandBuilder()->createFindCommand($tokenModel->getTableSchema(), $criteria);
         $result = $command->query();
         while ($tokenRow = $result->read()) {
             $existingtokens[$tokenRow['token']] = true;
         }
         $result->close();
         $invalidtokencount = 0;
         $newDummyToken = 0;
         while ($newDummyToken < $amount && $invalidtokencount < 50) {
             $token = Token::create($iSurveyId);
             $token->setAttributes($aData, false);
             $token->firstname = str_replace('{TOKEN_COUNTER}', $newDummyToken, $token->firstname);
             $token->lastname = str_replace('{TOKEN_COUNTER}', $newDummyToken, $token->lastname);
             $token->email = str_replace('{TOKEN_COUNTER}', $newDummyToken, $token->email);
             $attempts = 0;
             do {
                 $token->token = randomChars($tokenlength);
                 $attempts++;
             } while (isset($existingtokens[$token->token]) && $attempts < 50);
             if ($attempts == 50) {
                 throw new Exception('Something is wrong with your random generator.');
             }
             $existingtokens[$token->token] = true;
             $token->save();
             $newDummyToken++;
         }
         $aData['thissurvey'] = getSurveyInfo($iSurveyId);
         $aData['surveyid'] = $iSurveyId;
         if (!$invalidtokencount) {
             $aData['success'] = false;
             $message = array('title' => $clang->gT("Success"), 'message' => $clang->gT("New dummy tokens were added.") . "<br /><br />\n<input type='button' value='" . $clang->gT("Display tokens") . "' onclick=\"window.open('" . $this->getController()->createUrl("admin/tokens/sa/browse/surveyid/{$iSurveyId}") . "', '_top')\" />\n");
         } else {
             $aData['success'] = true;
             $message = array('title' => $clang->gT("Failed"), 'message' => "<p>" . sprintf($clang->gT("Only %s new dummy tokens were added after %s trials."), $newDummyToken, $invalidtokencount) . $clang->gT("Try with a bigger token length.") . "</p>" . "\n<input type='button' value='" . $clang->gT("Display tokens") . "' onclick=\"window.open('" . $this->getController()->createUrl("admin/tokens/sa/browse/surveyid/{$iSurveyId}") . "', '_top')\" />\n");
         }
         $this->_renderWrappedTemplate('token', array('tokenbar', 'message' => $message), $aData);
     } else {
         $tokenlength = !empty(Token::model($iSurveyId)->survey->tokenlength) ? Token::model($iSurveyId)->survey->tokenlength : 15;
         $thissurvey = getSurveyInfo($iSurveyId);
         $aData['thissurvey'] = $thissurvey;
         $aData['surveyid'] = $iSurveyId;
         $aData['tokenlength'] = $tokenlength;
         $aData['dateformatdetails'] = getDateFormatData(Yii::app()->session['dateformat'], $clang->langcode);
         $aData['aAttributeFields'] = GetParticipantAttributes($iSurveyId);
         $this->_renderWrappedTemplate('token', array('tokenbar', 'dummytokenform'), $aData);
     }
 }
Exemplo n.º 26
0
    function action()
    {
        global $surveyid;
        global $thissurvey, $thisstep;
        global $clienttoken, $tokensexist, $token;
        global $clang;
        $clang = Yii::app()->lang;
        @ini_set('session.gc_maxlifetime', Yii::app()->getConfig('iSessionExpirationTime'));
        $this->_loadRequiredHelpersAndLibraries();
        $param = $this->_getParameters(func_get_args(), $_POST);
        $surveyid = $param['sid'];
        Yii::app()->setConfig('surveyID', $surveyid);
        $thisstep = $param['thisstep'];
        $move = $param['move'];
        $clienttoken = $param['token'];
        $standardtemplaterootdir = Yii::app()->getConfig('standardtemplaterootdir');
        // unused vars in this method (used in methods using compacted method vars)
        @($loadname = $param['loadname']);
        @($loadpass = $param['loadpass']);
        $sitename = Yii::app()->getConfig('sitename');
        if (isset($param['newtest']) && $param['newtest'] == "Y") {
            killSurveySession($surveyid);
        }
        list($surveyExists, $isSurveyActive) = $this->_surveyExistsAndIsActive($surveyid);
        // collect all data in this method to pass on later
        $redata = compact(array_keys(get_defined_vars()));
        $clang = $this->_loadLimesurveyLang($surveyid);
        if ($this->_isClientTokenDifferentFromSessionToken($clienttoken, $surveyid)) {
            $asMessage = array($clang->gT('Token mismatch'), $clang->gT('The token you provided doesn\'t match the one in your session.'), $clang->gT('Please wait to begin with a new session.'));
            $this->_createNewUserSessionAndRedirect($surveyid, $redata, __LINE__, $asMessage);
        }
        if ($this->_isSurveyFinished($surveyid)) {
            $asMessage = array($clang->gT('Previous session is set to be finished.'), $clang->gT('Your browser reports that it was used previously to answer this survey. We are resetting the session so that you can start from the beginning.'), $clang->gT('Please wait to begin with a new session.'));
            $this->_createNewUserSessionAndRedirect($surveyid, $redata, __LINE__, $asMessage);
        }
        if ($this->_isPreviewAction($param) && !$this->_canUserPreviewSurvey($surveyid)) {
            $asMessage = array($clang->gT('Error'), $clang->gT('We are sorry but you don\'t have permissions to do this.'));
            $this->_niceExit($redata, __LINE__, null, $asMessage);
        }
        if ($this->_surveyCantBeViewedWithCurrentPreviewAccess($surveyid, $isSurveyActive, $surveyExists)) {
            $bPreviewRight = $this->_userHasPreviewAccessSession($surveyid);
            if ($bPreviewRight === false) {
                $asMessage = array($clang->gT("Error"), $clang->gT("We are sorry but you don't have permissions to do this."), sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
                $this->_niceExit($redata, __LINE__, null, $asMessage);
            }
        }
        // TODO can this be moved to the top?
        // (Used to be global, used in ExpressionManager, merged into amVars. If not filled in === '')
        // can this be added in the first computation of $redata?
        if (isset($_SESSION['survey_' . $surveyid]['srid'])) {
            $saved_id = $_SESSION['survey_' . $surveyid]['srid'];
        }
        // recompute $redata since $saved_id used to be a global
        $redata = compact(array_keys(get_defined_vars()));
        /*if ( $this->_didSessionTimeOut() )
          {
          // @TODO is this still required ?
          $asMessage = array(
          $clang->gT("Error"),
          $clang->gT("We are sorry but your session has expired."),
          $clang->gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection."),
          sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail'])
          );
          $this->_niceExit($redata, __LINE__, null, $asMessage);
          };*/
        // Set the language of the survey, either from POST, GET parameter of session var
        if (!empty($_REQUEST['lang'])) {
            $sTempLanguage = sanitize_languagecode($_REQUEST['lang']);
        } elseif (!empty($param['lang'])) {
            $sTempLanguage = sanitize_languagecode($param['lang']);
        } elseif (isset($_SESSION['survey_' . $surveyid]['s_lang'])) {
            $sTempLanguage = $_SESSION['survey_' . $surveyid]['s_lang'];
        } else {
            $sTempLanguage = '';
        }
        //CHECK FOR REQUIRED INFORMATION (sid)
        if ($surveyid && $surveyExists) {
            LimeExpressionManager::SetSurveyId($surveyid);
            // must be called early - it clears internal cache if a new survey is being used
            $clang = SetSurveyLanguage($surveyid, $sTempLanguage);
            UpdateSessionGroupList($surveyid, $sTempLanguage);
            // to refresh the language strings in the group list session variable
            UpdateFieldArray();
            // to refresh question titles and question text
        } else {
            if (!is_null($param['lang'])) {
                $sDisplayLanguage = $param['lang'];
            } else {
                $sDisplayLanguage = Yii::app()->getConfig('defaultlang');
            }
            $clang = $this->_loadLimesurveyLang($sDisplayLanguage);
            $languagechanger = makeLanguageChanger($sDisplayLanguage);
            //Find out if there are any publicly available surveys
            $query = "SELECT sid, surveyls_title, publicstatistics, language\n            FROM {{surveys}}\n            INNER JOIN {{surveys_languagesettings}}\n            ON ( surveyls_survey_id = sid  )\n            AND (surveyls_language=language)\n            WHERE\n            active='Y'\n            AND listpublic='Y'\n            AND ((expires >= '" . date("Y-m-d H:i") . "') OR (expires is null))\n            AND ((startdate <= '" . date("Y-m-d H:i") . "') OR (startdate is null))\n            ORDER BY surveyls_title";
            $result = dbExecuteAssoc($query, false, true) or safeDie("Could not connect to database. If you try to install LimeSurvey please refer to the <a href='http://docs.limesurvey.org'>installation docs</a> and/or contact the system administrator of this webpage.");
            //Checked
            $list = array();
            foreach ($result->readAll() as $rows) {
                $querylang = "SELECT surveyls_title\n                FROM {{surveys_languagesettings}}\n                WHERE surveyls_survey_id={$rows['sid']}\n                AND surveyls_language='{$sDisplayLanguage}'";
                $resultlang = Yii::app()->db->createCommand($querylang)->queryRow();
                if ($resultlang['surveyls_title']) {
                    $rows['surveyls_title'] = $resultlang['surveyls_title'];
                    $langtag = "";
                } else {
                    $langtag = "lang=\"{$rows['language']}\"";
                }
                $link = "<li><a href='" . $this->getController()->createUrl('/survey/index/sid/' . $rows['sid']);
                if (isset($param['lang']) && $langtag == "") {
                    $link .= "/lang-" . sanitize_languagecode($param['lang']);
                }
                $link .= "' {$langtag} class='surveytitle'>" . $rows['surveyls_title'] . "</a>\n";
                if ($rows['publicstatistics'] == 'Y') {
                    $link .= "<a href='" . $this->getController()->createUrl("/statistics_user/action/surveyid/" . $rows['sid']) . "/language/" . $sDisplayLanguage . "'>(" . $clang->gT('View statistics') . ")</a>";
                }
                $link .= "</li>\n";
                $list[] = $link;
            }
            //Check for inactive surveys which allow public registration.
            // TODO add a new template replace {SURVEYREGISTERLIST} ?
            $squery = "SELECT sid, surveyls_title, publicstatistics, language\n            FROM {{surveys}}\n            INNER JOIN {{surveys_languagesettings}}\n            ON (surveyls_survey_id = sid)\n            AND (surveyls_language=language)\n            WHERE allowregister='Y'\n            AND active='Y'\n            AND listpublic='Y'\n            AND ((expires >= '" . date("Y-m-d H:i") . "') OR (expires is null))\n            AND (startdate >= '" . date("Y-m-d H:i") . "')\n            ORDER BY surveyls_title";
            $sresult = dbExecuteAssoc($squery) or safeDie("Couldn't execute {$squery}");
            $aRows = $sresult->readAll();
            if (count($aRows) > 0) {
                $list[] = "</ul>" . " <div class=\"survey-list-heading\">" . $clang->gT("Following survey(s) are not yet active but you can register for them.") . "</div>" . " <ul>";
                // TODO give it to template
                foreach ($aRows as $rows) {
                    $querylang = "SELECT surveyls_title\n                    FROM {{surveys_languagesettings}}\n                    WHERE surveyls_survey_id={$rows['sid']}\n                    AND surveyls_language='{$sDisplayLanguage}'";
                    $resultlang = Yii::app()->db->createCommand($querylang)->queryRow();
                    if ($resultlang['surveyls_title']) {
                        $rows['surveyls_title'] = $resultlang['surveyls_title'];
                        $langtag = "";
                    } else {
                        $langtag = "lang=\"{$rows['language']}\"";
                    }
                    $link = "<li><a href=\"#\" id='inactivesurvey' onclick = 'sendreq(" . $rows['sid'] . ");' ";
                    //$link = "<li><a href=\"#\" id='inactivesurvey' onclick = 'convertGETtoPOST(".$this->getController()->createUrl('survey/send/')."?sid={$rows['sid']}&amp;)sendreq(".$rows['sid'].",".$rows['startdate'].",".$rows['expires'].");' ";
                    $link .= " {$langtag} class='surveytitle'>" . $rows['surveyls_title'] . "</a>\n";
                    $link .= "</li><div id='regform'></div>\n";
                    $list[] = $link;
                }
            }
            if (count($list) < 1) {
                $list[] = "<li class='surveytitle'>" . $clang->gT("No available surveys") . "</li>";
            }
            if (!$surveyid) {
                $thissurvey['name'] = Yii::app()->getConfig("sitename");
                $nosid = $clang->gT("You have not provided a survey identification number");
            } else {
                $thissurvey['name'] = $clang->gT("The survey identification number is invalid");
                $nosid = $clang->gT("The survey identification number is invalid");
            }
            $surveylist = array("nosid" => $nosid, "contact" => sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), Yii::app()->getConfig("siteadminname"), encodeEmail(Yii::app()->getConfig("siteadminemail"))), "listheading" => $clang->gT("The following surveys are available:"), "list" => implode("\n", $list));
            $data['thissurvey'] = $thissurvey;
            //$data['privacy'] = $privacy;
            $data['surveylist'] = $surveylist;
            $data['surveyid'] = $surveyid;
            $data['templatedir'] = getTemplatePath(Yii::app()->getConfig("defaulttemplate"));
            $data['templateurl'] = getTemplateURL(Yii::app()->getConfig("defaulttemplate")) . "/";
            $data['templatename'] = Yii::app()->getConfig("defaulttemplate");
            $data['sitename'] = Yii::app()->getConfig("sitename");
            $data['languagechanger'] = $languagechanger;
            //A nice exit
            sendCacheHeaders();
            doHeader();
            $this->_printTemplateContent(getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . "/startpage.pstpl", $data, __LINE__);
            $this->_printTemplateContent(getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . "/surveylist.pstpl", $data, __LINE__);
            echo '<script type="text/javascript" >
            function sendreq(surveyid)
            {

            $.ajax({
            type: "GET",
            url: "' . $this->getController()->createUrl("/register/ajaxregisterform/surveyid") . '/" + surveyid,
            }).done(function(msg) {
            document.getElementById("regform").innerHTML = msg;
            });
            }
            </script>';
            $this->_printTemplateContent(getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . "/endpage.pstpl", $data, __LINE__);
            doFooter();
            exit;
        }
        // Get token
        if (!isset($token)) {
            $token = $clienttoken;
        }
        //GET BASIC INFORMATION ABOUT THIS SURVEY
        $thissurvey = getSurveyInfo($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
        //SEE IF SURVEY USES TOKENS
        if ($surveyExists == 1 && tableExists('{{tokens_' . $thissurvey['sid'] . '}}')) {
            $tokensexist = 1;
        } else {
            $tokensexist = 0;
            unset($_POST['token']);
            unset($param['token']);
            unset($token);
            unset($clienttoken);
        }
        //SET THE TEMPLATE DIRECTORY
        $thistpl = getTemplatePath($thissurvey['templatedir']);
        $timeadjust = Yii::app()->getConfig("timeadjust");
        //MAKE SURE SURVEY HASN'T EXPIRED
        if ($thissurvey['expiry'] != '' and dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust) > $thissurvey['expiry'] && $thissurvey['active'] != 'N') {
            $redata = compact(array_keys(get_defined_vars()));
            $asMessage = array($clang->gT("Error"), $clang->gT("This survey is no longer available."), sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
            $this->_niceExit($redata, __LINE__, $thistpl, $asMessage);
        }
        //MAKE SURE SURVEY IS ALREADY VALID
        if ($thissurvey['startdate'] != '' and dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust) < $thissurvey['startdate'] && $thissurvey['active'] != 'N') {
            $redata = compact(array_keys(get_defined_vars()));
            $asMessage = array($clang->gT("Error"), $clang->gT("This survey is not yet started."), sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
            $this->_niceExit($redata, __LINE__, $thistpl, $asMessage);
        }
        //CHECK FOR PREVIOUSLY COMPLETED COOKIE
        //If cookies are being used, and this survey has been completed, a cookie called "PHPSID[sid]STATUS" will exist (ie: SID6STATUS) and will have a value of "COMPLETE"
        $sCookieName = "LS_" . $surveyid . "_STATUS";
        if (isset($_COOKIE[$sCookieName]) && $_COOKIE[$sCookieName] == "COMPLETE" && $thissurvey['usecookie'] == "Y" && $tokensexist != 1 && (!isset($param['newtest']) || $param['newtest'] != "Y")) {
            $redata = compact(array_keys(get_defined_vars()));
            $asMessage = array($clang->gT("Error"), $clang->gT("You have already completed this survey."), sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['adminname'], $thissurvey['adminemail']));
            $this->_niceExit($redata, __LINE__, $thistpl, $asMessage);
        }
        if (isset($_GET['loadall']) && $_GET['loadall'] == "reload") {
            if (returnGlobal('loadname') && returnGlobal('loadpass')) {
                $_POST['loadall'] = "reload";
            }
        }
        //LOAD SAVED SURVEY
        if (isset($_POST['loadall']) && $_POST['loadall'] == "reload") {
            $errormsg = "";
            if (!isset($param['loadname']) || $param['loadname'] == null) {
                $errormsg .= $clang->gT("You did not provide a name") . "<br />\n";
            }
            if (!isset($param['loadpass']) || $param['loadpass'] == null) {
                $errormsg .= $clang->gT("You did not provide a password") . "<br />\n";
            }
            // if security question answer is incorrect
            // Not called if scid is set in GET params (when using email save/reload reminder URL)
            if (function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
                if ((!isset($_POST['loadsecurity']) || !isset($_SESSION['survey_' . $surveyid]['secanswer']) || $_POST['loadsecurity'] != $_SESSION['survey_' . $surveyid]['secanswer']) && !isset($_GET['scid'])) {
                    $errormsg .= $clang->gT("The answer to the security question is incorrect.") . "<br />\n";
                }
            }
            // Load session before loading the values from the saved data
            if (isset($_GET['loadall'])) {
                buildsurveysession($surveyid);
            }
            $_SESSION['survey_' . $surveyid]['holdname'] = $param['loadname'];
            //Session variable used to load answers every page.
            $_SESSION['survey_' . $surveyid]['holdpass'] = $param['loadpass'];
            //Session variable used to load answers every page.
            if ($errormsg == "") {
                loadanswers();
            }
            $move = "movenext";
            if ($errormsg) {
                $_POST['loadall'] = $clang->gT("Load unfinished survey");
            }
        }
        //Allow loading of saved survey
        if (isset($_POST['loadall']) && $_POST['loadall'] == $clang->gT("Load unfinished survey")) {
            $redata = compact(array_keys(get_defined_vars()));
            Yii::import("application.libraries.Load_answers");
            $tmp = new Load_answers();
            $tmp->run($redata);
        }
        //Check if TOKEN is used for EVERY PAGE
        //This function fixes a bug where users able to submit two surveys/votes
        //by checking that the token has not been used at each page displayed.
        // bypass only this check at first page (Step=0) because
        // this check is done in buildsurveysession and error message
        // could be more interresting there (takes into accound captcha if used)
        if ($tokensexist == 1 && isset($token) && $token && isset($_SESSION['survey_' . $surveyid]['step']) && $_SESSION['survey_' . $surveyid]['step'] > 0 && tableExists("tokens_{$surveyid}}}")) {
            //check if tokens actually haven't been already used
            $areTokensUsed = usedTokens(trim(strip_tags(returnGlobal('token'))), $surveyid);
            // check if token actually does exist
            // check also if it is allowed to change survey after completion
            if ($thissurvey['alloweditaftercompletion'] == 'Y') {
                $sQuery = "SELECT * FROM {{tokens_" . $surveyid . "}} WHERE token='" . $token . "'";
            } else {
                $sQuery = "SELECT * FROM {{tokens_" . $surveyid . "}} WHERE token='" . $token . "' AND (completed = 'N' or completed='')";
            }
            $aRow = Yii::app()->db->createCommand($sQuery)->queryRow();
            $tokendata = $aRow;
            if (!$aRow || $areTokensUsed && $thissurvey['alloweditaftercompletion'] != 'Y') {
                sendCacheHeaders();
                doHeader();
                //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
                $redata = compact(array_keys(get_defined_vars()));
                $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__);
                $this->_printTemplateContent($thistpl . '/survey.pstpl', $redata, __LINE__);
                $asMessage = array(null, $clang->gT("This is a controlled survey. You need a valid token to participate."), sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname'] . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)"));
                $this->_niceExit($redata, __LINE__, $thistpl, $asMessage, true);
            }
        }
        if ($tokensexist == 1 && isset($token) && $token && tableExists("{{tokens_" . $surveyid . "}}")) {
            // check also if it is allowed to change survey after completion
            if ($thissurvey['alloweditaftercompletion'] == 'Y') {
                $tkquery = "SELECT * FROM {{tokens_" . $surveyid . "}} WHERE token='" . $token . "'";
            } else {
                $tkquery = "SELECT * FROM {{tokens_" . $surveyid . "}} WHERE token='" . $token . "' AND (completed = 'N' or completed='')";
            }
            $tkresult = dbExecuteAssoc($tkquery);
            //Checked
            $tokendata = $tkresult->read();
            if (isset($tokendata['validfrom']) && (trim($tokendata['validfrom']) != '' && $tokendata['validfrom'] > dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust)) || isset($tokendata['validuntil']) && (trim($tokendata['validuntil']) != '' && $tokendata['validuntil'] < dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust))) {
                sendCacheHeaders();
                doHeader();
                //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
                $redata = compact(array_keys(get_defined_vars()));
                $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__);
                $this->_printTemplateContent($thistpl . '/survey.pstpl', $redata, __LINE__);
                $asMessage = array(null, $clang->gT("We are sorry but you are not allowed to enter this survey."), $clang->gT("Your token seems to be valid but can be used only during a certain time period."), sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname'] . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)"));
                $this->_niceExit($redata, __LINE__, $thistpl, $asMessage, true);
            }
        }
        //Clear session and remove the incomplete response if requested.
        if (isset($move) && $move == "clearall") {
            // delete the response but only if not already completed
            $s_lang = $_SESSION['survey_' . $surveyid]['s_lang'];
            if (isset($_SESSION['survey_' . $surveyid]['srid']) && !Survey_dynamic::model($surveyid)->isCompleted($_SESSION['survey_' . $surveyid]['srid'])) {
                // delete the response but only if not already completed
                $result = dbExecuteAssoc('DELETE FROM {{survey_' . $surveyid . '}} WHERE id=' . $_SESSION['survey_' . $surveyid]['srid'] . " AND submitdate IS NULL");
                if ($result->count() > 0) {
                    // Using count() here *should* be okay for MSSQL because it is a delete statement
                    // find out if there are any fuqt questions - checked
                    $fieldmap = createFieldMap($surveyid, 'short', false, false, $s_lang);
                    foreach ($fieldmap as $field) {
                        if ($field['type'] == "|" && !strpos($field['fieldname'], "_filecount")) {
                            if (!isset($qid)) {
                                $qid = array();
                            }
                            $qid[] = $field['fieldname'];
                        }
                    }
                    // if yes, extract the response json to those questions
                    if (isset($qid)) {
                        $query = "SELECT * FROM {{survey_" . $surveyid . "}} WHERE id=" . $_SESSION['survey_' . $surveyid]['srid'];
                        $result = dbExecuteAssoc($query);
                        foreach ($result->readAll() as $row) {
                            foreach ($qid as $question) {
                                $json = $row[$question];
                                if ($json == "" || $json == NULL) {
                                    continue;
                                }
                                // decode them
                                $phparray = json_decode($json);
                                foreach ($phparray as $metadata) {
                                    $target = Yii::app()->getConfig("uploaddir") . "/surveys/" . $surveyid . "/files/";
                                    // delete those files
                                    unlink($target . $metadata->filename);
                                }
                            }
                        }
                    }
                    // done deleting uploaded files
                }
                // also delete a record from saved_control when there is one
                dbExecuteAssoc('DELETE FROM {{saved_control}} WHERE srid=' . $_SESSION['survey_' . $surveyid]['srid'] . ' AND sid=' . $surveyid);
            }
            killSurveySession($surveyid);
            sendCacheHeaders();
            doHeader();
            $redata = compact(array_keys(get_defined_vars()));
            $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__);
            echo "\n\n<!-- JAVASCRIPT FOR CONDITIONAL QUESTIONS -->\n" . "\t<script type='text/javascript'>\n" . "\t<!--\n" . "function checkconditions(value, name, type, evt_type)\n" . "\t{\n" . "\t}\n" . "\t//-->\n" . "\t</script>\n\n";
            //Present the clear all page using clearall.pstpl template
            $this->_printTemplateContent($thistpl . '/clearall.pstpl', $redata, __LINE__);
            $this->_printTemplateContent($thistpl . '/endpage.pstpl', $redata, __LINE__);
            doFooter();
            exit;
        }
        //Check to see if a refering URL has been captured.
        if (!isset($_SESSION['survey_' . $surveyid]['refurl'])) {
            $_SESSION['survey_' . $surveyid]['refurl'] = GetReferringUrl();
            // do not overwrite refurl
        }
        // Let's do this only if
        //  - a saved answer record hasn't been loaded through the saved feature
        //  - the survey is not anonymous
        //  - the survey is active
        //  - a token information has been provided
        //  - the survey is setup to allow token-response-persistence
        if (!isset($_SESSION['survey_' . $surveyid]['srid']) && $thissurvey['anonymized'] == "N" && $thissurvey['active'] == "Y" && isset($token) && $token != '') {
            // load previous answers if any (dataentry with nosubmit)
            $sQuery = "SELECT id,submitdate,lastpage FROM {$thissurvey['tablename']} WHERE {$thissurvey['tablename']}.token='{$token}' order by id desc";
            $aRow = Yii::app()->db->createCommand($sQuery)->queryRow();
            if ($aRow) {
                if ($aRow['submitdate'] == '' && $thissurvey['tokenanswerspersistence'] == 'Y' || $aRow['submitdate'] != '' && $thissurvey['alloweditaftercompletion'] == 'Y') {
                    $_SESSION['survey_' . $surveyid]['srid'] = $aRow['id'];
                    if (!is_null($aRow['lastpage']) && $aRow['submitdate'] == '') {
                        $_SESSION['survey_' . $surveyid]['LEMtokenResume'] = true;
                        $_SESSION['survey_' . $surveyid]['step'] = $aRow['lastpage'];
                    }
                }
                buildsurveysession($surveyid);
                loadanswers();
            }
        }
        //        // SAVE POSTED ANSWERS TO DATABASE IF MOVE (NEXT,PREV,LAST, or SUBMIT) or RETURNING FROM SAVE FORM
        //        if (isset($move) || isset($_POST['saveprompt']))
        //        {
        //            $redata = compact(array_keys(get_defined_vars()));
        //            //save.php
        //            Yii::import("application.libraries.Save");
        //            $tmp = new Save();
        //            $tmp->run($redata);
        //
        //            // RELOAD THE ANSWERS INCASE SOMEONE ELSE CHANGED THEM
        //            if ($thissurvey['active'] == "Y" &&
        //            ( $thissurvey['allowsave'] == "Y" || $thissurvey['tokenanswerspersistence'] == "Y") )
        //            {
        //                loadanswers();
        //            }
        //        }
        if (isset($param['action']) && $param['action'] == 'previewgroup') {
            $thissurvey['format'] = 'G';
            buildsurveysession($surveyid, true);
        }
        if (isset($param['action']) && $param['action'] == 'previewquestion') {
            $thissurvey['format'] = 'S';
            buildsurveysession($surveyid, true);
        }
        sendCacheHeaders();
        //Send local variables to the appropriate survey type
        unset($redata);
        $redata = compact(array_keys(get_defined_vars()));
        Yii::import('application.helpers.SurveyRuntimeHelper');
        $tmp = new SurveyRuntimeHelper();
        $tmp->run($surveyid, $redata);
        if (isset($_POST['saveall']) || isset($flashmessage)) {
            echo "<script type='text/javascript'> \$(document).ready( function() { alert('" . $clang->gT("Your responses were successfully saved.", "js") . "');}) </script>";
        }
    }
/**
* This function replaces keywords in a text and is mainly intended for templates
* If you use this functions put your replacement strings into the $replacements variable
* instead of using global variables
* NOTE - Don't do any embedded replacements in this function.  Create the array of replacement values and
* they will be done in batch at the end
*
* @param mixed $line Text to search in
* @param mixed $replacements Array of replacements:  Array( <stringtosearch>=><stringtoreplacewith>
* @param boolean $anonymized Determines if token data is being used or just replaced with blanks
* @param questionNum - needed to support dynamic JavaScript-based tailoring within questions
* @param bStaticReplacement - Default off, forces non-dynamic replacements without <SPAN> tags (e.g. for the Completed page)
* @return string  Text with replaced strings
*/
function templatereplace($line, $replacements = array(), &$redata = array(), $debugSrc = 'Unspecified', $anonymized = false, $questionNum = NULL, $registerdata = array(), $bStaticReplacement = false, $oTemplate = '')
{
    /*
    global $clienttoken,$token,$sitename,$move,$showxquestions,$showqnumcode,$questioncode;
    global $s_lang,$errormsg,$saved_id, $languagechanger,$captchapath,$loadname;
    */
    /*
    $allowedvars = array('surveylist', 'sitename', 'clienttoken', 'rooturl', 'thissurvey', 'imageurl', 'defaulttemplate',
    'percentcomplete', 'move', 'groupname', 'groupdescription', 'question', 'showxquestions',
    'showgroupinfo', 'showqnumcode', 'questioncode', 'answer', 'navigator', 'help', 'totalquestions',
    'surveyformat', 'completed', 'notanswered', 'privacy', 'surveyid', 'publicurl',
    'templatedir', 'token', 'assessments', 's_lang', 'errormsg', 'saved_id', 'usertemplaterootdir',
    'languagechanger', 'printoutput', 'captchapath', 'loadname');
    */
    $allowedvars = array('assessments', 'captchapath', 'clienttoken', 'completed', 'errormsg', 'groupdescription', 'groupname', 'imageurl', 'languagechanger', 'loadname', 'move', 'navigator', 'moveprevbutton', 'movenextbutton', 'percentcomplete', 'privacy', 's_lang', 'saved_id', 'showgroupinfo', 'showqnumcode', 'showxquestions', 'sitename', 'sitelogo', 'surveylist', 'templatedir', 'thissurvey', 'token', 'totalBoilerplatequestions', 'totalquestions', 'questionindex', 'questionindexmenu');
    $varsPassed = array();
    foreach ($allowedvars as $var) {
        if (isset($redata[$var])) {
            ${$var} = $redata[$var];
            $varsPassed[] = $var;
        }
    }
    //    if (count($varsPassed) > 0) {
    //        log_message('debug', 'templatereplace() called from ' . $debugSrc . ' contains: ' . implode(', ', $varsPassed));
    //    }
    //    if (isset($redata['question'])) {
    //        LimeExpressionManager::ShowStackTrace('has QID and/or SGA',$allowedvars);
    //    }
    //    extract($redata);   // creates variables for each of the keys in the array
    // Local over-rides in case not set above
    if (!isset($showgroupinfo)) {
        $showgroupinfo = Yii::app()->getConfig('showgroupinfo');
    }
    if (!isset($showqnumcode)) {
        $showqnumcode = Yii::app()->getConfig('showqnumcode');
    }
    $_surveyid = Yii::app()->getConfig('surveyID');
    if (!isset($showxquestions)) {
        $showxquestions = Yii::app()->getConfig('showxquestions');
    }
    if (!isset($s_lang)) {
        $s_lang = isset(Yii::app()->session['survey_' . $_surveyid]['s_lang']) ? Yii::app()->session['survey_' . $_surveyid]['s_lang'] : 'en';
    }
    if ($_surveyid && !isset($thissurvey)) {
        $thissurvey = getSurveyInfo($_surveyid, $s_lang);
    }
    if (!isset($captchapath)) {
        $captchapath = '';
    }
    if (!isset($sitename)) {
        $sitename = Yii::app()->getConfig('sitename');
    }
    if (!isset($saved_id) && isset(Yii::app()->session['survey_' . $_surveyid]['srid'])) {
        $saved_id = Yii::app()->session['survey_' . $_surveyid]['srid'];
    }
    Yii::app()->loadHelper('surveytranslator');
    if (isset($thissurvey['sid'])) {
        $surveyid = $thissurvey['sid'];
    }
    // lets sanitize the survey template
    if (isset($thissurvey['templatedir'])) {
        $templatename = $thissurvey['templatedir'];
    } else {
        $templatename = Yii::app()->getConfig('defaulttemplate');
    }
    if (!isset($templatedir)) {
        $templatedir = getTemplatePath($templatename);
    }
    if (!isset($templateurl)) {
        $templateurl = getTemplateURL($templatename) . "/";
    }
    if (!$anonymized && isset($thissurvey['anonymized'])) {
        $anonymized = $thissurvey['anonymized'] == "Y";
    }
    // TEMPLATECSS
    $_templatecss = "";
    $_templatejs = "";
    /**
     * Template css/js files from the template config files are loaded.
     * It use the asset manager (so user never need to empty the cache, even if template is updated)
     * If debug mode is on, no asset manager is used.
     *
     * oTemplate is defined in controller/survey/index
     *
     * If templatereplace is called from the template editor, a $oTemplate is provided.
     */
    $oTemplate = Template::model()->getInstance($templatename);
    $aCssFiles = $oTemplate->config->files->css->filename;
    $aJsFiles = $oTemplate->config->files->js->filename;
    $aOtherFiles = $oTemplate->otherFiles;
    //var_dump($aOtherFiles); die();
    if (stripos($line, "{TEMPLATECSS}")) {
        // If the template has files for css, we can't publish the files one by one, but we must publish them as a whole directory
        // TODO : extend asset manager so it check for file modification even in directory mode
        if (!YII_DEBUG || count($aOtherFiles) < 0) {
            foreach ($aCssFiles as $sCssFile) {
                if (file_exists($oTemplate->path . DIRECTORY_SEPARATOR . $sCssFile)) {
                    Yii::app()->getClientScript()->registerCssFile(App()->getAssetManager()->publish($oTemplate->path . DIRECTORY_SEPARATOR . $sCssFile), $sCssFile['media']);
                }
            }
        } else {
            foreach ($aCssFiles as $sCssFile) {
                if (file_exists($oTemplate->path . DIRECTORY_SEPARATOR . $sCssFile)) {
                    Yii::app()->getClientScript()->registerCssFile("{$templateurl}{$sCssFile}", $sCssFile['media']);
                }
            }
        }
        /* RTL CSS */
        if (getLanguageRTL(App()->language)) {
            $aCssFiles = (array) $oTemplate->config->files->rtl->css->filename;
            if (!YII_DEBUG) {
                foreach ($aCssFiles as $sCssFile) {
                    if (file_exists($oTemplate->path . DIRECTORY_SEPARATOR . $sCssFile)) {
                        Yii::app()->getClientScript()->registerCssFile(App()->getAssetManager()->publish($oTemplate->path . DIRECTORY_SEPARATOR . $sCssFile), $sCssFile['media']);
                    }
                }
            } else {
                foreach ($aCssFiles as $sCssFile) {
                    if (file_exists($oTemplate->path . DIRECTORY_SEPARATOR . $sCssFile)) {
                        Yii::app()->getClientScript()->registerCssFile("{$templateurl}{$sCssFile}", $sCssFile['media']);
                    }
                }
            }
        }
    }
    if (stripos($line, "{TEMPLATEJS}")) {
        if (!YII_DEBUG) {
            foreach ($aJsFiles as $sJsFile) {
                if (file_exists($oTemplate->path . DIRECTORY_SEPARATOR . $sJsFile)) {
                    App()->getClientScript()->registerScriptFile(App()->getAssetManager()->publish($oTemplate->path . DIRECTORY_SEPARATOR . $sJsFile));
                }
            }
        } else {
            foreach ($aJsFiles as $sJsFile) {
                if (file_exists($oTemplate->path . DIRECTORY_SEPARATOR . $sJsFile)) {
                    Yii::app()->getClientScript()->registerScriptFile("{$templateurl}{$sJsFile}");
                }
            }
        }
        /* RTL JS */
        if (getLanguageRTL(App()->language)) {
            $aJsFiles = (array) $oTemplate->config->files->rtl->js->filename;
            if (!YII_DEBUG) {
                foreach ($aJsFiles as $aJsFile) {
                    if (file_exists($oTemplate->path . DIRECTORY_SEPARATOR . $aJsFile)) {
                        App()->getClientScript()->registerScriptFile(App()->getAssetManager()->publish($oTemplate->path . DIRECTORY_SEPARATOR . $aJsFile));
                    }
                }
            } else {
                foreach ($aJsFiles as $sJsFile) {
                    if (file_exists($oTemplate->path . DIRECTORY_SEPARATOR . $sJsFile)) {
                        Yii::app()->getClientScript()->registerScriptFile("{$templateurl}{$sJsFile}");
                    }
                }
            }
        }
    }
    // surveyformat
    if (isset($thissurvey['format'])) {
        $surveyformat = str_replace(array("A", "S", "G"), array("allinone", "questionbyquestion", "groupbygroup"), $thissurvey['format']);
    } else {
        $surveyformat = "";
    }
    if ($oTemplate->config->engine->cssframework) {
        $surveyformat .= " " . $oTemplate->config->engine->cssframework . "-engine ";
    }
    if (isset(Yii::app()->session['step']) && Yii::app()->session['step'] % 2 && $surveyformat != "allinone") {
        $surveyformat .= " page-odd";
    }
    if (isset($thissurvey['questionindex']) && $thissurvey['questionindex'] > 0 && $surveyformat != "allinone" && (isset(Yii::app()->session['step']) && Yii::app()->session['step'] > 0)) {
        $surveyformat .= " withindex";
    }
    if (isset($thissurvey['showprogress']) && $thissurvey['showprogress'] == "Y") {
        $surveyformat .= " showprogress";
    }
    if (isset($thissurvey['showqnumcode'])) {
        $surveyformat .= " showqnumcode-" . $thissurvey['showqnumcode'];
    }
    // real survey contact
    if (isset($surveylist) && isset($surveylist['contact'])) {
        $surveycontact = $surveylist['contact'];
    } elseif (isset($surveylist) && isset($thissurvey['admin']) && $thissurvey['admin'] != "") {
        $surveycontact = sprintf(gT("Please contact %s ( %s ) for further assistance."), $thissurvey['admin'], $thissurvey['adminemail']);
    } else {
        $surveycontact = "";
    }
    // If there are non-bracketed replacements to be made do so above this line.
    // Only continue in this routine if there are bracketed items to replace {}
    if (strpos($line, "{") === false) {
        // process string anyway so that it can be pretty-printed
        return LimeExpressionManager::ProcessString($line, $questionNum, NULL, false, 1, 1, true);
    }
    if ($showgroupinfo == 'both' || $showgroupinfo == 'name' || $showgroupinfo == 'choose' && !isset($thissurvey['showgroupinfo']) || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'B' || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'N') {
        $_groupname = isset($groupname) ? $groupname : '';
    } else {
        $_groupname = '';
    }
    if ($showgroupinfo == 'both' || $showgroupinfo == 'description' || $showgroupinfo == 'choose' && !isset($thissurvey['showgroupinfo']) || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'B' || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'D') {
        $_groupdescription = isset($groupdescription) ? $groupdescription : '';
    } else {
        $_groupdescription = '';
    }
    if (!isset($totalquestions)) {
        $totalquestions = 0;
    }
    $_totalquestionsAsked = $totalquestions;
    if ($showxquestions == 'show' || $showxquestions == 'choose' && !isset($thissurvey['showxquestions']) || $showxquestions == 'choose' && $thissurvey['showxquestions'] == 'Y') {
        if ($_totalquestionsAsked < 1) {
            $_therearexquestions = gT("There are no questions in this survey");
            // Singular
        } elseif ($_totalquestionsAsked == 1) {
            $_therearexquestions = gT("There is 1 question in this survey");
            //Singular
        } else {
            $_therearexquestions = gT("There are {NUMBEROFQUESTIONS} questions in this survey.");
            //Note this line MUST be before {NUMBEROFQUESTIONS}
        }
    } else {
        $_therearexquestions = '';
    }
    if (isset($token)) {
        $_token = $token;
    } elseif (isset($clienttoken)) {
        $_token = htmlentities($clienttoken, ENT_QUOTES, 'UTF-8');
        // or should it be URL-encoded?
    } else {
        $_token = '';
    }
    // Expiry
    if (isset($thissurvey['expiry'])) {
        $dateformatdetails = getDateFormatData($thissurvey['surveyls_dateformat']);
        Yii::import('application.libraries.Date_Time_Converter', true);
        $datetimeobj = new Date_Time_Converter($thissurvey['expiry'], "Y-m-d");
        $_dateoutput = $datetimeobj->convert($dateformatdetails['phpdate']);
    } else {
        $_dateoutput = '-';
    }
    $_submitbutton = "<input class='submit btn btn-default' type='submit' value=' " . gT("Submit") . " ' name='move2' onclick=\"javascript:document.limesurvey.move.value = 'movesubmit';\" />";
    if (isset($thissurvey['surveyls_url']) and $thissurvey['surveyls_url'] != "") {
        if (trim($thissurvey['surveyls_urldescription']) != '') {
            $_linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_urldescription']}</a>";
        } else {
            $_linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_url']}</a>";
        }
    } else {
        $_linkreplace = '';
    }
    if (isset($thissurvey['sid']) && isset($_SESSION['survey_' . $thissurvey['sid']]['srid']) && $thissurvey['active'] == 'Y') {
        $iscompleted = SurveyDynamic::model($surveyid)->isCompleted($_SESSION['survey_' . $thissurvey['sid']]['srid']);
    } else {
        $iscompleted = false;
    }
    if (isset($surveyid) && !$iscompleted) {
        $_clearall = CHtml::htmlButton(gT("Exit and clear survey"), array('type' => 'submit', 'id' => "clearall", 'value' => 'clearall', 'name' => 'clearall', 'class' => 'clearall button  btn btn-default btn-lg  col-xs-4 hidden', 'data-confirmedby' => 'confirm-clearall', 'title' => gT("This action need confirmation.")));
        $_clearall .= CHtml::checkBox("confirm-clearall", false, array('id' => 'confirm-clearall', 'value' => 'confirm', 'class' => 'hide jshide  btn btn-default btn-lg  col-xs-4'));
        $_clearall .= CHtml::label(gT("Are you sure you want to clear all your responses?"), 'confirm-clearall', array('class' => 'hide jshide  btn btn-default btn-lg  col-xs-4'));
        $_clearalllinks = '<li><a href="#" id="clearallbtnlink">' . gT("Exit and clear survey") . '</a></li>';
    } else {
        $_clearall = "";
        $_clearalllinks = '';
    }
    if (isset(Yii::app()->session['datestamp'])) {
        $_datestamp = Yii::app()->session['datestamp'];
    } else {
        $_datestamp = '-';
    }
    if (isset($thissurvey['allowsave']) and $thissurvey['allowsave'] == "Y") {
        $_saveall = doHtmlSaveAll(isset($move) ? $move : NULL);
        $_savelinks = doHtmlSaveLinks(isset($move) ? $move : NULL);
    } else {
        $_saveall = "";
        $_savelinks = "";
    }
    if (isset($thissurvey['allowprev']) && $thissurvey['allowprev'] == "N") {
        $_strreview = "";
    } else {
        $_strreview = gT("If you want to check any of the answers you have made, and/or change them, you can do that now by clicking on the [<< prev] button and browsing through your responses.");
    }
    if (isset($surveyid)) {
        $restartparam = array();
        if ($_token) {
            $restartparam['token'] = sanitize_token($_token);
        }
        // urlencode with needed with sanitize_token
        if (Yii::app()->request->getQuery('lang')) {
            $restartparam['lang'] = sanitize_languagecode(Yii::app()->request->getQuery('lang'));
        } elseif ($s_lang) {
            $restartparam['lang'] = $s_lang;
        }
        $restartparam['newtest'] = "Y";
        $restarturl = Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}", $restartparam);
        $_restart = "<a href='{$restarturl}'>" . gT("Restart this Survey") . "</a>";
    } else {
        $_restart = "";
    }
    if (isset($thissurvey['anonymized']) && $thissurvey['anonymized'] == 'Y') {
        $_savealert = gT("To remain anonymous please use a pseudonym as your username, also an email address is not required.");
    } else {
        $_savealert = "";
    }
    if (isset($surveyid)) {
        if ($_token) {
            $returnlink = Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}", array('token' => Token::sanitizeToken($_token)));
        } else {
            $returnlink = Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}");
        }
        $_return_to_survey = "<a href='{$returnlink}'>" . gT("Return to survey") . "</a>";
    } else {
        $_return_to_survey = "";
    }
    // Save Form
    $_saveform = "<table class='save-survey-form'><tr class='save-survey-row save-survey-name'><td class='save-survey-label label-cell' align='right'><label for='savename'>" . gT("Name") . "</label>:</td><td class='save-survey-input input-cell'><input type='text' name='savename' id='savename' value='";
    if (isset($_POST['savename'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['savename']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr class='save-survey-row save-survey-password-1'><td class='save-survey-label label-cell' align='right'><label for='savepass'>" . gT("Password") . "</label>:</td><td class='save-survey-input input-cell'><input type='password' id='savepass' name='savepass' value='";
    if (isset($_POST['savepass'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['savepass']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr class='save-survey-row save-survey-password-2'><td class='save-survey-label label-cell' align='right'><label for='savepass2'>" . gT("Repeat password") . "</label>:</td><td class='save-survey-input input-cell'><input type='password' id='savepass2' name='savepass2' value='";
    if (isset($_POST['savepass2'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['savepass2']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr class='save-survey-row save-survey-email'><td class='save-survey-label label-cell' align='right'><label for='saveemail'>" . gT("Your email address") . "</label>:</td><td class='save-survey-input input-cell'><input type='text' id='saveemail' name='saveemail' value='";
    if (isset($_POST['saveemail'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['saveemail']));
    }
    $_saveform .= "' /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
        $_saveform .= "<tr class='save-survey-row save-survey-captcha'><td class='save-survey-label label-cell' align='right'><label for='loadsecurity'>" . gT("Security question") . "</label>:</td><td class='save-survey-input input-cell'><table class='captcha-table'><tr><td class='captcha-image' valign='middle'><img alt='' src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . (isset($surveyid) ? $surveyid : '')) . "' /></td><td class='captcha-input' valign='middle' style='text-align:left'><input type='text' size='5' maxlength='3' id='loadsecurity' name='loadsecurity' value='' /></td></tr></table></td></tr>\n";
    }
    $_saveform .= "<tr><td align='right'></td><td></td></tr>\n" . "<tr class='save-survey-row save-survey-submit'><td class='save-survey-label label-cell'><label class='hide jshide' for='savebutton'>" . gT("Save Now") . "</label></td><td class='save-survey-input input-cell'><input type='submit' id='savebutton' name='savesubmit' class='button' value='" . gT("Save Now") . "' /></td></tr>\n" . "</table>";
    // Load Form
    $_loadform = "<table class='load-survey-form'><tr class='load-survey-row load-survey-name'><td class='load-survey-label label-cell' align='right'><label for='loadname'>" . gT("Saved name") . "</label>:</td><td class='load-survey-input input-cell'><input type='text' id='loadname' name='loadname' value='";
    if (isset($loadname)) {
        $_loadform .= HTMLEscape(autoUnescape($loadname));
    }
    $_loadform .= "' /></td></tr>\n" . "<tr class='load-survey-row load-survey-password'><td class='load-survey-label label-cell' align='right'><label for='loadpass'>" . gT("Password") . "</label>:</td><td class='load-survey-input input-cell'><input type='password' id='loadpass' name='loadpass' value='";
    if (isset($loadpass)) {
        $_loadform .= HTMLEscape(autoUnescape($loadpass));
    }
    $_loadform .= "' /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
        $_loadform .= "<tr class='load-survey-row load-survey-captcha'><td class='load-survey-label label-cell' align='right'><label for='loadsecurity'>" . gT("Security question") . "</label>:</td><td class='load-survey-input input-cell'><table class='captcha-table'><tr><td class='captcha-image' valign='middle'><img src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . (isset($surveyid) ? $surveyid : '')) . "' alt='' /></td><td class='captcha-input' valign='middle'><input type='text' size='5' maxlength='3' id='loadsecurity' name='loadsecurity' value='' alt=''/></td></tr></table></td></tr>\n";
    }
    $_loadform .= "<tr class='load-survey-row load-survey-submit'><td class='load-survey-label label-cell'><label class='hide jshide' for='loadbutton'>" . gT("Load now") . "</label></td><td class='load-survey-input input-cell'><input type='submit' id='loadbutton' class='button' value='" . gT("Load now") . "' /></td></tr></table>\n";
    // Assessments
    $assessmenthtml = "";
    if (isset($surveyid) && !is_null($surveyid) && function_exists('doAssessment')) {
        $assessmentdata = doAssessment($surveyid, true);
        $_assessment_current_total = $assessmentdata['total'];
        if (stripos($line, "{ASSESSMENTS}")) {
            $assessmenthtml = doAssessment($surveyid, false);
        }
    } else {
        $_assessment_current_total = '';
    }
    if (isset($thissurvey['googleanalyticsapikey']) && trim($thissurvey['googleanalyticsapikey']) != '') {
        $_googleAnalyticsAPIKey = trim($thissurvey['googleanalyticsapikey']);
    } else {
        $_googleAnalyticsAPIKey = trim(getGlobalSetting('googleanalyticsapikey'));
    }
    $_googleAnalyticsStyle = isset($thissurvey['googleanalyticsstyle']) ? $thissurvey['googleanalyticsstyle'] : '0';
    $_googleAnalyticsJavaScript = '';
    if ($_googleAnalyticsStyle != '' && $_googleAnalyticsStyle != 0 && $_googleAnalyticsAPIKey != '') {
        switch ($_googleAnalyticsStyle) {
            case '1':
                // Default Google Tracking
                $_googleAnalyticsJavaScript = <<<EOD
<script>
(function(i,s,o,g,r,a,m){ i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments) },i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', '{$_googleAnalyticsAPIKey}', 'auto');  // Replace with your property ID.
ga('send', 'pageview');

</script>

EOD;
                break;
            case '2':
                // SurveyName-[SID]/[GSEQ]-GroupName - create custom GSEQ based upon page step
                $moveInfo = LimeExpressionManager::GetLastMoveResult();
                if (is_null($moveInfo)) {
                    $gseq = 'welcome';
                } else {
                    if ($moveInfo['finished']) {
                        $gseq = 'finished';
                    } else {
                        if (isset($moveInfo['at_start']) && $moveInfo['at_start']) {
                            $gseq = 'welcome';
                        } else {
                            if (is_null($_groupname)) {
                                $gseq = 'printanswers';
                            } else {
                                $gseq = $moveInfo['gseq'] + 1;
                            }
                        }
                    }
                }
                $_trackURL = htmlspecialchars($thissurvey['name'] . '-[' . $surveyid . ']/[' . $gseq . ']-' . $_groupname);
                $_googleAnalyticsJavaScript = <<<EOD
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', '{$_googleAnalyticsAPIKey}', 'auto');  // Replace with your property ID.
ga('send', 'pageview');
ga('send', 'pageview', '{$_trackURL}');

</script>
EOD;
                break;
        }
    }
    $_endtext = '';
    if (isset($thissurvey['surveyls_endtext']) && trim($thissurvey['surveyls_endtext']) != '') {
        $_endtext = $thissurvey['surveyls_endtext'];
    }
    $sitelogo = !empty($oTemplate->siteLogo) ? '<img src="' . App()->getAssetManager()->publish($oTemplate->path . '/' . $oTemplate->siteLogo) . '"/>' : '';
    // Set the array of replacement variables here - don't include curly braces
    $coreReplacements = array();
    $coreReplacements['ACTIVE'] = isset($thissurvey['active']) && !($thissurvey['active'] != "Y");
    $coreReplacements['ANSWERSCLEARED'] = gT("Answers cleared");
    $coreReplacements['ASSESSMENTS'] = $assessmenthtml;
    $coreReplacements['ASSESSMENT_CURRENT_TOTAL'] = $_assessment_current_total;
    $coreReplacements['ASSESSMENT_HEADING'] = gT("Your assessment");
    $coreReplacements['CHECKJAVASCRIPT'] = "<noscript><span class='warningjs'>" . gT("Caution: JavaScript execution is disabled in your browser. You may not be able to answer all questions in this survey. Please, verify your browser parameters.") . "</span></noscript>";
    $coreReplacements['CLEARALL'] = $_clearall;
    $coreReplacements['CLEARALL_LINKS'] = $_clearalllinks;
    $coreReplacements['CLOSEWINDOW'] = '';
    // Obsolete tag - keep this line for compatibility reaons
    $coreReplacements['COMPLETED'] = isset($redata['completed']) ? $redata['completed'] : '';
    // global
    $coreReplacements['DATESTAMP'] = $_datestamp;
    $coreReplacements['ENDTEXT'] = $_endtext;
    $coreReplacements['EXPIRY'] = $_dateoutput;
    $coreReplacements['ADMINNAME'] = isset($thissurvey['admin']) ? $thissurvey['admin'] : '';
    $coreReplacements['ADMINEMAIL'] = isset($thissurvey['adminemail']) ? $thissurvey['adminemail'] : '';
    $coreReplacements['GID'] = Yii::app()->getConfig('gid', '');
    // Use the gid of the question, except if we are not in question (Randomization group name)
    $coreReplacements['GOOGLE_ANALYTICS_API_KEY'] = $_googleAnalyticsAPIKey;
    $coreReplacements['GOOGLE_ANALYTICS_JAVASCRIPT'] = $_googleAnalyticsJavaScript;
    $coreReplacements['GROUPDESCRIPTION'] = $_groupdescription;
    $coreReplacements['GROUPNAME'] = $_groupname;
    $coreReplacements['LANG'] = App()->language;
    $coreReplacements['LANGUAGECHANGER'] = isset($languagechanger) ? $languagechanger : '';
    // global
    $coreReplacements['LOADERROR'] = isset($errormsg) ? $errormsg : '';
    // global
    $coreReplacements['LOADFORM'] = $_loadform;
    $coreReplacements['LOADHEADING'] = gT("Load a previously saved survey");
    $coreReplacements['LOADMESSAGE'] = gT("You can load a survey that you have previously saved from this screen.") . "<br />" . gT("Type in the 'name' you used to save the survey, and the password.") . "<br />";
    $coreReplacements['NAVIGATOR'] = isset($navigator) ? $navigator : '';
    // global
    $coreReplacements['MOVEPREVBUTTON'] = isset($moveprevbutton) ? $moveprevbutton : '';
    // global
    $coreReplacements['MOVENEXTBUTTON'] = isset($movenextbutton) ? $movenextbutton : '';
    // global
    $coreReplacements['NOSURVEYID'] = isset($surveylist) ? $surveylist['nosid'] : '';
    $coreReplacements['NUMBEROFQUESTIONS'] = $_totalquestionsAsked;
    $coreReplacements['PERCENTCOMPLETE'] = isset($percentcomplete) ? $percentcomplete : '';
    // global
    $coreReplacements['PRIVACY'] = isset($privacy) ? $privacy : '';
    // global
    $coreReplacements['PRIVACYMESSAGE'] = "<span style='font-weight:bold; font-style: italic;'>" . gT("A Note On Privacy") . "</span><br />" . gT("This survey is anonymous.") . "<br />" . gT("The record of your survey responses does not contain any identifying information about you, unless a specific survey question explicitly asked for it.") . ' ' . gT("If you used an identifying token to access this survey, please rest assured that this token will not be stored together with your responses. It is managed in a separate database and will only be updated to indicate whether you did (or did not) complete this survey. There is no way of matching identification tokens with survey responses.");
    $coreReplacements['QUESTION_INDEX'] = isset($questionindex) ? $questionindex : '';
    $coreReplacements['QUESTION_INDEX_MENU'] = isset($questionindexmenu) ? $questionindexmenu : '';
    $coreReplacements['RESTART'] = $_restart;
    $coreReplacements['RETURNTOSURVEY'] = $_return_to_survey;
    $coreReplacements['SAVE_LINKS'] = $_savelinks;
    $coreReplacements['SAVE'] = $_saveall;
    $coreReplacements['SAVEALERT'] = $_savealert;
    $coreReplacements['SAVEDID'] = isset($saved_id) ? $saved_id : '';
    // global
    $coreReplacements['SAVEERROR'] = isset($errormsg) ? $errormsg : '';
    // global - same as LOADERROR
    $coreReplacements['SAVEFORM'] = $_saveform;
    $coreReplacements['SAVEHEADING'] = gT("Save your unfinished survey");
    $coreReplacements['SAVEMESSAGE'] = gT("Enter a name and password for this survey and click save below.") . "<br />\n" . gT("Your survey will be saved using that name and password, and can be completed later by logging in with the same name and password.") . "<br /><br />\n<span class='emailoptional'>" . gT("If you give an email address, an email containing the details will be sent to you.") . "</span><br /><br />\n" . gT("After having clicked the save button you can either close this browser window or continue filling out the survey.");
    $coreReplacements['SID'] = Yii::app()->getConfig('surveyID', '');
    // Allways use surveyID from config
    $coreReplacements['SITENAME'] = isset($sitename) ? $sitename : '';
    // global
    $coreReplacements['SITELOGO'] = $sitelogo;
    $coreReplacements['SUBMITBUTTON'] = $_submitbutton;
    $coreReplacements['SUBMITCOMPLETE'] = "<strong>" . gT("Thank you!") . "<br /><br />" . gT("You have completed answering the questions in this survey.") . "</strong><br /><br />" . gT("Click on 'Submit' now to complete the process and save your answers.");
    $coreReplacements['SUBMITREVIEW'] = $_strreview;
    $coreReplacements['SURVEYCONTACT'] = $surveycontact;
    $coreReplacements['SURVEYDESCRIPTION'] = isset($thissurvey['description']) ? $thissurvey['description'] : '';
    $coreReplacements['SURVEYFORMAT'] = isset($surveyformat) ? $surveyformat : '';
    // global
    $coreReplacements['SURVEYLANGUAGE'] = App()->language;
    $coreReplacements['SURVEYLIST'] = isset($surveylist) ? $surveylist['list'] : '';
    $coreReplacements['SURVEYLISTHEADING'] = isset($surveylist) ? $surveylist['listheading'] : '';
    $coreReplacements['SURVEYNAME'] = isset($thissurvey['name']) ? $thissurvey['name'] : '';
    $coreReplacements['SURVEYRESOURCESURL'] = isset($thissurvey['sid']) ? Yii::app()->getConfig("uploadurl") . '/surveys/' . $thissurvey['sid'] . '/' : '';
    $coreReplacements['TEMPLATECSS'] = $_templatecss;
    $coreReplacements['TEMPLATEJS'] = $_templatejs;
    $coreReplacements['TEMPLATEURL'] = $templateurl;
    $coreReplacements['THEREAREXQUESTIONS'] = $_therearexquestions;
    $coreReplacements['TOKEN'] = !$anonymized ? $_token : '';
    // Silently replace TOKEN by empty string
    $coreReplacements['URL'] = $_linkreplace;
    $coreReplacements['WELCOME'] = isset($thissurvey['welcome']) ? $thissurvey['welcome'] : '';
    if (!isset($replacements['QID'])) {
        Yii::import('application.helpers.SurveyRuntimeHelper');
        $coreReplacements = array_merge($coreReplacements, SurveyRuntimeHelper::getQuestionReplacement(null));
        // so $replacements overrides core values
    }
    if (!is_null($replacements) && is_array($replacements)) {
        $doTheseReplacements = array_merge($coreReplacements, $replacements);
        // so $replacements overrides core values
    } else {
        $doTheseReplacements = $coreReplacements;
    }
    // Now do all of the replacements - In rare cases, need to do 3 deep recursion, that that is default
    $line = LimeExpressionManager::ProcessString($line, $questionNum, $doTheseReplacements, false, 3, 1, false, true, $bStaticReplacement);
    return $line;
}
Exemplo n.º 28
0
 function actionparticipants()
 {
     $iSurveyID = Yii::app()->request->getQuery('surveyid');
     $sLanguageCode = Yii::app()->request->getQuery('langcode');
     $sToken = sanitize_token(Yii::app()->request->getQuery('token'));
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('sanitize');
     if (!$iSurveyID) {
         $this->redirect(array('/'));
     }
     $iSurveyID = (int) $iSurveyID;
     //Make sure it's an integer (protect from SQL injects)
     //Check that there is a SID
     // Get passed language from form, so that we dont lose 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, "The survey in which you are trying to participate 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, $sToken, false);
         $oToken = Token::model($iSurveyID)->findByAttributes(array('token' => $sToken));
         if (!isset($oToken)) {
             $sMessage = gT('You are not a participant in this survey.');
         } else {
             if (substr($oToken->emailstatus, 0, strlen('OptOut')) !== 'OptOut') {
                 $oToken->emailstatus = 'OptOut';
                 $oToken->save();
                 $sMessage = gT('You have been successfully removed from this survey.');
             } else {
                 $sMessage = gT('You have been already removed from this survey.');
             }
             if (!empty($oToken->participant_id)) {
                 //Participant also exists in central db
                 $oParticipant = Participant::model()->findByPk($oToken->participant_id);
                 if ($oParticipant->blacklisted == "Y") {
                     $sMessage .= "<br />";
                     $sMessage .= gT("You have already been removed from the central participants list for this site");
                 } else {
                     $oParticipant->blacklisted = 'Y';
                     $oParticipant->save();
                     $sMessage .= "<br />";
                     $sMessage .= gT("You have been removed from the central participants list for this site");
                 }
             }
         }
     }
     //PRINT COMPLETED PAGE
     if (!$aSurveyInfo['templatedir']) {
         $sTemplate = getTemplatePath(Yii::app()->getConfig("defaulttemplate"));
     } else {
         $sTemplate = getTemplatePath($aSurveyInfo['templatedir']);
     }
     $this->_renderHtml($sMessage, $sTemplate, $aSurveyInfo);
 }
 private function _saveSettings()
 {
     if ($_POST['action'] !== "globalsettingssave") {
         return;
     }
     if (Yii::app()->session['USER_RIGHT_CONFIGURATOR'] != 1) {
         $this->getController()->redirect($this->getController()->createUrl('/admin'));
     }
     $clang = $this->getController()->lang;
     Yii::app()->loadHelper('surveytranslator');
     $maxemails = $_POST['maxemails'];
     if (sanitize_int($_POST['maxemails']) < 1) {
         $maxemails = 1;
     }
     $defaultlang = sanitize_languagecode($_POST['defaultlang']);
     $aRestrictToLanguages = explode(' ', sanitize_languagecodeS($_POST['restrictToLanguages']));
     if (!in_array($defaultlang, $aRestrictToLanguages)) {
         // Force default language in restrictToLanguages
         $aRestrictToLanguages[] = $defaultlang;
     }
     if (count(array_diff(array_keys(getLanguageData(false, Yii::app()->session['adminlang'])), $aRestrictToLanguages)) == 0) {
         $aRestrictToLanguages = '';
     } else {
         $aRestrictToLanguages = implode(' ', $aRestrictToLanguages);
     }
     setGlobalSetting('defaultlang', $defaultlang);
     setGlobalSetting('restrictToLanguages', trim($aRestrictToLanguages));
     setGlobalSetting('sitename', strip_tags($_POST['sitename']));
     setGlobalSetting('updatecheckperiod', (int) $_POST['updatecheckperiod']);
     setGlobalSetting('defaulthtmleditormode', sanitize_paranoid_string($_POST['defaulthtmleditormode']));
     setGlobalSetting('defaultquestionselectormode', sanitize_paranoid_string($_POST['defaultquestionselectormode']));
     setGlobalSetting('defaulttemplateeditormode', sanitize_paranoid_string($_POST['defaulttemplateeditormode']));
     setGlobalSetting('defaulttemplate', sanitize_paranoid_string($_POST['defaulttemplate']));
     setGlobalSetting('admintheme', sanitize_paranoid_string($_POST['admintheme']));
     setGlobalSetting('adminthemeiconsize', trim(file_get_contents(Yii::app()->getConfig("styledir") . DIRECTORY_SEPARATOR . sanitize_paranoid_string($_POST['admintheme']) . DIRECTORY_SEPARATOR . 'iconsize')));
     setGlobalSetting('emailmethod', strip_tags($_POST['emailmethod']));
     setGlobalSetting('emailsmtphost', strip_tags(returnGlobal('emailsmtphost')));
     if (returnGlobal('emailsmtppassword') != 'somepassword') {
         setGlobalSetting('emailsmtppassword', strip_tags(returnGlobal('emailsmtppassword')));
     }
     setGlobalSetting('bounceaccounthost', strip_tags(returnGlobal('bounceaccounthost')));
     setGlobalSetting('bounceaccounttype', strip_tags(returnGlobal('bounceaccounttype')));
     setGlobalSetting('bounceencryption', strip_tags(returnGlobal('bounceencryption')));
     setGlobalSetting('bounceaccountuser', strip_tags(returnGlobal('bounceaccountuser')));
     if (returnGlobal('bounceaccountpass') != 'enteredpassword') {
         setGlobalSetting('bounceaccountpass', strip_tags(returnGlobal('bounceaccountpass')));
     }
     setGlobalSetting('emailsmtpssl', sanitize_paranoid_string(Yii::app()->request->getPost('emailsmtpssl', '')));
     setGlobalSetting('emailsmtpdebug', sanitize_int(Yii::app()->request->getPost('emailsmtpdebug', '0')));
     setGlobalSetting('emailsmtpuser', strip_tags(returnGlobal('emailsmtpuser')));
     setGlobalSetting('filterxsshtml', strip_tags($_POST['filterxsshtml']));
     setGlobalSetting('siteadminbounce', strip_tags($_POST['siteadminbounce']));
     setGlobalSetting('siteadminemail', strip_tags($_POST['siteadminemail']));
     setGlobalSetting('siteadminname', strip_tags($_POST['siteadminname']));
     setGlobalSetting('shownoanswer', sanitize_int($_POST['shownoanswer']));
     setGlobalSetting('showxquestions', $_POST['showxquestions']);
     setGlobalSetting('showgroupinfo', $_POST['showgroupinfo']);
     setGlobalSetting('showqnumcode', $_POST['showqnumcode']);
     $repeatheadingstemp = (int) $_POST['repeatheadings'];
     if ($repeatheadingstemp == 0) {
         $repeatheadingstemp = 25;
     }
     setGlobalSetting('repeatheadings', $repeatheadingstemp);
     setGlobalSetting('maxemails', sanitize_int($maxemails));
     $iSessionExpirationTime = (int) $_POST['iSessionExpirationTime'];
     if ($iSessionExpirationTime == 0) {
         $iSessionExpirationTime = 7200;
     }
     setGlobalSetting('iSessionExpirationTime', $iSessionExpirationTime);
     setGlobalSetting('ipInfoDbAPIKey', $_POST['ipInfoDbAPIKey']);
     setGlobalSetting('googleMapsAPIKey', $_POST['googleMapsAPIKey']);
     setGlobalSetting('googleanalyticsapikey', $_POST['googleanalyticsapikey']);
     setGlobalSetting('googletranslateapikey', $_POST['googletranslateapikey']);
     setGlobalSetting('force_ssl', $_POST['force_ssl']);
     setGlobalSetting('surveyPreview_require_Auth', $_POST['surveyPreview_require_Auth']);
     setGlobalSetting('RPCInterface', $_POST['RPCInterface']);
     $savetime = (double) $_POST['timeadjust'] * 60 . ' minutes';
     //makes sure it is a number, at least 0
     if (substr($savetime, 0, 1) != '-' && substr($savetime, 0, 1) != '+') {
         $savetime = '+' . $savetime;
     }
     setGlobalSetting('timeadjust', $savetime);
     setGlobalSetting('usercontrolSameGroupPolicy', strip_tags($_POST['usercontrolSameGroupPolicy']));
     Yii::app()->session['flashmessage'] = $clang->gT("Global settings were saved.");
     $url = htmlspecialchars_decode(Yii::app()->session['refurl']);
     if ($url) {
         Yii::app()->getController()->redirect($url);
     }
 }
Exemplo n.º 30
0
 private function _saveSettings()
 {
     if ($_POST['action'] !== "globalsettingssave") {
         return;
     }
     if (!Permission::model()->hasGlobalPermission('settings', 'update')) {
         $this->getController()->redirect(array('/admin'));
     }
     Yii::app()->loadHelper('surveytranslator');
     $iPDFFontSize = sanitize_int($_POST['pdffontsize']);
     if ($iPDFFontSize < 1) {
         $iPDFFontSize = 9;
     }
     $iPDFLogoWidth = sanitize_int($_POST['pdflogowidth']);
     if ($iPDFLogoWidth < 1) {
         $iPDFLogoWidth = 50;
     }
     $maxemails = $_POST['maxemails'];
     if (sanitize_int($_POST['maxemails']) < 1) {
         $maxemails = 1;
     }
     $defaultlang = sanitize_languagecode($_POST['defaultlang']);
     $aRestrictToLanguages = explode(' ', sanitize_languagecodeS($_POST['restrictToLanguages']));
     if (!in_array($defaultlang, $aRestrictToLanguages)) {
         // Force default language in restrictToLanguages
         $aRestrictToLanguages[] = $defaultlang;
     }
     if (count(array_diff(array_keys(getLanguageData(false, Yii::app()->session['adminlang'])), $aRestrictToLanguages)) == 0) {
         $aRestrictToLanguages = '';
     } else {
         $aRestrictToLanguages = implode(' ', $aRestrictToLanguages);
     }
     setGlobalSetting('defaultlang', $defaultlang);
     setGlobalSetting('restrictToLanguages', trim($aRestrictToLanguages));
     setGlobalSetting('sitename', strip_tags($_POST['sitename']));
     setGlobalSetting('defaulthtmleditormode', sanitize_paranoid_string($_POST['defaulthtmleditormode']));
     setGlobalSetting('defaultquestionselectormode', sanitize_paranoid_string($_POST['defaultquestionselectormode']));
     setGlobalSetting('defaulttemplateeditormode', sanitize_paranoid_string($_POST['defaulttemplateeditormode']));
     if (!Yii::app()->getConfig('demoMode')) {
         $sTemplate = Yii::app()->getRequest()->getPost("defaulttemplate");
         if (array_key_exists($sTemplate, getTemplateList())) {
             setGlobalSetting('defaulttemplate', $sTemplate);
         }
     }
     setGlobalSetting('admintheme', sanitize_paranoid_string($_POST['admintheme']));
     setGlobalSetting('adminthemeiconsize', trim(file_get_contents(Yii::app()->getConfig("styledir") . DIRECTORY_SEPARATOR . sanitize_paranoid_string($_POST['admintheme']) . DIRECTORY_SEPARATOR . 'iconsize')));
     setGlobalSetting('emailmethod', strip_tags($_POST['emailmethod']));
     setGlobalSetting('emailsmtphost', strip_tags(returnGlobal('emailsmtphost')));
     if (returnGlobal('emailsmtppassword') != 'somepassword') {
         setGlobalSetting('emailsmtppassword', strip_tags(returnGlobal('emailsmtppassword')));
     }
     setGlobalSetting('bounceaccounthost', strip_tags(returnGlobal('bounceaccounthost')));
     setGlobalSetting('bounceaccounttype', strip_tags(returnGlobal('bounceaccounttype')));
     setGlobalSetting('bounceencryption', strip_tags(returnGlobal('bounceencryption')));
     setGlobalSetting('bounceaccountuser', strip_tags(returnGlobal('bounceaccountuser')));
     if (returnGlobal('bounceaccountpass') != 'enteredpassword') {
         setGlobalSetting('bounceaccountpass', strip_tags(returnGlobal('bounceaccountpass')));
     }
     setGlobalSetting('emailsmtpssl', sanitize_paranoid_string(Yii::app()->request->getPost('emailsmtpssl', '')));
     setGlobalSetting('emailsmtpdebug', sanitize_int(Yii::app()->request->getPost('emailsmtpdebug', '0')));
     setGlobalSetting('emailsmtpuser', strip_tags(returnGlobal('emailsmtpuser')));
     setGlobalSetting('filterxsshtml', strip_tags($_POST['filterxsshtml']));
     $warning = '';
     // make sure emails are valid before saving them
     if (Yii::app()->request->getPost('siteadminbounce', '') == '' || validateEmailAddress(Yii::app()->request->getPost('siteadminbounce'))) {
         setGlobalSetting('siteadminbounce', strip_tags(Yii::app()->request->getPost('siteadminbounce')));
     } else {
         $warning .= gT("Warning! Admin bounce email was not saved because it was not valid.") . '<br/>';
     }
     if (Yii::app()->request->getPost('siteadminemail', '') == '' || validateEmailAddress(Yii::app()->request->getPost('siteadminemail'))) {
         setGlobalSetting('siteadminemail', strip_tags(Yii::app()->request->getPost('siteadminemail')));
     } else {
         $warning .= gT("Warning! Admin email was not saved because it was not valid.") . '<br/>';
     }
     setGlobalSetting('siteadminname', strip_tags($_POST['siteadminname']));
     setGlobalSetting('shownoanswer', sanitize_int($_POST['shownoanswer']));
     setGlobalSetting('showxquestions', $_POST['showxquestions']);
     setGlobalSetting('showgroupinfo', $_POST['showgroupinfo']);
     setGlobalSetting('showqnumcode', $_POST['showqnumcode']);
     $repeatheadingstemp = (int) $_POST['repeatheadings'];
     if ($repeatheadingstemp == 0) {
         $repeatheadingstemp = 25;
     }
     setGlobalSetting('repeatheadings', $repeatheadingstemp);
     setGlobalSetting('maxemails', sanitize_int($maxemails));
     $iSessionExpirationTime = (int) $_POST['iSessionExpirationTime'];
     if ($iSessionExpirationTime == 0) {
         $iSessionExpirationTime = 7200;
     }
     setGlobalSetting('iSessionExpirationTime', $iSessionExpirationTime);
     setGlobalSetting('ipInfoDbAPIKey', $_POST['ipInfoDbAPIKey']);
     setGlobalSetting('pdffontsize', $iPDFFontSize);
     setGlobalSetting('pdfshowheader', $_POST['pdfshowheader']);
     setGlobalSetting('pdflogowidth', $iPDFLogoWidth);
     setGlobalSetting('pdfheadertitle', $_POST['pdfheadertitle']);
     setGlobalSetting('pdfheaderstring', $_POST['pdfheaderstring']);
     setGlobalSetting('googleMapsAPIKey', $_POST['googleMapsAPIKey']);
     setGlobalSetting('googleanalyticsapikey', $_POST['googleanalyticsapikey']);
     setGlobalSetting('googletranslateapikey', $_POST['googletranslateapikey']);
     setGlobalSetting('force_ssl', $_POST['force_ssl']);
     setGlobalSetting('surveyPreview_require_Auth', $_POST['surveyPreview_require_Auth']);
     setGlobalSetting('RPCInterface', $_POST['RPCInterface']);
     setGlobalSetting('rpc_publish_api', (bool) $_POST['rpc_publish_api']);
     $savetime = (double) $_POST['timeadjust'] * 60 . ' minutes';
     //makes sure it is a number, at least 0
     if (substr($savetime, 0, 1) != '-' && substr($savetime, 0, 1) != '+') {
         $savetime = '+' . $savetime;
     }
     setGlobalSetting('timeadjust', $savetime);
     setGlobalSetting('usercontrolSameGroupPolicy', strip_tags($_POST['usercontrolSameGroupPolicy']));
     Yii::app()->session['flashmessage'] = $warning . gT("Global settings were saved.");
     $url = htmlspecialchars_decode(Yii::app()->session['refurl']);
     if ($url) {
         Yii::app()->getController()->redirect($url);
     }
 }