Ejemplo n.º 1
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);
 }
Ejemplo n.º 2
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);
 }
Ejemplo n.º 3
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);
 }
Ejemplo n.º 4
0
 /**
  * import from csv
  */
 function import($iSurveyId)
 {
     $clang = $this->getController()->lang;
     $iSurveyId = (int) $iSurveyId;
     if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'import')) {
         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}"));
     }
     // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY
     $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}');
     if (!$bTokenExists) {
         self::_newtokentable($iSurveyId);
     }
     App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'tokensimport.js');
     $aEncodings = aEncodingsArray();
     if (Yii::app()->request->getPost('submit')) {
         if (Yii::app()->request->getPost('csvcharset') && Yii::app()->request->getPost('csvcharset')) {
             $uploadcharset = Yii::app()->request->getPost('csvcharset');
             if (!array_key_exists($uploadcharset, $aEncodings)) {
                 $uploadcharset = 'auto';
             }
             $filterduplicatetoken = Yii::app()->request->getPost('filterduplicatetoken') && Yii::app()->request->getPost('filterduplicatetoken') == 'on';
             $filterblankemail = Yii::app()->request->getPost('filterblankemail') && Yii::app()->request->getPost('filterblankemail') == 'on';
         }
         $attrfieldnames = getAttributeFieldNames($iSurveyId);
         $duplicatelist = array();
         $invalidemaillist = array();
         $invalidformatlist = array();
         $firstline = array();
         $sPath = Yii::app()->getConfig('tempdir');
         $sFileTmpName = $_FILES['the_file']['tmp_name'];
         $sFilePath = $sPath . '/' . randomChars(20);
         if (!@move_uploaded_file($sFileTmpName, $sFilePath)) {
             $aData['sError'] = $clang->gT("Upload file not found. Check your permissions and path ({$sFilePath}) for the upload directory");
             $aData['aEncodings'] = $aEncodings;
             $aData['iSurveyId'] = $aData['surveyid'] = $iSurveyId;
             $aData['thissurvey'] = getSurveyInfo($iSurveyId);
             $this->_renderWrappedTemplate('token', array('tokenbar', 'csvupload'), $aData);
         } else {
             $xz = 0;
             $recordcount = 0;
             $xv = 0;
             // This allows to read file with MAC line endings too
             @ini_set('auto_detect_line_endings', true);
             // open it and trim the ednings
             $tokenlistarray = file($sFilePath);
             $sBaseLanguage = Survey::model()->findByPk($iSurveyId)->language;
             if (!Yii::app()->request->getPost('filterduplicatefields') || Yii::app()->request->getPost('filterduplicatefields') && count(Yii::app()->request->getPost('filterduplicatefields')) == 0) {
                 $filterduplicatefields = array('firstname', 'lastname', 'email');
             } else {
                 $filterduplicatefields = Yii::app()->request->getPost('filterduplicatefields');
             }
             $separator = returnGlobal('separator');
             foreach ($tokenlistarray as $buffer) {
                 $buffer = @mb_convert_encoding($buffer, "UTF-8", $uploadcharset);
                 if ($recordcount == 0) {
                     // Parse first line (header) from CSV
                     $buffer = removeBOM($buffer);
                     // We alow all field except tid because this one is really not needed.
                     $allowedfieldnames = array('participant_id', 'firstname', 'lastname', 'email', 'emailstatus', 'token', 'language', 'blacklisted', 'sent', 'remindersent', 'remindercount', 'validfrom', 'validuntil', 'completed', 'usesleft');
                     $allowedfieldnames = array_merge($attrfieldnames, $allowedfieldnames);
                     // Some header don't have same column name
                     $aReplacedFields = array('invited' => 'sent');
                     switch ($separator) {
                         case 'comma':
                             $separator = ',';
                             break;
                         case 'semicolon':
                             $separator = ';';
                             break;
                         default:
                             $comma = substr_count($buffer, ',');
                             $semicolon = substr_count($buffer, ';');
                             if ($semicolon > $comma) {
                                 $separator = ';';
                             } else {
                                 $separator = ',';
                             }
                     }
                     $firstline = str_getcsv($buffer, $separator, '"');
                     $firstline = array_map('trim', $firstline);
                     $ignoredcolumns = array();
                     // Now check the first line for invalid fields
                     foreach ($firstline as $index => $fieldname) {
                         $firstline[$index] = preg_replace("/(.*) <[^,]*>\$/", "\$1", $fieldname);
                         $fieldname = $firstline[$index];
                         if (!in_array($fieldname, $allowedfieldnames)) {
                             $ignoredcolumns[] = $fieldname;
                         }
                         if (array_key_exists($fieldname, $aReplacedFields)) {
                             $firstline[$index] = $aReplacedFields[$fieldname];
                         }
                     }
                     if (!in_array('firstname', $firstline) || !in_array('lastname', $firstline) || !in_array('email', $firstline)) {
                         $recordcount = count($tokenlistarray);
                         break;
                     }
                 } else {
                     $line = str_getcsv($buffer, $separator, '"');
                     if (count($firstline) != count($line)) {
                         $invalidformatlist[] = $recordcount;
                         $recordcount++;
                         continue;
                     }
                     $writearray = array_combine($firstline, $line);
                     //kick out ignored columns
                     foreach ($ignoredcolumns as $column) {
                         unset($writearray[$column]);
                     }
                     $dupfound = false;
                     $invalidemail = false;
                     if ($filterduplicatetoken != false) {
                         $dupquery = "SELECT count(tid) from {{tokens_" . intval($iSurveyId) . "}} where 1=1";
                         foreach ($filterduplicatefields as $field) {
                             if (isset($writearray[$field])) {
                                 $dupquery .= " and " . Yii::app()->db->quoteColumnName($field) . " = " . Yii::app()->db->quoteValue($writearray[$field]);
                             }
                         }
                         $dupresult = Yii::app()->db->createCommand($dupquery)->queryScalar();
                         if ($dupresult > 0) {
                             $dupfound = true;
                             $duplicatelist[] = Yii::app()->db->quoteValue($writearray['firstname']) . " " . Yii::app()->db->quoteValue($writearray['lastname']) . " (" . Yii::app()->db->quoteValue($writearray['email']) . ")";
                         }
                     }
                     $writearray['email'] = trim($writearray['email']);
                     //treat blank emails
                     if ($filterblankemail && $writearray['email'] == '') {
                         $invalidemail = true;
                         $invalidemaillist[] = $line[0] . " " . $line[1] . " ( )";
                     }
                     if ($writearray['email'] != '') {
                         $aEmailAddresses = explode(';', $writearray['email']);
                         foreach ($aEmailAddresses as $sEmailaddress) {
                             if (!validateEmailAddress($sEmailaddress)) {
                                 $invalidemail = true;
                                 $invalidemaillist[] = $line[0] . " " . $line[1] . " (" . $line[2] . ")";
                             }
                         }
                     }
                     if (isset($writearray['token'])) {
                         $writearray['token'] = sanitize_token($writearray['token']);
                     }
                     if (!$dupfound && !$invalidemail) {
                         // unset all empty value
                         foreach ($writearray as $key => $value) {
                             if ($writearray[$key] == "") {
                                 unset($writearray[$key]);
                             }
                             if (substr($value, 0, 1) == '"' && substr($value, -1) == '"') {
                                 // Fix CSV quote
                                 $value = substr($value, 1, -1);
                             }
                         }
                         // Some default value : to be moved to Token model rules in future release ?
                         // But think we have to accept invalid email etc ... then use specific scenario
                         $writearray['emailstatus'] = isset($writearray['emailstatus']) ? $writearray['emailstatus'] : "OK";
                         $writearray['language'] = isset($writearray['language']) ? $writearray['language'] : $sBaseLanguage;
                         $oToken = Token::create($iSurveyId);
                         foreach ($writearray as $key => $value) {
                             //if(in_array($key,$oToken->attributes)) Not needed because we filter attributes before
                             $oToken->{$key} = $value;
                         }
                         $ir = $oToken->save();
                         if (!$ir) {
                             $duplicatelist[] = $writearray['firstname'] . " " . $writearray['lastname'] . " (" . $writearray['email'] . ")";
                         } else {
                             $xz++;
                         }
                     }
                     $xv++;
                 }
                 $recordcount++;
             }
             $recordcount = $recordcount - 1;
             unlink($sFilePath);
             $aData['tokenlistarray'] = $tokenlistarray;
             $aData['xz'] = $xz;
             $aData['xv'] = $xv;
             $aData['recordcount'] = $recordcount;
             $aData['firstline'] = $firstline;
             $aData['duplicatelist'] = $duplicatelist;
             $aData['invalidformatlist'] = $invalidformatlist;
             $aData['invalidemaillist'] = $invalidemaillist;
             $aData['thissurvey'] = getSurveyInfo($iSurveyId);
             $aData['iSurveyId'] = $aData['surveyid'] = $iSurveyId;
             $this->_renderWrappedTemplate('token', array('tokenbar', 'csvpost'), $aData);
         }
     } else {
         $aData['aEncodings'] = $aEncodings;
         $aData['iSurveyId'] = $iSurveyId;
         $aData['thissurvey'] = getSurveyInfo($iSurveyId);
         $aData['surveyid'] = $iSurveyId;
         $aTokenTableFields = getTokenFieldsAndNames($iSurveyId);
         unset($aTokenTableFields['sent']);
         unset($aTokenTableFields['remindersent']);
         unset($aTokenTableFields['remindercount']);
         unset($aTokenTableFields['usesleft']);
         foreach ($aTokenTableFields as $sKey => $sValue) {
             if ($sValue['description'] != $sKey) {
                 $sValue['description'] .= ' - ' . $sKey;
             }
             $aNewTokenTableFields[$sKey] = $sValue['description'];
         }
         $aData['aTokenTableFields'] = $aNewTokenTableFields;
         $this->_renderWrappedTemplate('token', array('tokenbar', 'csvupload'), $aData);
     }
 }
Ejemplo n.º 5
0
                {
                    $aEmailAddresses=explode(';',$writearray['email']);
                    foreach ($aEmailAddresses as $sEmailaddress)
                    {
                        if (!validate_email($sEmailaddress))
                        {
                    $invalidemail=true;
                    $invalidemaillist[]=$line[0]." ".$line[1]." (".$line[2].")";
                }
                    }
                }

                if (!isset($writearray['token'])) {
                    $writearray['token'] = '';
                } else {
                    $writearray['token']=sanitize_token($writearray['token']);
                }

                if (!$dupfound && !$invalidemail)
                {
                    if (!isset($writearray['emailstatus']) || $writearray['emailstatus']=='') $writearray['emailstatus'] = "OK";
                    if (!isset($writearray['language']) || $writearray['language'] == "") $writearray['language'] = $baselanguage;
                    if (isset($writearray['validfrom']) && trim($writearray['validfrom']=='')){ unset($writearray['validfrom']);}
                    if (isset($writearray['validuntil']) && trim($writearray['validuntil']=='')){ unset($writearray['validuntil']);}

                    // sanitize it before writing into table
                    $sanitizedArray = array_map('db_quote',array_values($writearray));

                    $iq = "INSERT INTO ".db_table_name("tokens_$surveyid")." \n"
                    . "(".implode(',',array_keys($writearray)).") \n"
                    . "VALUES ('".implode("','",$sanitizedArray)."')";
Ejemplo n.º 6
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);
 }
Ejemplo n.º 7
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);
 }
Ejemplo n.º 8
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);
 }
Ejemplo n.º 9
0
function makelanguagechanger()
{
    global $relativeurl;
    if (!isset($surveyid)) {
        $surveyid = returnglobal('sid');
    }
    if (isset($surveyid)) {
        $slangs = GetAdditionalLanguagesFromSurveyID($surveyid);
        $sBaseLanguage = GetBaseLanguageFromSurveyID($surveyid);
    }
    $token = sanitize_token(returnglobal('token'));
    if ($token != '') {
        $tokenparam = "&token={$token}";
    } else {
        $tokenparam = "";
    }
    $previewgrp = false;
    if (isset($_REQUEST['action'])) {
        if ($_REQUEST['action'] == 'previewgroup') {
            $previewgrp = true;
        }
    }
    if (!empty($slangs)) {
        if (isset($_SESSION['s_lang']) && $_SESSION['s_lang'] != '') {
            $lang = sanitize_languagecode($_SESSION['s_lang']);
        } else {
            if (isset($_POST['lang']) && $_POST['lang'] != '') {
                $lang = sanitize_languagecode($_POST['lang']);
            } else {
                if (isset($_GET['lang']) && $_GET['lang'] != '') {
                    $lang = sanitize_languagecode($_GET['lang']);
                } else {
                    $lang = $sBaseLanguage;
                }
            }
        }
        $slangs[] = $sBaseLanguage;
        $aAllLanguages = getLanguageData();
        $slangs = array_keys(array_intersect_key($aAllLanguages, array_flip($slangs)));
        // Sort languages by their locale name
        $htmlcode = "<select name=\"select\" class='languagechanger' onchange=\"javascript:window.location=this.value\">\n";
        $sAddToURL = "";
        $sTargetURL = "{$relativeurl}/index.php";
        if ($previewgrp) {
            $sAddToURL = "&amp;action=previewgroup&amp;gid={$_REQUEST['gid']}";
            $sTargetURL = "";
        }
        foreach ($slangs as $otherlang) {
            $htmlcode .= "\t<option value=\"{$sTargetURL}?sid=" . $surveyid . "&amp;lang=" . $otherlang . "{$tokenparam}{$sAddToURL}\" ";
            if ($otherlang == $lang) {
                $htmlcode .= " selected=\"selected\" ";
            }
            $htmlcode .= ">" . getLanguageNameFromCode($otherlang, false) . "</option>\n";
        }
        $htmlcode .= "</select>\n";
        //    . "</form>";
        return $htmlcode;
    } elseif (!isset($surveyid)) {
        global $defaultlang, $baselang;
        $htmlcode = "<select name=\"select\" class='languagechanger' onchange=\"javascript:window.location=this.value\">\n";
        $htmlcode .= "<option value=\"{$relativeurl}/index.php?lang=" . $defaultlang . "{$tokenparam}\">" . getLanguageNameFromCode($defaultlang, false) . "</option>\n";
        foreach (getlanguagedata() as $key => $val) {
            $htmlcode .= "\t<option value=\"{$relativeurl}/index.php?lang=" . $key . "{$tokenparam}\" ";
            $htmlcode .= ">" . getLanguageNameFromCode($key, false) . "</option>\n";
        }
        $htmlcode .= "</select>\n";
        return $htmlcode;
    }
}
Ejemplo n.º 10
0
 /**
  * import from csv
  */
 function import($iSurveyId)
 {
     $iSurveyId = (int) $iSurveyId;
     if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'import')) {
         Yii::app()->session['flashmessage'] = gT("You do not have sufficient rights to access this page.");
         $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}"));
     }
     // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY
     $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}');
     if (!$bTokenExists) {
         self::_newtokentable($iSurveyId);
     }
     App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'tokensimport.js');
     $aEncodings = aEncodingsArray();
     if (Yii::app()->request->isPostRequest) {
         $sUploadCharset = Yii::app()->request->getPost('csvcharset');
         if (!array_key_exists($sUploadCharset, $aEncodings)) {
             $sUploadCharset = 'auto';
         }
         $bFilterDuplicateToken = Yii::app()->request->getPost('filterduplicatetoken');
         $bFilterBlankEmail = Yii::app()->request->getPost('filterblankemail');
         $bAllowInvalidEmail = Yii::app()->request->getPost('allowinvalidemail');
         $aAttrFieldNames = getAttributeFieldNames($iSurveyId);
         $aDuplicateList = array();
         $aInvalidEmailList = array();
         $aInvalidFormatList = array();
         $aModelErrorList = array();
         $aFirstLine = array();
         $oFile = CUploadedFile::getInstanceByName("the_file");
         $sPath = Yii::app()->getConfig('tempdir');
         $sFileName = $sPath . '/' . randomChars(20);
         //$sFileTmpName=$oFile->getTempName();
         /* More way to validate CSV ?
            $aCsvMimetypes = array(
                'text/csv',
                'text/plain',
                'application/csv',
                'text/comma-separated-values',
                'application/excel',
                'application/vnd.ms-excel',
                'application/vnd.msexcel',
                'text/anytext',
                'application/octet-stream',
                'application/txt',
            );
            */
         if (strtolower($oFile->getExtensionName()) != 'csv') {
             Yii::app()->setFlashMessage(gT("Only CSV files are allowed."), 'error');
         } elseif (!@$oFile->saveAs($sFileName)) {
             Yii::app()->setFlashMessage(sprintf(gT("Upload file not found. Check your permissions and path (%s) for the upload directory"), $sPath), 'error');
         } else {
             $iRecordImported = 0;
             $iRecordCount = 0;
             $iRecordOk = 0;
             $iInvalidEmailCount = 0;
             // Count invalid email imported
             // This allows to read file with MAC line endings too
             @ini_set('auto_detect_line_endings', true);
             // open it and trim the ednings
             $aTokenListArray = file($sFileName);
             $sBaseLanguage = Survey::model()->findByPk($iSurveyId)->language;
             if (!Yii::app()->request->getPost('filterduplicatefields') || Yii::app()->request->getPost('filterduplicatefields') && count(Yii::app()->request->getPost('filterduplicatefields')) == 0) {
                 $aFilterDuplicateFields = array('firstname', 'lastname', 'email');
             } else {
                 $aFilterDuplicateFields = Yii::app()->request->getPost('filterduplicatefields');
             }
             $sSeparator = Yii::app()->request->getPost('separator');
             foreach ($aTokenListArray as $buffer) {
                 $buffer = @mb_convert_encoding($buffer, "UTF-8", $sUploadCharset);
                 if ($iRecordCount == 0) {
                     // Parse first line (header) from CSV
                     $buffer = removeBOM($buffer);
                     // We alow all field except tid because this one is really not needed.
                     $aAllowedFieldNames = Token::model($iSurveyId)->tableSchema->getColumnNames();
                     if (($kTid = array_search('tid', $aAllowedFieldNames)) !== false) {
                         unset($aAllowedFieldNames[$kTid]);
                     }
                     // Some header don't have same column name
                     $aReplacedFields = array('invited' => 'sent', 'reminded' => 'remindersent');
                     switch ($sSeparator) {
                         case 'comma':
                             $sSeparator = ',';
                             break;
                         case 'semicolon':
                             $sSeparator = ';';
                             break;
                         default:
                             $comma = substr_count($buffer, ',');
                             $semicolon = substr_count($buffer, ';');
                             if ($semicolon > $comma) {
                                 $sSeparator = ';';
                             } else {
                                 $sSeparator = ',';
                             }
                     }
                     $aFirstLine = str_getcsv($buffer, $sSeparator, '"');
                     $aFirstLine = array_map('trim', $aFirstLine);
                     $aIgnoredColumns = array();
                     // Now check the first line for invalid fields
                     foreach ($aFirstLine as $index => $sFieldname) {
                         $aFirstLine[$index] = preg_replace("/(.*) <[^,]*>\$/", "\$1", $sFieldname);
                         $sFieldname = $aFirstLine[$index];
                         if (!in_array($sFieldname, $aAllowedFieldNames)) {
                             $aIgnoredColumns[] = $sFieldname;
                         }
                         if (array_key_exists($sFieldname, $aReplacedFields)) {
                             $aFirstLine[$index] = $aReplacedFields[$sFieldname];
                         }
                     }
                 } else {
                     $line = str_getcsv($buffer, $sSeparator, '"');
                     if (count($aFirstLine) != count($line)) {
                         $aInvalidFormatList[] = sprintf(gt("Line %s"), $iRecordCount);
                         $iRecordCount++;
                         continue;
                     }
                     $aWriteArray = array_combine($aFirstLine, $line);
                     //kick out ignored columns
                     foreach ($aIgnoredColumns as $column) {
                         unset($aWriteArray[$column]);
                     }
                     $bDuplicateFound = false;
                     $bInvalidEmail = false;
                     $aWriteArray['email'] = isset($aWriteArray['email']) ? trim($aWriteArray['email']) : "";
                     $aWriteArray['firstname'] = isset($aWriteArray['firstname']) ? $aWriteArray['firstname'] : "";
                     $aWriteArray['lastname'] = isset($aWriteArray['lastname']) ? $aWriteArray['lastname'] : "";
                     $aWriteArray['language'] = isset($aWriteArray['language']) ? $aWriteArray['language'] : $sBaseLanguage;
                     if ($bFilterDuplicateToken) {
                         $aParams = array();
                         $oCriteria = new CDbCriteria();
                         $oCriteria->condition = "";
                         foreach ($aFilterDuplicateFields as $field) {
                             if (isset($aWriteArray[$field])) {
                                 $oCriteria->addCondition("{$field} = :{$field}");
                                 $aParams[":{$field}"] = $aWriteArray[$field];
                             }
                         }
                         if (!empty($aParams)) {
                             $oCriteria->params = $aParams;
                         }
                         $dupresult = TokenDynamic::model($iSurveyId)->count($oCriteria);
                         if ($dupresult > 0) {
                             $bDuplicateFound = true;
                             $aDuplicateList[] = sprintf(gt("Line %s : %s %s (%s)"), $iRecordCount, $aWriteArray['firstname'], $aWriteArray['lastname'], $aWriteArray['email']);
                         }
                     }
                     //treat blank emails
                     if (!$bDuplicateFound && $bFilterBlankEmail && $aWriteArray['email'] == '') {
                         $bInvalidEmail = true;
                         $aInvalidEmailList[] = sprintf(gt("Line %s : %s %s"), $iRecordCount, CHtml::encode($aWriteArray['firstname']), CHtml::encode($aWriteArray['lastname']));
                     }
                     if (!$bDuplicateFound && $aWriteArray['email'] != '') {
                         $aEmailAddresses = explode(';', $aWriteArray['email']);
                         foreach ($aEmailAddresses as $sEmailaddress) {
                             if (!validateEmailAddress($sEmailaddress)) {
                                 if ($bAllowInvalidEmail) {
                                     $iInvalidEmailCount++;
                                     if (empty($aWriteArray['emailstatus']) || strtoupper($aWriteArray['emailstatus'] == "OK")) {
                                         $aWriteArray['emailstatus'] = "invalid";
                                     }
                                 } else {
                                     $bInvalidEmail = true;
                                     $aInvalidEmailList[] = sprintf(gt("Line %s : %s %s (%s)"), $iRecordCount, CHtml::encode($aWriteArray['firstname']), CHtml::encode($aWriteArray['lastname']), CHtml::encode($aWriteArray['email']));
                                 }
                             }
                         }
                     }
                     if (!$bDuplicateFound && !$bInvalidEmail && isset($aWriteArray['token'])) {
                         $aWriteArray['token'] = sanitize_token($aWriteArray['token']);
                         // We allways search for duplicate token (it's in model. Allow to reset or update token ?
                         if (Token::model($iSurveyId)->count("token=:token", array(":token" => $aWriteArray['token']))) {
                             $bDuplicateFound = true;
                             $aDuplicateList[] = sprintf(gt("Line %s : %s %s (%s) - token : %s"), $iRecordCount, CHtml::encode($aWriteArray['firstname']), CHtml::encode($aWriteArray['lastname']), CHtml::encode($aWriteArray['email']), CHtml::encode($aWriteArray['token']));
                         }
                     }
                     if (!$bDuplicateFound && !$bInvalidEmail) {
                         // unset all empty value
                         foreach ($aWriteArray as $key => $value) {
                             if ($aWriteArray[$key] == "") {
                                 unset($aWriteArray[$key]);
                             }
                             if (substr($value, 0, 1) == '"' && substr($value, -1) == '"') {
                                 // Fix CSV quote
                                 $value = substr($value, 1, -1);
                             }
                         }
                         // Some default value : to be moved to Token model rules in future release ?
                         // But think we have to accept invalid email etc ... then use specific scenario
                         $oToken = Token::create($iSurveyId);
                         if ($bAllowInvalidEmail) {
                             $oToken->scenario = 'allowinvalidemail';
                         }
                         foreach ($aWriteArray as $key => $value) {
                             $oToken->{$key} = $value;
                         }
                         if (!$oToken->save()) {
                             tracevar($oToken->getErrors());
                             $aModelErrorList[] = sprintf(gt("Line %s : %s"), $iRecordCount, Chtml::errorSummary($oToken));
                         } else {
                             $iRecordImported++;
                         }
                     }
                     $iRecordOk++;
                 }
                 $iRecordCount++;
             }
             $iRecordCount = $iRecordCount - 1;
             unlink($sFileName);
             $aData['aTokenListArray'] = $aTokenListArray;
             // Big array in memory, just for success ?
             $aData['iRecordImported'] = $iRecordImported;
             $aData['iRecordOk'] = $iRecordOk;
             $aData['iRecordCount'] = $iRecordCount;
             $aData['aFirstLine'] = $aFirstLine;
             // Seem not needed
             $aData['aDuplicateList'] = $aDuplicateList;
             $aData['aInvalidFormatList'] = $aInvalidFormatList;
             $aData['aInvalidEmailList'] = $aInvalidEmailList;
             $aData['aModelErrorList'] = $aModelErrorList;
             $aData['iInvalidEmailCount'] = $iInvalidEmailCount;
             $aData['thissurvey'] = getSurveyInfo($iSurveyId);
             $aData['iSurveyId'] = $aData['surveyid'] = $iSurveyId;
             $this->_renderWrappedTemplate('token', array('tokenbar', 'csvpost'), $aData);
             Yii::app()->end();
         }
     }
     // If there are error with file : show the form
     $aData['aEncodings'] = $aEncodings;
     $aData['iSurveyId'] = $iSurveyId;
     $aData['thissurvey'] = getSurveyInfo($iSurveyId);
     $aData['surveyid'] = $iSurveyId;
     $aTokenTableFields = getTokenFieldsAndNames($iSurveyId);
     unset($aTokenTableFields['sent']);
     unset($aTokenTableFields['remindersent']);
     unset($aTokenTableFields['remindercount']);
     unset($aTokenTableFields['usesleft']);
     foreach ($aTokenTableFields as $sKey => $sValue) {
         if ($sValue['description'] != $sKey) {
             $sValue['description'] .= ' - ' . $sKey;
         }
         $aNewTokenTableFields[$sKey] = $sValue['description'];
     }
     $aData['aTokenTableFields'] = $aNewTokenTableFields;
     $this->_renderWrappedTemplate('token', array('tokenbar', 'csvupload'), $aData);
 }
Ejemplo n.º 11
0
function makelanguagechanger()
{
    global $relativeurl;
    if (!isset($surveyid)) {
        $surveyid = returnglobal('sid');
    }
    if (isset($surveyid)) {
        $slangs = GetAdditionalLanguagesFromSurveyID($surveyid);
    }
    $token = sanitize_token(returnglobal('token'));
    if ($token != '') {
        $tokenparam = "&token={$token}";
    } else {
        $tokenparam = "";
    }
    if (!empty($slangs)) {
        if (isset($_SESSION['s_lang']) && $_SESSION['s_lang'] != '') {
            $lang = sanitize_languagecode($_SESSION['s_lang']);
        } else {
            if (isset($_POST['lang']) && $_POST['lang'] != '') {
                $lang = sanitize_languagecode($_POST['lang']);
            } else {
                if (isset($_GET['lang']) && $_GET['lang'] != '') {
                    $lang = sanitize_languagecode($_GET['lang']);
                } else {
                    $lang = GetBaseLanguageFromSurveyID($surveyid);
                }
            }
        }
        $htmlcode = "<select name=\"select\" class='languagechanger' onchange=\"javascript:window.location=this.value\">\n";
        $htmlcode .= "<option value=\"{$relativeurl}/index.php?sid=" . $surveyid . "&amp;lang=" . $lang . "{$tokenparam}\">" . getLanguageNameFromCode($lang, false) . "</option>\n";
        foreach ($slangs as $otherlang) {
            if ($otherlang != $lang) {
                $htmlcode .= "\t<option value=\"{$relativeurl}/index.php?sid=" . $surveyid . "&amp;lang=" . $otherlang . "{$tokenparam}\" >" . getLanguageNameFromCode($otherlang, false) . "</option>\n";
            }
        }
        if ($lang != GetBaseLanguageFromSurveyID($surveyid)) {
            $htmlcode .= "<option value=\"{$relativeurl}/index.php?sid=" . $surveyid . "&amp;lang=" . GetBaseLanguageFromSurveyID($surveyid) . "{$tokenparam}\">" . getLanguageNameFromCode(GetBaseLanguageFromSurveyID($surveyid), false) . "</option>\n";
        }
        $htmlcode .= "</select>\n";
        //    . "</form>";
        return $htmlcode;
    } elseif (!isset($surveyid)) {
        global $defaultlang, $baselang;
        $htmlcode = "<select name=\"select\" class='languagechanger' onchange=\"javascript:window.location=this.value\">\n";
        $htmlcode .= "<option value=\"{$relativeurl}/index.php?lang=" . $defaultlang . "{$tokenparam}\">" . getLanguageNameFromCode($defaultlang, false) . "</option>\n";
        foreach (getlanguagedata() as $key => $val) {
            $htmlcode .= "\t<option value=\"{$relativeurl}/index.php?lang=" . $key . "{$tokenparam}\" ";
            if ($key == $baselang) {
                $htmlcode .= " selected=\"selected\" ";
            }
            $htmlcode .= ">" . getLanguageNameFromCode($key, false) . "</option>\n";
        }
        $htmlcode .= "</select>\n";
        return $htmlcode;
    }
}
Ejemplo n.º 12
0
 /**
  * import from csv
  */
 function import($iSurveyId)
 {
     // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY
     $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}');
     if (!$bTokenExists) {
         self::_newtokentable($iSurveyId);
     }
     $clang = $this->getController()->lang;
     $iSurveyId = (int) $iSurveyId;
     if (!hasSurveyPermission($iSurveyId, 'tokens', 'create')) {
         die('access denied');
     }
     $this->getController()->_js_admin_includes(Yii::app()->getConfig('adminscripts') . 'tokens.js');
     $aEncodings = array("armscii8" => $clang->gT("ARMSCII-8 Armenian"), "ascii" => $clang->gT("US ASCII"), "auto" => $clang->gT("Automatic"), "big5" => $clang->gT("Big5 Traditional Chinese"), "binary" => $clang->gT("Binary pseudo charset"), "cp1250" => $clang->gT("Windows Central European"), "cp1251" => $clang->gT("Windows Cyrillic"), "cp1256" => $clang->gT("Windows Arabic"), "cp1257" => $clang->gT("Windows Baltic"), "cp850" => $clang->gT("DOS West European"), "cp852" => $clang->gT("DOS Central European"), "cp866" => $clang->gT("DOS Russian"), "cp932" => $clang->gT("SJIS for Windows Japanese"), "dec8" => $clang->gT("DEC West European"), "eucjpms" => $clang->gT("UJIS for Windows Japanese"), "euckr" => $clang->gT("EUC-KR Korean"), "gb2312" => $clang->gT("GB2312 Simplified Chinese"), "gbk" => $clang->gT("GBK Simplified Chinese"), "geostd8" => $clang->gT("GEOSTD8 Georgian"), "greek" => $clang->gT("ISO 8859-7 Greek"), "hebrew" => $clang->gT("ISO 8859-8 Hebrew"), "hp8" => $clang->gT("HP West European"), "keybcs2" => $clang->gT("DOS Kamenicky Czech-Slovak"), "koi8r" => $clang->gT("KOI8-R Relcom Russian"), "koi8u" => $clang->gT("KOI8-U Ukrainian"), "latin1" => $clang->gT("cp1252 West European"), "latin2" => $clang->gT("ISO 8859-2 Central European"), "latin5" => $clang->gT("ISO 8859-9 Turkish"), "latin7" => $clang->gT("ISO 8859-13 Baltic"), "macce" => $clang->gT("Mac Central European"), "macroman" => $clang->gT("Mac West European"), "sjis" => $clang->gT("Shift-JIS Japanese"), "swe7" => $clang->gT("7bit Swedish"), "tis620" => $clang->gT("TIS620 Thai"), "ucs2" => $clang->gT("UCS-2 Unicode"), "ujis" => $clang->gT("EUC-JP Japanese"), "utf8" => $clang->gT("UTF-8 Unicode"));
     if (Yii::app()->request->getPost('submit')) {
         if (Yii::app()->request->getPost('csvcharset') && Yii::app()->request->getPost('csvcharset')) {
             $uploadcharset = Yii::app()->request->getPost('csvcharset');
             if (!array_key_exists($uploadcharset, $aEncodings)) {
                 $uploadcharset = 'auto';
             }
             $filterduplicatetoken = Yii::app()->request->getPost('filterduplicatetoken') && Yii::app()->request->getPost('filterduplicatetoken') == 'on';
             $filterblankemail = Yii::app()->request->getPost('filterblankemail') && Yii::app()->request->getPost('filterblankemail') == 'on';
         }
         $attrfieldnames = getAttributeFieldNames($iSurveyId);
         $duplicatelist = array();
         $invalidemaillist = array();
         $invalidformatlist = array();
         $firstline = array();
         $sPath = Yii::app()->getConfig('tempdir');
         $sFileName = $_FILES['the_file']['name'];
         $sFileTmpName = $_FILES['the_file']['tmp_name'];
         $sFilePath = $sPath . '/' . $sFileName;
         if (!@move_uploaded_file($sFileTmpName, $sFilePath)) {
             $aData['sError'] = $clang->gT("Upload file not found. Check your permissions and path ({$sFilePath}) for the upload directory");
             $aData['aEncodings'] = $aEncodings;
             $aData['iSurveyId'] = $aData['surveyid'] = $iSurveyId;
             $aData['thissurvey'] = getSurveyInfo($iSurveyId);
             $this->_renderWrappedTemplate('token', array('tokenbar', 'csvupload'), $aData);
         } else {
             $xz = 0;
             $recordcount = 0;
             $xv = 0;
             // This allows to read file with MAC line endings too
             @ini_set('auto_detect_line_endings', true);
             // open it and trim the ednings
             $tokenlistarray = file($sFilePath);
             $sBaseLanguage = Survey::model()->findByPk($iSurveyId)->language;
             if (!Yii::app()->request->getPost('filterduplicatefields') || Yii::app()->request->getPost('filterduplicatefields') && count(Yii::app()->request->getPost('filterduplicatefields')) == 0) {
                 $filterduplicatefields = array('firstname', 'lastname', 'email');
             } else {
                 $filterduplicatefields = Yii::app()->request->getPost('filterduplicatefields');
             }
             $separator = returnGlobal('separator');
             foreach ($tokenlistarray as $buffer) {
                 $buffer = @mb_convert_encoding($buffer, "UTF-8", $uploadcharset);
                 $firstname = "";
                 $lastname = "";
                 $email = "";
                 $emailstatus = "OK";
                 $token = "";
                 $language = "";
                 $attribute1 = "";
                 $attribute2 = "";
                 //Clear out values from the last path, in case the next line is missing a value
                 if ($recordcount == 0) {
                     // Pick apart the first line
                     $buffer = removeBOM($buffer);
                     $allowedfieldnames = array('firstname', 'lastname', 'email', 'emailstatus', 'token', 'language', 'validfrom', 'validuntil', 'usesleft');
                     $allowedfieldnames = array_merge($attrfieldnames, $allowedfieldnames);
                     switch ($separator) {
                         case 'comma':
                             $separator = ',';
                             break;
                         case 'semicolon':
                             $separator = ';';
                             break;
                         default:
                             $comma = substr_count($buffer, ',');
                             $semicolon = substr_count($buffer, ';');
                             if ($semicolon > $comma) {
                                 $separator = ';';
                             } else {
                                 $separator = ',';
                             }
                     }
                     $firstline = convertCSVRowToArray($buffer, $separator, '"');
                     $firstline = array_map('trim', $firstline);
                     $ignoredcolumns = array();
                     //now check the first line for invalid fields
                     foreach ($firstline as $index => $fieldname) {
                         $firstline[$index] = preg_replace("/(.*) <[^,]*>\$/", "\$1", $fieldname);
                         $fieldname = $firstline[$index];
                         if (!in_array($fieldname, $allowedfieldnames)) {
                             $ignoredcolumns[] = $fieldname;
                         }
                     }
                     if (!in_array('firstname', $firstline) || !in_array('lastname', $firstline) || !in_array('email', $firstline)) {
                         $recordcount = count($tokenlistarray);
                         break;
                     }
                 } else {
                     $line = convertCSVRowToArray($buffer, $separator, '"');
                     if (count($firstline) != count($line)) {
                         $invalidformatlist[] = $recordcount;
                         $recordcount++;
                         continue;
                     }
                     $writearray = array_combine($firstline, $line);
                     //kick out ignored columns
                     foreach ($ignoredcolumns as $column) {
                         unset($writearray[$column]);
                     }
                     $dupfound = false;
                     $invalidemail = false;
                     if ($filterduplicatetoken != false) {
                         $dupquery = "SELECT count(tid) from {{tokens_" . intval($iSurveyId) . "}} where 1=1";
                         foreach ($filterduplicatefields as $field) {
                             if (isset($writearray[$field])) {
                                 $dupquery .= " and " . Yii::app()->db->quoteColumnName($field) . " = " . Yii::app()->db->quoteValue($writearray[$field]);
                             }
                         }
                         $dupresult = Yii::app()->db->createCommand($dupquery)->queryScalar();
                         if ($dupresult > 0) {
                             $dupfound = true;
                             $duplicatelist[] = Yii::app()->db->quoteValue($writearray['firstname']) . " " . Yii::app()->db->quoteValue($writearray['lastname']) . " (" . Yii::app()->db->quoteValue($writearray['email']) . ")";
                         }
                     }
                     $writearray['email'] = trim($writearray['email']);
                     //treat blank emails
                     if ($filterblankemail && $writearray['email'] == '') {
                         $invalidemail = true;
                         $invalidemaillist[] = $line[0] . " " . $line[1] . " ( )";
                     }
                     if ($writearray['email'] != '') {
                         $aEmailAddresses = explode(';', $writearray['email']);
                         foreach ($aEmailAddresses as $sEmailaddress) {
                             if (!validateEmailAddress($sEmailaddress)) {
                                 $invalidemail = true;
                                 $invalidemaillist[] = $line[0] . " " . $line[1] . " (" . $line[2] . ")";
                             }
                         }
                     }
                     if (!isset($writearray['token'])) {
                         $writearray['token'] = '';
                     } else {
                         $writearray['token'] = sanitize_token($writearray['token']);
                     }
                     if (!$dupfound && !$invalidemail) {
                         if (!isset($writearray['emailstatus']) || $writearray['emailstatus'] == '') {
                             $writearray['emailstatus'] = "OK";
                         }
                         if (!isset($writearray['usesleft']) || $writearray['usesleft'] == '') {
                             $writearray['usesleft'] = 1;
                         }
                         if (!isset($writearray['language']) || $writearray['language'] == "") {
                             $writearray['language'] = $sBaseLanguage;
                         }
                         if (isset($writearray['validfrom']) && trim($writearray['validfrom'] == '')) {
                             unset($writearray['validfrom']);
                         }
                         if (isset($writearray['validuntil']) && trim($writearray['validuntil'] == '')) {
                             unset($writearray['validuntil']);
                         }
                         // sanitize it before writing into table
                         foreach ($writearray as $key => $value) {
                             if (substr($value, 0, 1) == '"' && substr($value, -1) == '"') {
                                 $value = substr($value, 1, -1);
                             }
                             $sanitizedArray[Yii::app()->db->quoteColumnName($key)] = Yii::app()->db->quoteValue($value);
                         }
                         $iq = "INSERT INTO {{tokens_{$iSurveyId}}} \n" . "(" . implode(',', array_keys($writearray)) . ") \n" . "VALUES (" . implode(",", $sanitizedArray) . ")";
                         $ir = Yii::app()->db->createCommand($iq)->execute();
                         if (!$ir) {
                             $duplicatelist[] = $writearray['firstname'] . " " . $writearray['lastname'] . " (" . $writearray['email'] . ")";
                         } else {
                             $xz++;
                         }
                     }
                     $xv++;
                 }
                 $recordcount++;
             }
             $recordcount = $recordcount - 1;
             unlink($sFilePath);
             $aData['tokenlistarray'] = $tokenlistarray;
             $aData['xz'] = $xz;
             $aData['xv'] = $xv;
             $aData['recordcount'] = $recordcount;
             $aData['firstline'] = $firstline;
             $aData['duplicatelist'] = $duplicatelist;
             $aData['invalidformatlist'] = $invalidformatlist;
             $aData['invalidemaillist'] = $invalidemaillist;
             $aData['thissurvey'] = getSurveyInfo($iSurveyId);
             $aData['iSurveyId'] = $aData['surveyid'] = $iSurveyId;
             $this->_renderWrappedTemplate('token', array('tokenbar', 'csvpost'), $aData);
         }
     } else {
         $aData['aEncodings'] = $aEncodings;
         $aData['iSurveyId'] = $iSurveyId;
         $aData['thissurvey'] = getSurveyInfo($iSurveyId);
         $aData['surveyid'] = $iSurveyId;
         $this->_renderWrappedTemplate('token', array('tokenbar', 'csvupload'), $aData);
     }
 }
Ejemplo n.º 13
0
/**
 * This function replaces keywords in a text and is mainly intended for templates
 * If you use this functions put your replacement strings into the $replacements variable
 * instead of using global variables
 * NOTE - Don't do any embedded replacements in this function.  Create the array of replacement values and
 * they will be done in batch at the end
 *
 * @param string $line Text to search in
 * @param array $replacements Array of replacements:  Array( <stringtosearch>=><stringtoreplacewith>, where <stringtosearch> is NOT surrounded with curly braces
 * @param boolean $anonymized Determines if token data is being used or just replaced with blanks
 * @return string  Text with replaced strings
 */
function templatereplace($line, $replacements = array(), $anonymized = false, $questionNum = NULL)
{
    global $surveylist, $sitename, $clienttoken, $rooturl;
    global $thissurvey, $imageurl, $defaulttemplate;
    global $percentcomplete, $move;
    global $groupname, $groupdescription;
    global $question;
    global $showxquestions, $showgroupinfo, $showqnumcode;
    global $answer, $navigator;
    global $help, $surveyformat;
    global $completed, $register_errormsg;
    global $privacy, $surveyid;
    global $publicurl, $templatedir, $token;
    global $assessments, $s_lang;
    global $errormsg, $clang;
    global $saved_id;
    global $totalBoilerplatequestions, $relativeurl;
    global $languagechanger;
    global $captchapath, $loadname;
    // lets sanitize the survey template
    if (isset($thissurvey['templatedir'])) {
        $_templatename = $thissurvey['templatedir'];
    } else {
        $_templatename = $defaulttemplate;
    }
    $_templatename = validate_templatedir($_templatename);
    // create absolute template URL and template dir vars
    $_templateurl = sGetTemplateURL($_templatename) . '/';
    $templatedir = sgetTemplatePath($_templatename);
    if (stripos($line, "</head>")) {
        $line = str_ireplace("</head>", "<script type=\"text/javascript\" src=\"{$rooturl}/scripts/survey_runtime.js\"></script>\n" . use_firebug() . "\t</head>", $line);
    }
    // Get some vars : move elsewhere ?
    // surveyformat
    if (isset($thissurvey['format'])) {
        $surveyformat = str_replace(array("A", "S", "G"), array("allinone", "questionbyquestion", "groupbygroup"), $thissurvey['format']);
    } else {
        $surveyformat = "";
    }
    /*if (isset($thissurvey['allowjumps']) && $thissurvey['allowjumps']=="Y" && $surveyformat!="allinone" && (isset($_SESSION['step']) && $_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['contact'])) {
        $_surveycontact = $surveylist['contact'];
    } elseif (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) {
        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 = $groupname;
    } else {
        $_groupname = '';
    }
    if ($showgroupinfo == 'both' || $showgroupinfo == 'description' || $showgroupinfo == 'choose' && !isset($thissurvey['showgroupinfo']) || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'B' || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'D') {
        $_groupdescription = $groupdescription;
    } else {
        $_groupdescription = '';
    }
    if (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'];
        if (isset($question['sgq'])) {
            $_question_sgq = $question['sgq'];
            $_parts = explode('X', $_question_sgq);
            $_question_gid = $_parts[1];
        } else {
            $_question_sgq = '';
            $_question_gid = '';
        }
        $_question_essentials = $question['essentials'];
        $_question_class = $question['class'];
        $_question_man_class = $question['man_class'];
        $_question_input_error_class = $question['input_error_class'];
        $_aid = isset($question['aid']) ? $question['aid'] : '';
        $_sqid = isset($question['sqid']) ? $question['sqid'] : '';
        $_question_type = isset($question['type']) ? $question['type'] : '';
    } else {
        $_question = $question;
        $_question_text = '';
        $_question_help = '';
        $_question_mandatory = '';
        $_question_man_message = '';
        $_question_valid_message = '';
        $_question_file_valid_message = '';
        $_question_gid = '';
        $_question_sgq = '';
        $_question_essentials = '';
        $_question_class = '';
        $_question_man_class = '';
        $_question_input_error_class = '';
        $_aid = '';
        $_sqid = '';
        $_question_type = '';
    }
    global $answer_id;
    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 = $question['number'];
    } else {
        $_question_number = '';
    }
    if ($showqnumcode == 'both' || $showqnumcode == 'code' || $showqnumcode == 'choose' && !isset($thissurvey['showqnumcode']) || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'B' || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'C') {
        $_question_code = $question['code'];
    } else {
        $_question_code = '';
    }
    if (isset($_SESSION['therearexquestions'])) {
        $_totalquestionsAsked = $_SESSION['therearexquestions'] - $totalBoilerplatequestions;
    } else {
        $_totalquestionsAsked = 0;
    }
    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');
    } else {
        $_token = '';
    }
    if (isset($thissurvey['surveyls_dateformat'])) {
        $dateformatdetails = getDateFormatData($thissurvey['surveyls_dateformat']);
    } else {
        $dateformatdetails = getDateFormatData();
    }
    if (isset($thissurvey['expiry'])) {
        $_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($clienttoken)) {
        $token = $clienttoken;
    } else {
        $token = '';
    }
    if (!isset($_SESSION['s_lang'])) {
        $_s_lang = 'en';
    } else {
        $_s_lang = $_SESSION['s_lang'];
    }
    $_clearall = "<input type='button' name='clearallbtn' value='" . $clang->gT("Exit and Clear Survey") . "' class='clearall' " . "onclick=\"if (confirm('" . $clang->gT("Are you sure you want to clear all your responses?", 'js') . "')) {\nwindow.open('{$publicurl}/index.php?sid={$surveyid}&amp;move=clearall&amp;lang=" . $_s_lang;
    if (returnglobal('token')) {
        $_clearall .= "&amp;token=" . urlencode(trim(sanitize_token(strip_tags(returnglobal('token')))));
    }
    $_clearall .= "', '_self')}\" />";
    if (isset($_SESSION['datestamp'])) {
        $_datestamp = $_SESSION['datestamp'];
    } else {
        $_datestamp = '-';
    }
    //Set up save/load feature
    if (isset($thissurvey['allowsave']) and $thissurvey['allowsave'] == "Y") {
        // Find out if the user has any saved data
        if ($thissurvey['format'] == 'A') {
            if ($thissurvey['tokenanswerspersistence'] != 'Y') {
                $_saveall = "\t\t\t<input type='submit' name='loadall' value='" . $clang->gT("Load Unfinished Survey") . "' class='saveall' " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>" . "\n\t\t\t<input type='button' name='saveallbtn' value='" . $clang->gT("Resume Later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
                // Show Save So Far button
            } else {
                $_saveall = "\t\t\t<input type='button' name='saveallbtn' value='" . $clang->gT("Resume Later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
                // Show Save So Far button
            }
        } elseif (!isset($_SESSION['step']) || !$_SESSION['step']) {
            //First page, show LOAD
            if ($thissurvey['tokenanswerspersistence'] != 'Y') {
                $_saveall = "\t\t\t<input type='submit' name='loadall' value='" . $clang->gT("Load Unfinished Survey") . "' class='saveall' " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
            } else {
                $_saveall = '';
            }
        } elseif (isset($_SESSION['scid']) && (isset($move) && $move == "movelast")) {
            //Already saved and on Submit Page, dont show Save So Far button
            $_saveall = '';
        } else {
            $_saveall = "<input type='button' name='saveallbtn' value='" . $clang->gT("Resume Later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
            // Show Save So Far button
        }
    } else {
        $_saveall = "";
    }
    $_templatecss = "<link rel='stylesheet' type='text/css' href='{$_templateurl}template.css' />\n";
    if (getLanguageRTL($clang->langcode)) {
        $_templatecss .= "<link rel='stylesheet' type='text/css' href='{$_templateurl}template-rtl.css' />\n";
    }
    if (FlattenText($help, 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 = $imageurl . "/help.gif";
            }
        }
        $_questionhelp = "<img src='{$helpicon}' alt='Help' align='left' />" . $help;
    } else {
        $_questionhelp = $help;
    }
    if (isset($thissurvey['allowprev']) && $thissurvey['allowprev'] == "N") {
        $_strreview = "";
    } else {
        $_strreview = $clang->gT("If you want to check any of the answers you have made, and/or change them, you can do that now by clicking on the [<< prev] button and browsing through your responses.");
    }
    if (isset($thissurvey['active']) and $thissurvey['active'] == "N") {
        $_restart = "<a href='{$publicurl}/index.php?sid={$surveyid}&amp;newtest=Y";
        if (isset($s_lang) && $s_lang != '') {
            $_restart .= "&amp;lang=" . $s_lang;
        }
        $_restart .= "'>" . $clang->gT("Restart this Survey") . "</a>";
    } else {
        $restart_extra = "";
        $restart_token = returnglobal('token');
        if (!empty($restart_token)) {
            $restart_extra .= "&amp;token=" . urlencode($restart_token);
        } else {
            $restart_extra = "&amp;newtest=Y";
        }
        if (!empty($_GET['lang'])) {
            $restart_extra .= "&amp;lang=" . returnglobal('lang');
        }
        $_restart = "<a href='{$publicurl}/index.php?sid={$surveyid}" . $restart_extra . "'>" . $clang->gT("Restart this Survey") . "</a>";
    }
    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 = "";
    }
    $_return_to_survey = "<a href='{$relativeurl}/index.php?sid={$surveyid}";
    if (returnglobal('token')) {
        $_return_to_survey .= "&amp;token=" . urlencode(trim(sanitize_xss_string(strip_tags(returnglobal('token')))));
    }
    $_return_to_survey .= "'>" . $clang->gT("Return To Survey") . "</a>";
    $_saveform = "<table><tr><td align='right'>" . $clang->gT("Name") . ":</td><td><input type='text' name='savename' value='";
    if (isset($_POST['savename'])) {
        $_saveform .= html_escape(auto_unescape($_POST['savename']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Password") . ":</td><td><input type='password' name='savepass' value='";
    if (isset($_POST['savepass'])) {
        $_saveform .= html_escape(auto_unescape($_POST['savepass']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Repeat Password") . ":</td><td><input type='password' name='savepass2' value='";
    if (isset($_POST['savepass2'])) {
        $_saveform .= html_escape(auto_unescape($_POST['savepass2']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Your Email") . ":</td><td><input type='text' name='saveemail' value='";
    if (isset($_POST['saveemail'])) {
        $_saveform .= html_escape(auto_unescape($_POST['saveemail']));
    }
    $_saveform .= "' /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && captcha_enabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
        $_saveform .= "<tr><td align='right'>" . $clang->gT("Security Question") . ":</td><td><table><tr><td valign='middle'><img src='{$captchapath}verification.php?sid={$surveyid}' alt='' /></td><td valign='middle' style='text-align:left'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table></td></tr>\n";
    }
    $_saveform .= "<tr><td align='right'></td><td></td></tr>\n" . "<tr><td></td><td><input type='submit'  id='savebutton' name='savesubmit' value='" . $clang->gT("Save Now") . "' /></td></tr>\n" . "</table>";
    $_loadform = "<table><tr><td align='right'>" . $clang->gT("Saved name") . ":</td><td><input type='text' name='loadname' value='";
    if ($loadname) {
        $_loadform .= html_escape(auto_unescape($loadname));
    }
    $_loadform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Password") . ":</td><td><input type='password' name='loadpass' value='";
    if (isset($loadpass)) {
        $_loadform .= html_escape(auto_unescape($loadpass));
    }
    $_loadform .= "' /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && captcha_enabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
        $_loadform .= "<tr><td align='right'>" . $clang->gT("Security Question") . ":</td><td><table><tr><td valign='middle'><img src='{$captchapath}verification.php?sid={$surveyid}' alt='' /></td><td valign='middle'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' alt=''/></td></tr></table></td></tr>\n";
    }
    $_loadform .= "<tr><td align='right'></td><td></td></tr>\n" . "<tr><td></td><td><input type='submit' id='loadbutton' value='" . $clang->gT("Load Now") . "' /></td></tr></table>\n";
    $_registerform = "<form method='post' action='{$publicurl}/register.php'>\n";
    if (!isset($_REQUEST['lang'])) {
        $_reglang = GetBaseLanguageFromSurveyID($surveyid);
    } else {
        $_reglang = returnglobal('lang');
    }
    $_registerform .= "<input type='hidden' name='lang' value='" . $_reglang . "' />\n";
    $_registerform .= "<input type='hidden' name='sid' value='{$surveyid}' id='sid' />\n";
    $_registerform .= "<table class='register' summary='Registrationform'>\n" . "<tr><td align='right'>" . $clang->gT("First name") . ":</td>" . "<td align='left'><input class='text' type='text' name='register_firstname'";
    if (isset($_POST['register_firstname'])) {
        $_registerform .= " value='" . htmlentities(returnglobal('register_firstname'), ENT_QUOTES, 'UTF-8') . "'";
    }
    $_registerform .= " /></td></tr>" . "<tr><td align='right'>" . $clang->gT("Last name") . ":</td>\n" . "<td align='left'><input class='text' type='text' name='register_lastname'";
    if (isset($_POST['register_lastname'])) {
        $_registerform .= " value='" . htmlentities(returnglobal('register_lastname'), ENT_QUOTES, 'UTF-8') . "'";
    }
    $_registerform .= " /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Email address") . ":</td>\n" . "<td align='left'><input class='text' type='text' name='register_email'";
    if (isset($_POST['register_email'])) {
        $_registerform .= " value='" . htmlentities(returnglobal('register_email'), ENT_QUOTES, 'UTF-8') . "'";
    }
    $_registerform .= " /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && captcha_enabled('registrationscreen', $thissurvey['usecaptcha'])) {
        $_registerform .= "<tr><td align='right'>" . $clang->gT("Security Question") . ":</td><td><table><tr><td valign='middle'><img src='{$captchapath}verification.php?sid={$surveyid}' alt='' /></td><td valign='middle'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table></td></tr>\n";
    }
    /*      if(isset($thissurvey['attribute1']) && $thissurvey['attribute1'])
             {
             $_registerform .= "<tr><td align='right'>".$thissurvey['attribute1'].":</td>\n"
             ."<td align='left'><input class='text' type='text' name='register_attribute1'";
             if (isset($_POST['register_attribute1']))
             {
             $_registerform .= " value='".htmlentities(returnglobal('register_attribute1'),ENT_QUOTES,'UTF-8')."'";
             }
             $_registerform .= " /></td></tr>\n";
             }
             if(isset($thissurvey['attribute2']) && $thissurvey['attribute2'])
             {
             $_registerform .= "<tr><td align='right'>".$thissurvey['attribute2'].":</td>\n"
             ."<td align='left'><input class='text' type='text' name='register_attribute2'";
             if (isset($_POST['register_attribute2']))
             {
             $_registerform .= " value='".htmlentities(returnglobal('register_attribute2'),ENT_QUOTES,'UTF-8')."'";
             }
             $_registerform .= " /></td></tr>\n";
          } */
    $_registerform .= "<tr><td></td><td><input id='registercontinue' class='submit' type='submit' value='" . $clang->gT("Continue") . "' />" . "</td></tr>\n" . "</table>\n" . "</form>\n";
    if (!is_null($surveyid) && function_exists('doAssessment')) {
        $assessmentdata = doAssessment($surveyid, true);
        $_assessment_current_total = $assessmentdata['total'];
    } 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 gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try{
var pageTracker = _gat._getTracker("{$_googleAnalyticsAPIKey}");
pageTracker._trackPageview();
} catch(err) { }
</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 gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try{
var pageTracker = _gat._getTracker("{$_googleAnalyticsAPIKey}");
pageTracker._trackPageview("{$_trackURL}");
} catch(err) { }
</script>
EOD;
                break;
        }
    }
    // Set the array of replacement variables here - don't include curly braces
    // Please put any conditional logic above this section.  Here below should just be an alphabetical list of replacement values with no embedded logic.
    $coreReplacements = array();
    $coreReplacements['AID'] = $_aid;
    // global
    $coreReplacements['ANSWER'] = $answer;
    // global
    $coreReplacements['ANSWERSCLEARED'] = $clang->gT("Answers Cleared");
    $coreReplacements['ASSESSMENTS'] = $assessments;
    // global
    $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'] = $completed;
    // global
    $coreReplacements['DATESTAMP'] = $_datestamp;
    $coreReplacements['EXPIRY'] = $_dateoutput;
    $coreReplacements['GID'] = $_question_gid;
    $coreReplacements['GOOGLE_ANALYTICS_API_KEY'] = $_googleAnalyticsAPIKey;
    $coreReplacements['GOOGLE_ANALYTICS_JAVASCRIPT'] = $_googleAnalyticsJavaScript;
    $coreReplacements['GROUPDESCRIPTION'] = $_groupdescription;
    $coreReplacements['GROUPNAME'] = $_groupname;
    $coreReplacements['LANG'] = $clang->getlangcode();
    $coreReplacements['LANGUAGECHANGER'] = $languagechanger;
    // global
    $coreReplacements['LOADERROR'] = $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'] = $navigator;
    // global
    $coreReplacements['NOSURVEYID'] = $surveylist['nosid'];
    // global
    $coreReplacements['NUMBEROFQUESTIONS'] = $_totalquestionsAsked;
    $coreReplacements['PERCENTCOMPLETE'] = $percentcomplete;
    // global
    $coreReplacements['PRIVACY'] = $privacy;
    // global
    $coreReplacements['PRIVACYMESSAGE'] = "<span style='font-weight:bold; font-style: italic;'>" . $clang->gT("A Note On Privacy") . "</span><br />" . $clang->gT("This survey is anonymous.") . "<br />" . $clang->gT("The record kept of your survey responses does not contain any identifying information about you unless a specific question in the survey has asked for this. If you have responded to a survey that used an identifying token to allow you to access the survey, you can rest assured that the identifying token is not kept with your responses. It is managed in a separate database, and will only be updated to indicate that you have (or haven't) completed this survey. There is no way of matching identification tokens with survey responses in this survey.");
    $coreReplacements['QID'] = isset($questionNum) ? $questionNum : '';
    $coreReplacements['QUESTION'] = $_question;
    $coreReplacements['QUESTIONHELP'] = $_questionhelp;
    $coreReplacements['QUESTIONHELPPLAINTEXT'] = strip_tags(addslashes($help));
    // global
    $coreReplacements['QUESTION_CLASS'] = $_question_class;
    $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'] = $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'] = $saved_id;
    // global
    $coreReplacements['SAVEERROR'] = $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'] = $surveyid;
    // global
    $coreReplacements['SITENAME'] = $sitename;
    // global
    $coreReplacements['SQID'] = $_sqid;
    // 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'] = $surveyformat;
    // global
    $coreReplacements['SURVEYLANGAGE'] = $clang->langcode;
    // this misspelling is kept for legacy reasons
    $coreReplacements['SURVEYLANGUAGE'] = $clang->langcode;
    $coreReplacements['SURVEYLIST'] = $surveylist['list'];
    // global
    $coreReplacements['SURVEYLISTHEADING'] = $surveylist['listheading'];
    // global
    $coreReplacements['SURVEYNAME'] = $thissurvey['name'];
    // global
    $coreReplacements['TEMPLATECSS'] = $_templatecss;
    $coreReplacements['TEMPLATEURL'] = $_templateurl;
    $coreReplacements['THEREAREXQUESTIONS'] = $_therearexquestions;
    if (!$anonymized) {
        $coreReplacements['TOKEN'] = $_token;
    }
    $coreReplacements['URL'] = $_linkreplace;
    $coreReplacements['WELCOME'] = isset($thissurvey['welcome']) ? $thissurvey['welcome'] : '';
    if (!is_null($replacements) && is_array($replacements)) {
        $doTheseReplacements = array_merge($coreReplacements, $replacements);
        // so $replacements overrides core values
    } else {
        $doTheseReplacements = $coreReplacements;
    }
    // Now do all of the replacements - either call it twice or do recursion within LimeExpressionManager
    $line = LimeExpressionManager::ProcessString($line, $questionNum, $doTheseReplacements, false, 2, 1);
    return $line;
}
/**
* 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;
}
Ejemplo n.º 15
0
 /**
  * import from csv
  */
 public function import($iSurveyId)
 {
     $aData = array();
     $iSurveyId = (int) $iSurveyId;
     if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'import')) {
         Yii::app()->session['flashmessage'] = gT("You do not have permission to access this page.");
         $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}"));
     }
     // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY
     $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}');
     if (!$bTokenExists) {
         self::_newtokentable($iSurveyId);
     }
     $surveyinfo = Survey::model()->findByPk($iSurveyId)->surveyinfo;
     $aData['sidemenu']['state'] = false;
     $aData["surveyinfo"] = $surveyinfo;
     $aData['title_bar']['title'] = $surveyinfo['surveyls_title'] . "(" . gT("ID") . ":" . $iSurveyId . ")";
     $aData['sidemenu']["token_menu"] = TRUE;
     $aData['token_bar']['closebutton']['url'] = 'admin/tokens/sa/index/surveyid/' . $iSurveyId;
     $this->registerScriptFile('ADMIN_SCRIPT_PATH', 'tokensimport.js');
     $aEncodings = aEncodingsArray();
     if (Yii::app()->request->isPostRequest) {
         $sUploadCharset = Yii::app()->request->getPost('csvcharset');
         if (!array_key_exists($sUploadCharset, $aEncodings)) {
             $sUploadCharset = 'auto';
         }
         $bFilterDuplicateToken = Yii::app()->request->getPost('filterduplicatetoken');
         $bFilterBlankEmail = Yii::app()->request->getPost('filterblankemail');
         $bAllowInvalidEmail = Yii::app()->request->getPost('allowinvalidemail');
         $aAttrFieldNames = getAttributeFieldNames($iSurveyId);
         $aDuplicateList = array();
         $aInvalidTokenList = array();
         $aInvalidEmailList = array();
         $aInvalidFormatList = array();
         $aModelErrorList = array();
         $aFirstLine = array();
         $oFile = CUploadedFile::getInstanceByName("the_file");
         $sPath = Yii::app()->getConfig('tempdir');
         $sFileName = $sPath . '/' . randomChars(20);
         if ($_FILES['the_file']['error'] == 1 || $_FILES['the_file']['error'] == 2) {
             Yii::app()->setFlashMessage(sprintf(gT("Sorry, this file is too large. Only files up to %01.2f MB are allowed."), getMaximumFileUploadSize() / 1024 / 1024), 'error');
         } elseif (strtolower($oFile->getExtensionName()) != 'csv') {
             Yii::app()->setFlashMessage(gT("Only CSV files are allowed."), 'error');
         } elseif (!@$oFile->saveAs($sFileName)) {
             Yii::app()->setFlashMessage(sprintf(gT("Upload file not found. Check your permissions and path (%s) for the upload directory"), $sPath), 'error');
         } else {
             $iRecordImported = 0;
             $iRecordCount = 0;
             $iRecordOk = 0;
             $iInvalidEmailCount = 0;
             // Count invalid email imported
             // This allows to read file with MAC line endings too
             @ini_set('auto_detect_line_endings', true);
             // open it and trim the ednings
             $aTokenListArray = file($sFileName);
             $sBaseLanguage = Survey::model()->findByPk($iSurveyId)->language;
             if (!Yii::app()->request->getPost('filterduplicatefields') || Yii::app()->request->getPost('filterduplicatefields') && count(Yii::app()->request->getPost('filterduplicatefields')) == 0) {
                 $aFilterDuplicateFields = array('firstname', 'lastname', 'email');
             } else {
                 $aFilterDuplicateFields = Yii::app()->request->getPost('filterduplicatefields');
             }
             $sSeparator = Yii::app()->request->getPost('separator');
             $aMissingAttrFieldName = $aInvalideAttrFieldName = array();
             foreach ($aTokenListArray as $buffer) {
                 $buffer = @mb_convert_encoding($buffer, "UTF-8", $sUploadCharset);
                 if ($iRecordCount == 0) {
                     // Parse first line (header) from CSV
                     $buffer = removeBOM($buffer);
                     // We alow all field except tid because this one is really not needed.
                     $aAllowedFieldNames = Token::model($iSurveyId)->tableSchema->getColumnNames();
                     if (($kTid = array_search('tid', $aAllowedFieldNames)) !== false) {
                         unset($aAllowedFieldNames[$kTid]);
                     }
                     // Some header don't have same column name
                     $aReplacedFields = array('invited' => 'sent', 'reminded' => 'remindersent');
                     switch ($sSeparator) {
                         case 'comma':
                             $sSeparator = ',';
                             break;
                         case 'semicolon':
                             $sSeparator = ';';
                             break;
                         default:
                             $comma = substr_count($buffer, ',');
                             $semicolon = substr_count($buffer, ';');
                             if ($semicolon > $comma) {
                                 $sSeparator = ';';
                             } else {
                                 $sSeparator = ',';
                             }
                     }
                     $aFirstLine = str_getcsv($buffer, $sSeparator, '"');
                     $aFirstLine = array_map('trim', $aFirstLine);
                     $aIgnoredColumns = array();
                     // Now check the first line for invalid fields
                     foreach ($aFirstLine as $index => $sFieldname) {
                         $aFirstLine[$index] = preg_replace("/(.*) <[^,]*>\$/", "\$1", $sFieldname);
                         $sFieldname = $aFirstLine[$index];
                         if (!in_array($sFieldname, $aAllowedFieldNames)) {
                             $aIgnoredColumns[] = $sFieldname;
                         }
                         if (array_key_exists($sFieldname, $aReplacedFields)) {
                             $aFirstLine[$index] = $aReplacedFields[$sFieldname];
                         }
                         // Attribute not in list
                         if (strpos($aFirstLine[$index], 'attribute_') !== false and !in_array($aFirstLine[$index], $aAttrFieldNames) and Yii::app()->request->getPost('showwarningtoken')) {
                             $aInvalideAttrFieldName[] = $aFirstLine[$index];
                         }
                     }
                     //compare attributes with source csv
                     if (Yii::app()->request->getPost('showwarningtoken')) {
                         $aMissingAttrFieldName = array_diff($aAttrFieldNames, $aFirstLine);
                         // get list of mandatory attributes
                         $allAttrFieldNames = GetParticipantAttributes($iSurveyId);
                         //if it isn't mandantory field we don't need to show in warning
                         if (!empty($aAttrFieldNames)) {
                             if (!empty($aMissingAttrFieldName)) {
                                 foreach ($aMissingAttrFieldName as $index => $AttrFieldName) {
                                     if (isset($allAttrFieldNames[$AttrFieldName]) and strtolower($allAttrFieldNames[$AttrFieldName]["mandatory"]) != "y") {
                                         unset($aMissingAttrFieldName[$index]);
                                     }
                                 }
                             }
                             if (isset($aInvalideAttrFieldName) and !empty($aInvalideAttrFieldName)) {
                                 foreach ($aInvalideAttrFieldName as $index => $AttrFieldName) {
                                     if (isset($allAttrFieldNames[$AttrFieldName]) and strtolower($allAttrFieldNames[$AttrFieldName]["mandatory"]) != "y") {
                                         unset($aInvalideAttrFieldName[$index]);
                                     }
                                 }
                             }
                         }
                     }
                 } else {
                     $line = str_getcsv($buffer, $sSeparator, '"');
                     if (count($aFirstLine) != count($line)) {
                         $aInvalidFormatList[] = sprintf(gT("Line %s"), $iRecordCount);
                         $iRecordCount++;
                         continue;
                     }
                     $aWriteArray = array_combine($aFirstLine, $line);
                     //kick out ignored columns
                     foreach ($aIgnoredColumns as $column) {
                         unset($aWriteArray[$column]);
                     }
                     $bDuplicateFound = false;
                     $bInvalidEmail = false;
                     $bInvalidToken = false;
                     $aWriteArray['email'] = isset($aWriteArray['email']) ? trim($aWriteArray['email']) : "";
                     $aWriteArray['firstname'] = isset($aWriteArray['firstname']) ? $aWriteArray['firstname'] : "";
                     $aWriteArray['lastname'] = isset($aWriteArray['lastname']) ? $aWriteArray['lastname'] : "";
                     $aWriteArray['language'] = isset($aWriteArray['language']) ? $aWriteArray['language'] : $sBaseLanguage;
                     if ($bFilterDuplicateToken) {
                         $aParams = array();
                         $oCriteria = new CDbCriteria();
                         $oCriteria->condition = "";
                         foreach ($aFilterDuplicateFields as $field) {
                             if (isset($aWriteArray[$field])) {
                                 $oCriteria->addCondition("{$field} = :{$field}");
                                 $aParams[":{$field}"] = $aWriteArray[$field];
                             }
                         }
                         if (!empty($aParams)) {
                             $oCriteria->params = $aParams;
                         }
                         $dupresult = TokenDynamic::model($iSurveyId)->count($oCriteria);
                         if ($dupresult > 0) {
                             $bDuplicateFound = true;
                             $aDuplicateList[] = sprintf(gT("Line %s : %s %s (%s)"), $iRecordCount, $aWriteArray['firstname'], $aWriteArray['lastname'], $aWriteArray['email']);
                         }
                     }
                     //treat blank emails
                     if (!$bDuplicateFound && $bFilterBlankEmail && $aWriteArray['email'] == '') {
                         $bInvalidEmail = true;
                         $aInvalidEmailList[] = sprintf(gT("Line %s : %s %s"), $iRecordCount, CHtml::encode($aWriteArray['firstname']), CHtml::encode($aWriteArray['lastname']));
                     }
                     if (!$bDuplicateFound && $aWriteArray['email'] != '') {
                         $aEmailAddresses = preg_split("/(,|;)/", $aWriteArray['email']);
                         foreach ($aEmailAddresses as $sEmailaddress) {
                             if (!validateEmailAddress($sEmailaddress)) {
                                 if ($bAllowInvalidEmail) {
                                     $iInvalidEmailCount++;
                                     if (empty($aWriteArray['emailstatus']) || strtoupper($aWriteArray['emailstatus'] == "OK")) {
                                         $aWriteArray['emailstatus'] = "invalid";
                                     }
                                 } else {
                                     $bInvalidEmail = true;
                                     $aInvalidEmailList[] = sprintf(gT("Line %s : %s %s (%s)"), $iRecordCount, CHtml::encode($aWriteArray['firstname']), CHtml::encode($aWriteArray['lastname']), CHtml::encode($aWriteArray['email']));
                                 }
                             }
                         }
                     }
                     if (!$bDuplicateFound && !$bInvalidEmail && isset($aWriteArray['token']) && trim($aWriteArray['token']) != '') {
                         if (trim($aWriteArray['token']) != sanitize_token($aWriteArray['token'])) {
                             $aInvalidTokenList[] = sprintf(gT("Line %s : %s %s (%s) - token : %s"), $iRecordCount, CHtml::encode($aWriteArray['firstname']), CHtml::encode($aWriteArray['lastname']), CHtml::encode($aWriteArray['email']), CHtml::encode($aWriteArray['token']));
                             $bInvalidToken = true;
                         }
                         // We allways search for duplicate token (it's in model. Allow to reset or update token ?
                         if (Token::model($iSurveyId)->count("token=:token", array(":token" => $aWriteArray['token']))) {
                             $bDuplicateFound = true;
                             $aDuplicateList[] = sprintf(gT("Line %s : %s %s (%s) - token : %s"), $iRecordCount, CHtml::encode($aWriteArray['firstname']), CHtml::encode($aWriteArray['lastname']), CHtml::encode($aWriteArray['email']), CHtml::encode($aWriteArray['token']));
                         }
                     }
                     if (!$bDuplicateFound && !$bInvalidEmail && !$bInvalidToken) {
                         // unset all empty value
                         foreach ($aWriteArray as $key => $value) {
                             if ($aWriteArray[$key] == "") {
                                 unset($aWriteArray[$key]);
                             }
                             if (substr($value, 0, 1) == '"' && substr($value, -1) == '"') {
                                 // Fix CSV quote
                                 $value = substr($value, 1, -1);
                             }
                         }
                         // Some default value : to be moved to Token model rules in future release ?
                         // But think we have to accept invalid email etc ... then use specific scenario
                         $oToken = Token::create($iSurveyId);
                         if ($bAllowInvalidEmail) {
                             $oToken->scenario = 'allowinvalidemail';
                         }
                         foreach ($aWriteArray as $key => $value) {
                             $oToken->{$key} = $value;
                         }
                         if (!$oToken->save()) {
                             $errors = $oToken->getErrors();
                             $aModelErrorList[] = sprintf(gT("Line %s : %s"), $iRecordCount, print_r($errors, true));
                         } else {
                             $iRecordImported++;
                         }
                     }
                     $iRecordOk++;
                 }
                 $iRecordCount++;
             }
             $iRecordCount = $iRecordCount - 1;
             unlink($sFileName);
             $aData['aTokenListArray'] = $aTokenListArray;
             // Big array in memory, just for success ?
             $aData['iRecordImported'] = $iRecordImported;
             $aData['iRecordOk'] = $iRecordOk;
             $aData['iRecordCount'] = $iRecordCount;
             $aData['aFirstLine'] = $aFirstLine;
             // Seem not needed
             $aData['aDuplicateList'] = $aDuplicateList;
             $aData['aInvalidTokenList'] = $aInvalidTokenList;
             $aData['aInvalidFormatList'] = $aInvalidFormatList;
             $aData['aInvalidEmailList'] = $aInvalidEmailList;
             $aData['aModelErrorList'] = $aModelErrorList;
             $aData['iInvalidEmailCount'] = $iInvalidEmailCount;
             $aData['thissurvey'] = getSurveyInfo($iSurveyId);
             $aData['iSurveyId'] = $aData['surveyid'] = $iSurveyId;
             $aData['aInvalideAttrFieldName'] = $aInvalideAttrFieldName;
             $aData['aMissingAttrFieldName'] = $aMissingAttrFieldName;
             $this->_renderWrappedTemplate('token', array('csvimportresult'), $aData);
             Yii::app()->end();
         }
     }
     // If there are error with file : show the form
     $aData['aEncodings'] = $aEncodings;
     asort($aData['aEncodings']);
     $aData['iSurveyId'] = $iSurveyId;
     $aData['thissurvey'] = getSurveyInfo($iSurveyId);
     $aData['surveyid'] = $iSurveyId;
     $aTokenTableFields = getTokenFieldsAndNames($iSurveyId);
     unset($aTokenTableFields['sent']);
     unset($aTokenTableFields['remindersent']);
     unset($aTokenTableFields['remindercount']);
     unset($aTokenTableFields['usesleft']);
     foreach ($aTokenTableFields as $sKey => $sValue) {
         if ($sValue['description'] != $sKey) {
             $sValue['description'] .= ' - ' . $sKey;
         }
         $aNewTokenTableFields[$sKey] = $sValue['description'];
     }
     $aData['aTokenTableFields'] = $aNewTokenTableFields;
     // Get default character set from global settings
     $thischaracterset = getGlobalSetting('characterset');
     // If no encoding was set yet, use the old "auto" default
     if ($thischaracterset == "") {
         $thischaracterset = "auto";
     }
     $aData['thischaracterset'] = $thischaracterset;
     $this->_renderWrappedTemplate('token', array('csvupload'), $aData);
 }
Ejemplo n.º 16
0
/**
* This function replaces keywords in a text and is mainly intended for templates
* If you use this functions put your replacement strings into the $replacements variable
* instead of using global variables
* NOTE - Don't do any embedded replacements in this function.  Create the array of replacement values and
* they will be done in batch at the end
*
* @param mixed $line Text to search in
* @param mixed $replacements Array of replacements:  Array( <stringtosearch>=><stringtoreplacewith>
* @param boolean $anonymized Determines if token data is being used or just replaced with blanks
* @param questionNum - needed to support dynamic JavaScript-based tailoring within questions
* @return string  Text with replaced strings
*/
function templatereplace($line, $replacements = array(), &$redata = array(), $debugSrc = 'Unspecified', $anonymized = false, $questionNum = NULL, $registerdata = array())
{
    /*
    global $clienttoken,$token,$sitename,$move,$showxquestions,$showqnumcode,$questioncode,$register_errormsg;
    global $s_lang,$errormsg,$saved_id, $relativeurl, $languagechanger,$captchapath,$loadname;
    */
    /*
    $allowedvars = array('surveylist', 'sitename', 'clienttoken', 'rooturl', 'thissurvey', 'imageurl', 'defaulttemplate',
    'percentcomplete', 'move', 'groupname', 'groupdescription', 'question', 'showxquestions',
    'showgroupinfo', 'showqnumcode', 'questioncode', 'answer', 'navigator', 'help', 'totalquestions',
    'surveyformat', 'completed', 'register_errormsg', 'notanswered', 'privacy', 'surveyid', 'publicurl',
    'templatedir', 'token', 'assessments', 's_lang', 'errormsg', 'clang', 'saved_id', 'usertemplaterootdir',
    'relativeurl', 'languagechanger', 'printoutput', 'captchapath', 'loadname');
    */
    $allowedvars = array('answer', 'assessments', 'captchapath', 'clienttoken', 'completed', 'errormsg', 'groupdescription', 'groupname', 'help', 'imageurl', 'languagechanger', 'loadname', 'move', 'navigator', 'percentcomplete', 'privacy', 'question', 'register_errormsg', 'relativeurl', 's_lang', 'saved_id', 'showgroupinfo', 'showqnumcode', 'showxquestions', 'sitename', 'surveylist', 'templatedir', 'thissurvey', 'token', 'totalBoilerplatequestions', 'totalquestions');
    $varsPassed = array();
    foreach ($allowedvars as $var) {
        if (isset($redata[$var])) {
            ${$var} = $redata[$var];
            $varsPassed[] = $var;
        }
    }
    //    if (count($varsPassed) > 0) {
    //        log_message('debug', 'templatereplace() called from ' . $debugSrc . ' contains: ' . implode(', ', $varsPassed));
    //    }
    //    if (isset($redata['question'])) {
    //        LimeExpressionManager::ShowStackTrace('has QID and/or SGA',$allowedvars);
    //    }
    //    extract($redata);   // creates variables for each of the keys in the array
    // Local over-rides in case not set above
    if (!isset($showgroupinfo)) {
        $showgroupinfo = Yii::app()->getConfig('showgroupinfo');
    }
    if (!isset($showqnumcode)) {
        $showqnumcode = Yii::app()->getConfig('showqnumcode');
    }
    $_surveyid = Yii::app()->getConfig('surveyID');
    if (!isset($showxquestions)) {
        $showxquestions = Yii::app()->getConfig('showxquestions');
    }
    if (!isset($s_lang)) {
        $s_lang = isset(Yii::app()->session['survey_' . $_surveyid]['s_lang']) ? Yii::app()->session['survey_' . $_surveyid]['s_lang'] : 'en';
    }
    if (!isset($captchapath)) {
        $captchapath = '';
    }
    $clang = Yii::app()->lang;
    Yii::app()->loadHelper('surveytranslator');
    $questiondetails = array('sid' => 0, 'gid' => 0, 'qid' => 0, 'aid' => 0);
    if (isset($question) && isset($question['sgq'])) {
        $questiondetails = getSIDGIDQIDAIDType($question['sgq']);
    }
    //Gets an array containing SID, GID, QID, AID and Question Type)
    if (isset($thissurvey['sid'])) {
        $surveyid = $thissurvey['sid'];
    }
    // lets sanitize the survey template
    if (isset($thissurvey['templatedir'])) {
        $templatename = $thissurvey['templatedir'];
    } else {
        $templatename = Yii::app()->getConfig('defaulttemplate');
    }
    if (!isset($templatedir)) {
        $templatedir = getTemplatePath($templatename);
    }
    if (!isset($templateurl)) {
        $templateurl = getTemplateURL($templatename) . "/";
    }
    // TEMPLATECSS and TEMPLATEJS
    $_templatecss = "";
    $_templatejs = "";
    if (stripos($line, "{TEMPLATECSS}")) {
        $css_header_includes = Yii::app()->getConfig("css_header_includes");
        if (file_exists($templatedir . DIRECTORY_SEPARATOR . 'jquery-ui-custom.css')) {
            $template_jqueryui_css = "<link rel='stylesheet' type='text/css' media='all' href='{$templateurl}jquery-ui-custom.css' />\n";
        } elseif (file_exists($templatedir . DIRECTORY_SEPARATOR . 'jquery-ui.css')) {
            $template_jqueryui_css = "<link rel='stylesheet' type='text/css' media='all' href='{$templateurl}jquery-ui.css' />\n";
        } else {
            $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='" . Yii::app()->getConfig('publicstyleurl') . "jquery-ui.css' />\n";
            // Remove it after corrected slider
            $template_jqueryui_css = "";
        }
        if ($css_header_includes) {
            foreach ($css_header_includes as $cssinclude) {
                if (substr($cssinclude, 0, 4) == 'http' || substr($cssinclude, 0, strlen(Yii::app()->getConfig('publicurl'))) == Yii::app()->getConfig('publicurl')) {
                    $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='" . $cssinclude . "' />\n";
                } else {
                    if (file_exists($templatedir . DIRECTORY_SEPARATOR . $cssinclude)) {
                        $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='{$templateurl}{$cssinclude}' />\n";
                    } else {
                        $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='" . Yii::app()->getConfig('publicstyleurl') . $cssinclude . "' />\n";
                    }
                }
            }
        }
        $_templatecss .= $template_jqueryui_css;
        // Template jquery ui after default css
        $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='{$templateurl}template.css' />\n";
        if (getLanguageRTL($clang->langcode)) {
            $_templatecss .= "<link rel='stylesheet' type='text/css' media='all' href='{$templateurl}template-rtl.css' />\n";
        }
    }
    if (stripos($line, "{TEMPLATEJS}")) {
        $js_header_includes = header_includes(false, 'js');
        $_jqueryuijsurl = Yii::app()->getConfig('generalscripts') . "jquery/jquery-ui.js";
        $_templatejs .= "<script type='text/javascript' src='" . Yii::app()->getConfig('generalscripts') . "jquery/jquery.js'></script>\n";
        $_templatejs .= "<script type='text/javascript' src='{$_jqueryuijsurl}'></script>\n";
        $_templatejs .= "<script type='text/javascript' src='" . Yii::app()->getConfig('generalscripts') . "jquery/jquery.ui.touch-punch.min.js'></script>\n";
        if ($js_header_includes) {
            foreach ($js_header_includes as $jsinclude) {
                if (substr($jsinclude, 0, 4) == 'http' || substr($jsinclude, 0, strlen(Yii::app()->getConfig('publicurl'))) == Yii::app()->getConfig('publicurl')) {
                    $_templatejs .= "<script type='text/javascript' src='{$jsinclude}'></script>\n";
                } else {
                    $_templatejs .= "<script type='text/javascript' src='" . Yii::app()->getConfig('generalscripts') . $jsinclude . "'></script>\n";
                }
            }
        }
        $_templatejs .= "<script type='text/javascript' src='" . Yii::app()->getConfig('generalscripts') . "survey_runtime.js'></script>\n";
        $_templatejs .= "<script type='text/javascript' src='{$templateurl}template.js'></script>\n";
        $_templatejs .= useFirebug();
    }
    // surveyformat
    if (isset($thissurvey['format'])) {
        $surveyformat = str_replace(array("A", "S", "G"), array("allinone", "questionbyquestion", "groupbygroup"), $thissurvey['format']);
    } else {
        $surveyformat = "";
    }
    if (isset(Yii::app()->session['step']) && Yii::app()->session['step'] % 2 && $surveyformat != "allinone") {
        $surveyformat .= " page-odd";
    }
    if (isset($thissurvey['allowjumps']) && $thissurvey['allowjumps'] == "Y" && $surveyformat != "allinone" && (isset(Yii::app()->session['step']) && Yii::app()->session['step'] > 0)) {
        $surveyformat .= " withindex";
    }
    if (isset($thissurvey['showprogress']) && $thissurvey['showprogress'] == "Y") {
        $surveyformat .= " showprogress";
    }
    if (isset($thissurvey['showqnumcode'])) {
        $surveyformat .= " showqnumcode-" . $thissurvey['showqnumcode'];
    }
    // real survey contact
    if (isset($surveylist) && isset($surveylist['contact'])) {
        $surveycontact = $surveylist['contact'];
    } elseif (isset($surveylist) && isset($thissurvey['admin']) && $thissurvey['admin'] != "") {
        $surveycontact = sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $thissurvey['admin'], $thissurvey['adminemail']);
    } else {
        $surveycontact = "";
    }
    // If there are non-bracketed replacements to be made do so above this line.
    // Only continue in this routine if there are bracketed items to replace {}
    if (strpos($line, "{") === false) {
        // process string anyway so that it can be pretty-printed
        return LimeExpressionManager::ProcessString($line, $questionNum, NULL, false, 1, 1, true);
    }
    if ($showgroupinfo == 'both' || $showgroupinfo == 'name' || $showgroupinfo == 'choose' && !isset($thissurvey['showgroupinfo']) || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'B' || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'N') {
        $_groupname = isset($groupname) ? $groupname : '';
    } else {
        $_groupname = '';
    }
    if ($showgroupinfo == 'both' || $showgroupinfo == 'description' || $showgroupinfo == 'choose' && !isset($thissurvey['showgroupinfo']) || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'B' || $showgroupinfo == 'choose' && $thissurvey['showgroupinfo'] == 'D') {
        $_groupdescription = isset($groupdescription) ? $groupdescription : '';
    } else {
        $_groupdescription = '';
    }
    if (isset($question) && is_array($question)) {
        $_question = $question['all'];
        $_question_text = $question['text'];
        $_question_help = $question['help'];
        $_question_mandatory = $question['mandatory'];
        $_question_man_message = $question['man_message'];
        $_question_valid_message = $question['valid_message'];
        $_question_file_valid_message = $question['file_valid_message'];
        $_question_sgq = isset($question['sgq']) ? $question['sgq'] : '';
        $_question_essentials = $question['essentials'];
        $_getQuestionClass = $question['class'];
        $_question_man_class = $question['man_class'];
        $_question_input_error_class = $question['input_error_class'];
        $_question_number = $question['number'];
        $_question_code = $question['code'];
        $_question_type = $question['type'];
    } else {
        $_question = isset($question) ? $question : '';
        $_question_text = '';
        $_question_help = '';
        $_question_mandatory = '';
        $_question_man_message = '';
        $_question_valid_message = '';
        $_question_file_valid_message = '';
        $_question_sgq = '';
        $_question_essentials = '';
        $_getQuestionClass = '';
        $_question_man_class = '';
        $_question_input_error_class = '';
        $_question_number = '';
        $_question_code = '';
        $_question_type = '';
    }
    if ($_question_type == '*') {
        $_question_text = '<div class="em_equation">' . $_question_text . '</div>';
    }
    if (!($showqnumcode == 'both' || $showqnumcode == 'number' || $showqnumcode == 'choose' && !isset($thissurvey['showqnumcode']) || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'B' || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'N')) {
        $_question_number = '';
    }
    if (!($showqnumcode == 'both' || $showqnumcode == 'code' || $showqnumcode == 'choose' && !isset($thissurvey['showqnumcode']) || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'B' || $showqnumcode == 'choose' && $thissurvey['showqnumcode'] == 'C')) {
        $_question_code = '';
    }
    if (!isset($totalquestions)) {
        $totalquestions = 0;
    }
    $_totalquestionsAsked = $totalquestions;
    if ($showxquestions == 'show' || $showxquestions == 'choose' && !isset($thissurvey['showxquestions']) || $showxquestions == 'choose' && $thissurvey['showxquestions'] == 'Y') {
        if ($_totalquestionsAsked < 1) {
            $_therearexquestions = $clang->gT("There are no questions in this survey");
            // Singular
        } elseif ($_totalquestionsAsked == 1) {
            $_therearexquestions = $clang->gT("There is 1 question in this survey");
            //Singular
        } else {
            $_therearexquestions = $clang->gT("There are {NUMBEROFQUESTIONS} questions in this survey.");
            //Note this line MUST be before {NUMBEROFQUESTIONS}
        }
    } else {
        $_therearexquestions = '';
    }
    if (isset($token)) {
        $_token = $token;
    } elseif (isset($clienttoken)) {
        $_token = htmlentities($clienttoken, ENT_QUOTES, 'UTF-8');
        // or should it be URL-encoded?
    } else {
        $_token = '';
    }
    // Expiry
    if (isset($thissurvey['expiry'])) {
        $dateformatdetails = getDateFormatData($thissurvey['surveyls_dateformat']);
        Yii::import('application.libraries.Date_Time_Converter', true);
        $datetimeobj = new Date_Time_Converter($thissurvey['expiry'], "Y-m-d");
        $_dateoutput = $datetimeobj->convert($dateformatdetails['phpdate']);
    } else {
        $_dateoutput = '-';
    }
    $_submitbutton = "<input class='submit' type='submit' value=' " . $clang->gT("Submit") . " ' name='move2' onclick=\"javascript:document.limesurvey.move.value = 'movesubmit';\" />";
    if (isset($thissurvey['surveyls_url']) and $thissurvey['surveyls_url'] != "") {
        if (trim($thissurvey['surveyls_urldescription']) != '') {
            $_linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_urldescription']}</a>";
        } else {
            $_linkreplace = "<a href='{$thissurvey['surveyls_url']}'>{$thissurvey['surveyls_url']}</a>";
        }
    } else {
        $_linkreplace = '';
    }
    if (isset($thissurvey['sid']) && isset($_SESSION['survey_' . $thissurvey['sid']]['srid']) && $thissurvey['active'] == 'Y') {
        $iscompleted = Survey_dynamic::model($surveyid)->isCompleted($_SESSION['survey_' . $thissurvey['sid']]['srid']);
    } else {
        $iscompleted = false;
    }
    if (isset($surveyid) && !$iscompleted) {
        $_clearall = "<input type='button' name='clearallbtn' value='" . $clang->gT("Exit and clear survey") . "' class='clearall' " . "onclick=\"if (confirm('" . $clang->gT("Are you sure you want to clear all your responses?", 'js') . "')) {\nwindow.open('" . Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}", array('move' => 'clearall', 'lang' => $s_lang), '&amp;');
        if (returnGlobal('token')) {
            $_clearall .= "&amp;token=" . urlencode(trim(sanitize_token(strip_tags(returnGlobal('token')))));
        }
        $_clearall .= "', '_self')}\" />";
    } else {
        $_clearall = "";
    }
    if (isset(Yii::app()->session['datestamp'])) {
        $_datestamp = Yii::app()->session['datestamp'];
    } else {
        $_datestamp = '-';
    }
    if (isset($thissurvey['allowsave']) and $thissurvey['allowsave'] == "Y") {
        // Find out if the user has any saved data
        if ($thissurvey['format'] == 'A') {
            if ($thissurvey['tokenanswerspersistence'] != 'Y' || !isset($surveyid) || !tableExists('tokens_' . $surveyid)) {
                $_saveall = "\t\t\t<input type='button' name='loadall' value='" . $clang->gT("Load unfinished survey") . "' class='saveall' onclick=\"javascript:addHiddenField(document.getElementById('limesurvey'),'loadall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>" . "\n\t\t\t<input type='button' name='saveallbtn' value='" . $clang->gT("Resume later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
                // Show Save So Far button
            } else {
                $_saveall = "\t\t\t<input type='button' name='saveallbtn' value='" . $clang->gT("Resume later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
                // Show Save So Far button
            }
        } elseif (isset($surveyid) && (!isset($_SESSION['survey_' . $surveyid]['step']) || !$_SESSION['survey_' . $surveyid]['step'])) {
            //First page, show LOAD
            if ($thissurvey['tokenanswerspersistence'] != 'Y' || !isset($surveyid) || !tableExists('tokens_' . $surveyid)) {
                $_saveall = "\t\t\t<input type='button' name='loadall' value='" . $clang->gT("Load unfinished survey") . "' class='saveall' onclick=\"javascript:addHiddenField(document.getElementById('limesurvey'),'loadall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
            } else {
                $_saveall = '';
            }
        } elseif (isset(Yii::app()->session['scid']) && (isset($move) && $move == "movelast")) {
            //Already saved and on Submit Page, dont show Save So Far button
            $_saveall = '';
        } else {
            $_saveall = "<input type='button' name='saveallbtn' value='" . $clang->gT("Resume later") . "' class='saveall' onclick=\"javascript:document.limesurvey.move.value = this.value;addHiddenField(document.getElementById('limesurvey'),'saveall',this.value);document.getElementById('limesurvey').submit();\" " . ($thissurvey['active'] != "Y" ? "disabled='disabled'" : "") . "/>";
            // Show Save So Far button
        }
    } else {
        $_saveall = "";
    }
    if (!isset($help)) {
        $help = "";
    }
    if (flattenText($help, true, true) != '') {
        if (!isset($helpicon)) {
            if (file_exists($templatedir . '/help.gif')) {
                $helpicon = $templateurl . 'help.gif';
            } elseif (file_exists($templatedir . '/help.png')) {
                $helpicon = $templateurl . 'help.png';
            } else {
                $helpicon = Yii::app()->getConfig('imageurl') . "/help.gif";
            }
        }
        $_questionhelp = "<img src='{$helpicon}' alt='Help' align='left' />" . $help;
    } else {
        $_questionhelp = $help;
    }
    if (isset($thissurvey['allowprev']) && $thissurvey['allowprev'] == "N") {
        $_strreview = "";
    } else {
        $_strreview = $clang->gT("If you want to check any of the answers you have made, and/or change them, you can do that now by clicking on the [<< prev] button and browsing through your responses.");
    }
    if (isset($thissurvey['active']) and $thissurvey['active'] == "N") {
        $_restart = "<a href='" . Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}/newtest/Y");
        if (isset($s_lang) && $s_lang != '') {
            $_restart .= "/lang/" . $s_lang;
        }
        $_restart .= "'>" . $clang->gT("Restart this survey") . "</a>";
    } else {
        if (isset($surveyid)) {
            $restart_extra = "";
            $restart_token = returnGlobal('token');
            if (!empty($restart_token)) {
                $restart_extra .= "/token/" . urlencode($restart_token);
            } else {
                $restart_extra = "/newtest/Y";
            }
            if (!empty($_GET['lang'])) {
                $restart_extra .= "/lang/" . returnGlobal('lang');
            }
            $_restart = "<a href='" . Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}{$restart_extra}") . "'>" . $clang->gT("Restart this Survey") . "</a>";
        } else {
            $_restart = "";
        }
    }
    if (isset($thissurvey['anonymized']) && $thissurvey['anonymized'] == 'Y') {
        $_savealert = $clang->gT("To remain anonymous please use a pseudonym as your username, also an email address is not required.");
    } else {
        $_savealert = "";
    }
    if (isset($surveyid)) {
        $_return_to_survey = "<a href=" . Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}");
        if (returnGlobal('token')) {
            $_return_to_survey .= "?amp;token=" . urlencode(trim(sanitize_xss_string(strip_tags(returnGlobal('token')))));
        }
        $_return_to_survey .= "'>" . $clang->gT("Return to survey") . "</a>";
    } else {
        $_return_to_survey = "";
    }
    // Save Form
    $_saveform = "<table><tr><td align='right'>" . $clang->gT("Name") . ":</td><td><input type='text' name='savename' value='";
    if (isset($_POST['savename'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['savename']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Password") . ":</td><td><input type='password' name='savepass' value='";
    if (isset($_POST['savepass'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['savepass']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Repeat password") . ":</td><td><input type='password' name='savepass2' value='";
    if (isset($_POST['savepass2'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['savepass2']));
    }
    $_saveform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Your email address") . ":</td><td><input type='text' name='saveemail' value='";
    if (isset($_POST['saveemail'])) {
        $_saveform .= HTMLEscape(autoUnescape($_POST['saveemail']));
    }
    $_saveform .= "' /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
        $_saveform .= "<tr><td align='right'>" . $clang->gT("Security question") . ":</td><td><table><tr><td valign='middle'><img src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . (isset($surveyid) ? $surveyid : '')) . "' alt6='' /></td><td valign='middle' style='text-align:left'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table></td></tr>\n";
    }
    $_saveform .= "<tr><td align='right'></td><td></td></tr>\n" . "<tr><td></td><td><input type='submit'  id='savebutton' name='savesubmit' value='" . $clang->gT("Save Now") . "' /></td></tr>\n" . "</table>";
    // Load Form
    $_loadform = "<table><tr><td align='right'>" . $clang->gT("Saved name") . ":</td><td><input type='text' name='loadname' value='";
    if (isset($loadname)) {
        $_loadform .= HTMLEscape(autoUnescape($loadname));
    }
    $_loadform .= "' /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Password") . ":</td><td><input type='password' name='loadpass' value='";
    if (isset($loadpass)) {
        $_loadform .= HTMLEscape(autoUnescape($loadpass));
    }
    $_loadform .= "' /></td></tr>\n";
    if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) {
        $_loadform .= "<tr><td align='right'>" . $clang->gT("Security question") . ":</td><td><table><tr><td valign='middle'><img src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='' /></td><td valign='middle'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' alt=''/></td></tr></table></td></tr>\n";
    }
    $_loadform .= "<tr><td align='right'></td><td></td></tr>\n" . "<tr><td></td><td><input type='submit' id='loadbutton' value='" . $clang->gT("Load now") . "' /></td></tr></table>\n";
    // Registration Form
    if (isset($surveyid) || isset($registerdata) && $debugSrc == 'register.php') {
        if (isset($surveyid)) {
            $tokensid = $surveyid;
        } else {
            $tokensid = $registerdata['sid'];
        }
        $_registerform = "<form method='post' action='" . Yii::app()->getController()->createUrl('/register/index/surveyid/' . $tokensid) . "'>\n";
        if (!isset($_REQUEST['lang'])) {
            $_reglang = Survey::model()->findByPk($tokensid)->language;
        } else {
            $_reglang = returnGlobal('lang');
        }
        $_registerform .= "<input type='hidden' name='lang' value='" . $_reglang . "' />\n";
        $_registerform .= "<input type='hidden' name='sid' value='{$tokensid}' id='sid' />\n";
        $_registerform .= "<table class='register' summary='Registrationform'>\n" . "<tr><td align='right'>" . $clang->gT("First name") . ":</td>" . "<td align='left'><input class='text' type='text' name='register_firstname'";
        if (isset($_POST['register_firstname'])) {
            $_registerform .= " value='" . htmlentities(returnGlobal('register_firstname'), ENT_QUOTES, 'UTF-8') . "'";
        }
        $_registerform .= " /></td></tr>" . "<tr><td align='right'>" . $clang->gT("Last name") . ":</td>\n" . "<td align='left'><input class='text' type='text' name='register_lastname'";
        if (isset($_POST['register_lastname'])) {
            $_registerform .= " value='" . htmlentities(returnGlobal('register_lastname'), ENT_QUOTES, 'UTF-8') . "'";
        }
        $_registerform .= " /></td></tr>\n" . "<tr><td align='right'>" . $clang->gT("Email address") . ":</td>\n" . "<td align='left'><input class='text' type='text' name='register_email'";
        if (isset($_POST['register_email'])) {
            $_registerform .= " value='" . htmlentities(returnGlobal('register_email'), ENT_QUOTES, 'UTF-8') . "'";
        }
        $_registerform .= " /></td></tr>\n";
        foreach ($thissurvey['attributedescriptions'] as $field => $attribute) {
            if (empty($attribute['show_register']) || $attribute['show_register'] != 'Y') {
                continue;
            }
            $_registerform .= '
            <tr>
            <td align="right">' . $thissurvey['attributecaptions'][$field] . ($attribute['mandatory'] == 'Y' ? '*' : '') . ':</td>
            <td align="left"><input class="text" type="text" name="register_' . $field . '" /></td>
            </tr>';
        }
        if ((count($registerdata) > 1 || isset($thissurvey['usecaptcha'])) && function_exists("ImageCreate") && isCaptchaEnabled('registrationscreen', $thissurvey['usecaptcha'])) {
            $_registerform .= "<tr><td align='right'>" . $clang->gT("Security Question") . ":</td><td><table><tr><td valign='middle'><img src='" . Yii::app()->getController()->createUrl('/verification/image/sid/' . $surveyid) . "' alt='' /></td><td valign='middle'><input type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table></td></tr>\n";
        }
        $_registerform .= "<tr><td></td><td><input id='registercontinue' class='submit' type='submit' value='" . $clang->gT("Continue") . "' />" . "</td></tr>\n" . "</table>\n";
        if (count($registerdata) > 1 && $registerdata['sid'] != NULL && $debugSrc == 'register.php') {
            $_registerform .= "<input name='startdate' type ='hidden' value='" . $registerdata['startdate'] . "' />";
            $_registerform .= "<input name='enddate' type ='hidden' value='" . $registerdata['enddate'] . "' />";
        }
        $_registerform .= "</form>\n";
    } else {
        $_registerform = "";
    }
    // Assessments
    $assessmenthtml = "";
    if (isset($surveyid) && !is_null($surveyid) && function_exists('doAssessment')) {
        $assessmentdata = doAssessment($surveyid, true);
        $_assessment_current_total = $assessmentdata['total'];
        if (stripos($line, "{ASSESSMENTS}")) {
            $assessmenthtml = doAssessment($surveyid, false);
        }
    } else {
        $_assessment_current_total = '';
    }
    if (isset($thissurvey['googleanalyticsapikey']) && trim($thissurvey['googleanalyticsapikey']) != '') {
        $_googleAnalyticsAPIKey = trim($thissurvey['googleanalyticsapikey']);
    } else {
        $_googleAnalyticsAPIKey = trim(getGlobalSetting('googleanalyticsapikey'));
    }
    $_googleAnalyticsStyle = isset($thissurvey['googleanalyticsstyle']) ? $thissurvey['googleanalyticsstyle'] : '0';
    $_googleAnalyticsJavaScript = '';
    if ($_googleAnalyticsStyle != '' && $_googleAnalyticsStyle != 0 && $_googleAnalyticsAPIKey != '') {
        switch ($_googleAnalyticsStyle) {
            case '1':
                // Default Google Tracking
                $_googleAnalyticsJavaScript = <<<EOD
<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', '{$_googleAnalyticsAPIKey}']);
  _gaq.push(['_trackPageview']);

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

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
</script>
EOD;
                break;
        }
    }
    $_endtext = '';
    if (isset($thissurvey['surveyls_endtext']) && trim($thissurvey['surveyls_endtext']) != '') {
        $_endtext = $thissurvey['surveyls_endtext'];
    }
    // Set the array of replacement variables here - don't include curly braces
    $coreReplacements = array();
    $coreReplacements['ACTIVE'] = isset($thissurvey['active']) && !($thissurvey['active'] != "Y");
    $coreReplacements['AID'] = isset($questiondetails['aid']) ? $questiondetails['aid'] : '';
    $coreReplacements['ANSWER'] = isset($answer) ? $answer : '';
    // global
    $coreReplacements['ANSWERSCLEARED'] = $clang->gT("Answers cleared");
    $coreReplacements['ASSESSMENTS'] = $assessmenthtml;
    $coreReplacements['ASSESSMENT_CURRENT_TOTAL'] = $_assessment_current_total;
    $coreReplacements['ASSESSMENT_HEADING'] = $clang->gT("Your assessment");
    $coreReplacements['CHECKJAVASCRIPT'] = "<noscript><span class='warningjs'>" . $clang->gT("Caution: JavaScript execution is disabled in your browser. You may not be able to answer all questions in this survey. Please, verify your browser parameters.") . "</span></noscript>";
    $coreReplacements['CLEARALL'] = $_clearall;
    $coreReplacements['CLOSEWINDOW'] = "<a href='javascript:%20self.close()'>" . $clang->gT("Close this window") . "</a>";
    $coreReplacements['COMPLETED'] = isset($redata['completed']) ? $redata['completed'] : '';
    // global
    $coreReplacements['DATESTAMP'] = $_datestamp;
    $coreReplacements['ENDTEXT'] = $_endtext;
    $coreReplacements['EXPIRY'] = $_dateoutput;
    $coreReplacements['GID'] = isset($questiondetails['gid']) ? $questiondetails['gid'] : '';
    $coreReplacements['GOOGLE_ANALYTICS_API_KEY'] = $_googleAnalyticsAPIKey;
    $coreReplacements['GOOGLE_ANALYTICS_JAVASCRIPT'] = $_googleAnalyticsJavaScript;
    $coreReplacements['GROUPDESCRIPTION'] = $_groupdescription;
    $coreReplacements['GROUPNAME'] = $_groupname;
    $coreReplacements['LANG'] = $clang->getlangcode();
    $coreReplacements['LANGUAGECHANGER'] = isset($languagechanger) ? $languagechanger : '';
    // global
    $coreReplacements['LOADERROR'] = isset($errormsg) ? $errormsg : '';
    // global
    $coreReplacements['LOADFORM'] = $_loadform;
    $coreReplacements['LOADHEADING'] = $clang->gT("Load a previously saved survey");
    $coreReplacements['LOADMESSAGE'] = $clang->gT("You can load a survey that you have previously saved from this screen.") . "<br />" . $clang->gT("Type in the 'name' you used to save the survey, and the password.") . "<br />";
    $coreReplacements['NAVIGATOR'] = isset($navigator) ? $navigator : '';
    // global
    $coreReplacements['NOSURVEYID'] = isset($surveylist) ? $surveylist['nosid'] : '';
    $coreReplacements['NUMBEROFQUESTIONS'] = $_totalquestionsAsked;
    $coreReplacements['PERCENTCOMPLETE'] = isset($percentcomplete) ? $percentcomplete : '';
    // global
    $coreReplacements['PRIVACY'] = isset($privacy) ? $privacy : '';
    // global
    $coreReplacements['PRIVACYMESSAGE'] = "<span style='font-weight:bold; font-style: italic;'>" . $clang->gT("A Note On Privacy") . "</span><br />" . $clang->gT("This survey is anonymous.") . "<br />" . $clang->gT("The record kept of your survey responses does not contain any identifying information about you unless a specific question in the survey has asked for this. If you have responded to a survey that used an identifying token to allow you to access the survey, you can rest assured that the identifying token is not kept with your responses. It is managed in a separate database, and will only be updated to indicate that you have (or haven't) completed this survey. There is no way of matching identification tokens with survey responses in this survey.");
    $coreReplacements['QID'] = isset($questiondetails['qid']) ? $questiondetails['qid'] : '';
    $coreReplacements['QUESTION'] = $_question;
    $coreReplacements['QUESTIONHELP'] = $_questionhelp;
    $coreReplacements['QUESTIONHELPPLAINTEXT'] = strip_tags(addslashes($help));
    // global
    $coreReplacements['QUESTION_CLASS'] = $_getQuestionClass;
    $coreReplacements['QUESTION_CODE'] = $_question_code;
    $coreReplacements['QUESTION_ESSENTIALS'] = $_question_essentials;
    $coreReplacements['QUESTION_FILE_VALID_MESSAGE'] = $_question_file_valid_message;
    $coreReplacements['QUESTION_HELP'] = $_question_help;
    $coreReplacements['QUESTION_INPUT_ERROR_CLASS'] = $_question_input_error_class;
    $coreReplacements['QUESTION_MANDATORY'] = $_question_mandatory;
    $coreReplacements['QUESTION_MAN_CLASS'] = $_question_man_class;
    $coreReplacements['QUESTION_MAN_MESSAGE'] = $_question_man_message;
    $coreReplacements['QUESTION_NUMBER'] = $_question_number;
    $coreReplacements['QUESTION_TEXT'] = $_question_text;
    $coreReplacements['QUESTION_VALID_MESSAGE'] = $_question_valid_message;
    $coreReplacements['REGISTERERROR'] = isset($register_errormsg) ? $register_errormsg : '';
    // global
    $coreReplacements['REGISTERFORM'] = $_registerform;
    $coreReplacements['REGISTERMESSAGE1'] = $clang->gT("You must be registered to complete this survey");
    $coreReplacements['REGISTERMESSAGE2'] = $clang->gT("You may register for this survey if you wish to take part.") . "<br />\n" . $clang->gT("Enter your details below, and an email containing the link to participate in this survey will be sent immediately.");
    $coreReplacements['RESTART'] = $_restart;
    $coreReplacements['RETURNTOSURVEY'] = $_return_to_survey;
    $coreReplacements['SAVE'] = $_saveall;
    $coreReplacements['SAVEALERT'] = $_savealert;
    $coreReplacements['SAVEDID'] = isset($saved_id) ? $saved_id : '';
    // global
    $coreReplacements['SAVEERROR'] = isset($errormsg) ? $errormsg : '';
    // global - same as LOADERROR
    $coreReplacements['SAVEFORM'] = $_saveform;
    $coreReplacements['SAVEHEADING'] = $clang->gT("Save your unfinished survey");
    $coreReplacements['SAVEMESSAGE'] = $clang->gT("Enter a name and password for this survey and click save below.") . "<br />\n" . $clang->gT("Your survey will be saved using that name and password, and can be completed later by logging in with the same name and password.") . "<br /><br />\n" . $clang->gT("If you give an email address, an email containing the details will be sent to you.") . "<br /><br />\n" . $clang->gT("After having clicked the save button you can either close this browser window or continue filling out the survey.");
    $coreReplacements['SGQ'] = $_question_sgq;
    $coreReplacements['SID'] = isset($surveyid) ? $surveyid : (isset($questiondetails['sid']) ? $questiondetails['sid'] : '');
    $coreReplacements['SITENAME'] = isset($sitename) ? $sitename : '';
    // global
    $coreReplacements['SUBMITBUTTON'] = $_submitbutton;
    $coreReplacements['SUBMITCOMPLETE'] = "<strong>" . $clang->gT("Thank you!") . "<br /><br />" . $clang->gT("You have completed answering the questions in this survey.") . "</strong><br /><br />" . $clang->gT("Click on 'Submit' now to complete the process and save your answers.");
    $coreReplacements['SUBMITREVIEW'] = $_strreview;
    $coreReplacements['SURVEYCONTACT'] = $surveycontact;
    $coreReplacements['SURVEYDESCRIPTION'] = isset($thissurvey['description']) ? $thissurvey['description'] : '';
    $coreReplacements['SURVEYFORMAT'] = isset($surveyformat) ? $surveyformat : '';
    // global
    $coreReplacements['SURVEYLANGAGE'] = $clang->langcode;
    $coreReplacements['SURVEYLANGUAGE'] = $clang->langcode;
    $coreReplacements['SURVEYLIST'] = isset($surveylist) ? $surveylist['list'] : '';
    $coreReplacements['SURVEYLISTHEADING'] = isset($surveylist) ? $surveylist['listheading'] : '';
    $coreReplacements['SURVEYNAME'] = isset($thissurvey['name']) ? $thissurvey['name'] : '';
    $coreReplacements['TEMPLATECSS'] = $_templatecss;
    $coreReplacements['TEMPLATEJS'] = $_templatejs;
    $coreReplacements['TEMPLATEURL'] = $templateurl;
    $coreReplacements['THEREAREXQUESTIONS'] = $_therearexquestions;
    if (!$anonymized) {
        $coreReplacements['TOKEN'] = $_token;
    }
    $coreReplacements['URL'] = $_linkreplace;
    $coreReplacements['WELCOME'] = isset($thissurvey['welcome']) ? $thissurvey['welcome'] : '';
    if (!is_null($replacements) && is_array($replacements)) {
        $doTheseReplacements = array_merge($coreReplacements, $replacements);
        // so $replacements overrides core values
    } else {
        $doTheseReplacements = $coreReplacements;
    }
    // Now do all of the replacements - In rare cases, need to do 3 deep recursion, that that is default
    $line = LimeExpressionManager::ProcessString($line, $questionNum, $doTheseReplacements, false, 3, 1);
    return $line;
}
Ejemplo n.º 17
0
function makelanguagechanger()
{
    global $relativeurl;
    if (!isset($surveyid)) {
        $surveyid = returnglobal('sid');
    }
    if (isset($surveyid)) {
        $slangs = GetAdditionalLanguagesFromSurveyID($surveyid);
        $sBaseLanguage = GetBaseLanguageFromSurveyID($surveyid);
    }
    // TODO - When is this needed?
    $token = sanitize_token(returnglobal('token'));
    if ($token != '') {
        $tokenparam = "&token={$token}";
    } else {
        $tokenparam = "";
    }
    $previewgrp = false;
    if (isset($_REQUEST['action'])) {
        if ($_REQUEST['action'] == 'previewgroup') {
            $previewgrp = true;
        }
    }
    if (!empty($slangs)) {
        if (isset($_SESSION['s_lang']) && $_SESSION['s_lang'] != '') {
            $lang = sanitize_languagecode($_SESSION['s_lang']);
        } else {
            if (isset($_POST['lang']) && $_POST['lang'] != '') {
                $lang = sanitize_languagecode($_POST['lang']);
            } else {
                if (isset($_GET['lang']) && $_GET['lang'] != '') {
                    $lang = sanitize_languagecode($_GET['lang']);
                } else {
                    $lang = $sBaseLanguage;
                }
            }
        }
        $slangs[] = $sBaseLanguage;
        $aAllLanguages = getLanguageData();
        $slangs = array_keys(array_intersect_key($aAllLanguages, array_flip($slangs)));
        // Sort languages by their locale name
        // Changed how language changer works so that posts any currently set values.  This also ensures that token (and other) parmeters are also posted.
        //        $htmlcode ="<select name=\"select\" class='languagechanger' onchange=\"javascript:window.location=this.value\">\n";
        $htmlcode = "<select name=\"select\" class='languagechanger' " . " onchange=\"javascript:\$('[name=move]').val('changelang_'+ this.value);\$('#limesurvey').submit();\">\n";
        $sAddToURL = "";
        $sTargetURL = "{$relativeurl}/index.php";
        if ($previewgrp) {
            $sAddToURL = "&amp;action=previewgroup&amp;gid={$_REQUEST['gid']}";
            $sTargetURL = "";
        }
        foreach ($slangs as $otherlang) {
            //            $htmlcode .= "\t<option value=\"$sTargetURL?sid=". $surveyid ."&amp;lang=". $otherlang ."$tokenparam$sAddToURL\" ";
            $htmlcode .= "\t<option value=\"" . $otherlang . "\" ";
            if ($otherlang == $lang) {
                $htmlcode .= " selected=\"selected\" ";
            }
            $htmlcode .= ">" . $aAllLanguages[$otherlang]['nativedescription'] . "</option>\n";
        }
        $htmlcode .= "</select>\n";
        //    . "</form>";
        return $htmlcode;
    } elseif (!isset($surveyid)) {
        global $defaultlang, $baselang;
        $htmlcode = "<select name=\"select\" class='languagechanger' onchange=\"javascript:window.location=this.value\">\n";
        $htmlcode .= "<option value=\"{$relativeurl}/index.php?lang=" . $defaultlang . "{$tokenparam}\">" . getLanguageNameFromCode($defaultlang, false) . "</option>\n";
        foreach (getlanguagedata() as $key => $val) {
            $htmlcode .= "\t<option value=\"{$relativeurl}/index.php?lang=" . $key . "{$tokenparam}\" ";
            $htmlcode .= ">" . getLanguageNameFromCode($key, false) . "</option>\n";
        }
        $htmlcode .= "</select>\n";
        return $htmlcode;
    }
}