Example #1
2
 /**
  * tokens::bounceprocessing()
  *
  * @return void
  */
 function bounceprocessing($iSurveyId)
 {
     $iSurveyId = sanitize_int($iSurveyId);
     $clang = $this->getController()->lang;
     $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}');
     if (!$bTokenExists) {
         $clang->eT("No token table.");
         return;
     }
     $thissurvey = getSurveyInfo($iSurveyId);
     if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'update')) {
         $clang->eT("We are sorry but you don't have permissions to do this.");
         return;
     }
     if ($thissurvey['bounceprocessing'] != 'N' || $thissurvey['bounceprocessing'] == 'G' && getGlobalSetting('bounceaccounttype') != 'off') {
         if (!function_exists('imap_open')) {
             $clang->eT("The imap PHP library is not installed. Please contact your system administrator.");
             return;
         }
         $bouncetotal = 0;
         $checktotal = 0;
         if ($thissurvey['bounceprocessing'] == 'G') {
             $accounttype = strtoupper(getGlobalSetting('bounceaccounttype'));
             $hostname = getGlobalSetting('bounceaccounthost');
             $username = getGlobalSetting('bounceaccountuser');
             $pass = getGlobalSetting('bounceaccountpass');
             $hostencryption = strtoupper(getGlobalSetting('bounceencryption'));
         } else {
             $accounttype = strtoupper($thissurvey['bounceaccounttype']);
             $hostname = $thissurvey['bounceaccounthost'];
             $username = $thissurvey['bounceaccountuser'];
             $pass = $thissurvey['bounceaccountpass'];
             $hostencryption = strtoupper($thissurvey['bounceaccountencryption']);
         }
         @(list($hostname, $port) = split(':', $hostname));
         if (empty($port)) {
             if ($accounttype == "IMAP") {
                 switch ($hostencryption) {
                     case "OFF":
                         $hostname = $hostname . ":143";
                         break;
                     case "SSL":
                         $hostname = $hostname . ":993";
                         break;
                     case "TLS":
                         $hostname = $hostname . ":993";
                         break;
                 }
             } else {
                 switch ($hostencryption) {
                     case "OFF":
                         $hostname = $hostname . ":110";
                         break;
                     case "SSL":
                         $hostname = $hostname . ":995";
                         break;
                     case "TLS":
                         $hostname = $hostname . ":995";
                         break;
                 }
             }
         } else {
             $hostname = $hostname . ":" . $port;
         }
         $flags = "";
         switch ($accounttype) {
             case "IMAP":
                 $flags .= "/imap";
                 break;
             case "POP":
                 $flags .= "/pop3";
                 break;
         }
         switch ($hostencryption) {
             case "OFF":
                 $flags .= "/notls";
                 // Really Off
                 break;
             case "SSL":
                 $flags .= "/ssl/novalidate-cert";
                 break;
             case "TLS":
                 $flags .= "/tls/novalidate-cert";
                 break;
         }
         if ($mbox = @imap_open('{' . $hostname . $flags . '}INBOX', $username, $pass)) {
             imap_errors();
             $count = imap_num_msg($mbox);
             if ($count > 0) {
                 $lasthinfo = imap_headerinfo($mbox, $count);
                 $datelcu = strtotime($lasthinfo->date);
                 $datelastbounce = $datelcu;
                 $lastbounce = $thissurvey['bouncetime'];
                 while ($datelcu > $lastbounce) {
                     @($header = explode("\r\n", imap_body($mbox, $count, FT_PEEK)));
                     // Don't mark messages as read
                     foreach ($header as $item) {
                         if (preg_match('/^X-surveyid/', $item)) {
                             $iSurveyIdBounce = explode(": ", $item);
                         }
                         if (preg_match('/^X-tokenid/', $item)) {
                             $tokenBounce = explode(": ", $item);
                             if ($iSurveyId == $iSurveyIdBounce[1]) {
                                 $aData = array('emailstatus' => 'bounced');
                                 $condn = array('token' => $tokenBounce[1]);
                                 $record = Token::model($iSurveyId)->findByAttributes($condn);
                                 if ($record->emailstatus != 'bounced') {
                                     $record->emailstatus = 'bounced';
                                     $record->save();
                                     $bouncetotal++;
                                 }
                                 $readbounce = imap_body($mbox, $count);
                                 // Put read
                                 if (isset($thissurvey['bounceremove']) && $thissurvey['bounceremove']) {
                                     $deletebounce = imap_delete($mbox, $count);
                                     // Put delete
                                 }
                             }
                         }
                     }
                     $count--;
                     @($lasthinfo = imap_headerinfo($mbox, $count));
                     @($datelc = $lasthinfo->date);
                     $datelcu = strtotime($datelc);
                     $checktotal++;
                 }
             }
             @imap_close($mbox);
             $condn = array('sid' => $iSurveyId);
             $survey = Survey::model()->findByAttributes($condn);
             $survey->bouncetime = $datelastbounce;
             $survey->save();
             if ($bouncetotal > 0) {
                 printf($clang->gT("%s messages were scanned out of which %s were marked as bounce by the system."), $checktotal, $bouncetotal);
             } else {
                 printf($clang->gT("%s messages were scanned, none were marked as bounce by the system."), $checktotal);
             }
         } else {
             $clang->eT("Please check your settings");
         }
     } else {
         $clang->eT("Bounce processing is deactivated either application-wide or for this survey in particular.");
         return;
     }
     exit;
     // if bounceprocessing : javascript : no more todo
 }
Example #2
0
 private function _displaySettings()
 {
     Yii::app()->loadHelper('surveytranslator');
     //save refurl from where global settings screen is called!
     $refurl = Yii::app()->getRequest()->getUrlReferrer();
     Yii::app()->session['refurl'] = htmlspecialchars($refurl);
     //just to be safe!
     $data['clang'] = $this->getController()->lang;
     $data['title'] = "hi";
     $data['message'] = "message";
     foreach ($this->_checkSettings() as $key => $row) {
         $data[$key] = $row;
     }
     $data['thisupdatecheckperiod'] = getGlobalSetting('updatecheckperiod');
     $data['updatelastcheck'] = Yii::app()->getConfig("updatelastcheck");
     $data['updateavailable'] = Yii::app()->getConfig("updateavailable") && Yii::app()->getConfig("updatable");
     $data['updatable'] = Yii::app()->getConfig("updatable");
     $data['updateinfo'] = Yii::app()->getConfig("updateinfo");
     $data['updatebuild'] = Yii::app()->getConfig("updatebuild");
     $data['updateversion'] = Yii::app()->getConfig("updateversion");
     $data['allLanguages'] = getLanguageData(false, Yii::app()->session['adminlang']);
     if (trim(Yii::app()->getConfig('restrictToLanguages')) == '') {
         $data['restrictToLanguages'] = array_keys($data['allLanguages']);
         $data['excludedLanguages'] = array();
     } else {
         $data['restrictToLanguages'] = explode(' ', trim(Yii::app()->getConfig('restrictToLanguages')));
         $data['excludedLanguages'] = array_diff(array_keys($data['allLanguages']), $data['restrictToLanguages']);
     }
     $this->_renderWrappedTemplate('', 'globalSettings_view', $data);
 }
Example #3
0
 public function run()
 {
     App()->loadHelper('surveytranslator');
     $aData['issuperadmin'] = false;
     if (Permission::model()->hasGlobalPermission('superadmin', 'read')) {
         $aData['issuperadmin'] = true;
     }
     // We get the last survey visited by user
     $setting_entry = 'last_survey_' . Yii::app()->user->getId();
     $lastsurvey = getGlobalSetting($setting_entry);
     $survey = Survey::model()->findByPk($lastsurvey);
     if ($lastsurvey != null && $survey) {
         $aData['showLastSurvey'] = true;
         $iSurveyID = $lastsurvey;
         $surveyinfo = $survey->surveyinfo;
         $aData['surveyTitle'] = $surveyinfo['surveyls_title'] . "(" . gT("ID") . ":" . $iSurveyID . ")";
         $aData['surveyUrl'] = $this->getController()->createUrl("admin/survey/sa/view/surveyid/{$iSurveyID}");
     } else {
         $aData['showLastSurvey'] = false;
     }
     // We get the last question visited by user
     $setting_entry = 'last_question_' . Yii::app()->user->getId();
     $lastquestion = getGlobalSetting($setting_entry);
     // the question group of this question
     $setting_entry = 'last_question_gid_' . Yii::app()->user->getId();
     $lastquestiongroup = getGlobalSetting($setting_entry);
     // the sid of this question : last_question_sid_1
     $setting_entry = 'last_question_sid_' . Yii::app()->user->getId();
     $lastquestionsid = getGlobalSetting($setting_entry);
     $survey = Survey::model()->findByPk($lastquestionsid);
     if ($lastquestion && $lastquestiongroup && $survey) {
         $baselang = $survey->language;
         $aData['showLastQuestion'] = true;
         $qid = $lastquestion;
         $gid = $lastquestiongroup;
         $sid = $lastquestionsid;
         $qrrow = Question::model()->findByAttributes(array('qid' => $qid, 'gid' => $gid, 'sid' => $sid, 'language' => $baselang));
         if ($qrrow) {
             $aData['last_question_name'] = $qrrow['title'];
             if ($qrrow['question']) {
                 $aData['last_question_name'] .= ' : ' . $qrrow['question'];
             }
             $aData['last_question_link'] = $this->getController()->createUrl("admin/questions/sa/view/surveyid/{$sid}/gid/{$gid}/qid/{$qid}");
         } else {
             $aData['showLastQuestion'] = false;
         }
     } else {
         $aData['showLastQuestion'] = false;
     }
     $aData['countSurveyList'] = count(getSurveyList(true));
     // We get the home page display setting
     $aData['bShowSurveyList'] = getGlobalSetting('show_survey_list') == "show";
     $aData['bShowSurveyListSearch'] = getGlobalSetting('show_survey_list_search') == "show";
     $aData['bShowLogo'] = getGlobalSetting('show_logo') == "show";
     $aData['oSurveySearch'] = new Survey('search');
     $aData['bShowLastSurveyAndQuestion'] = getGlobalSetting('show_last_survey_and_question') == "show";
     $aData['iBoxesByRow'] = (int) getGlobalSetting('boxes_by_row');
     $aData['sBoxesOffSet'] = (string) getGlobalSetting('boxes_offset');
     $this->_renderWrappedTemplate('super', 'welcome', $aData);
 }
Example #4
0
/**
* setNoAnswerMode
*/
function setNoAnswerMode($thissurvey)
{
    if (getGlobalSetting('shownoanswer') > 0 && $thissurvey['shownoanswer'] != 'N') {
        define('SHOW_NO_ANSWER', 1);
    } else {
        define('SHOW_NO_ANSWER', 0);
    }
}
Example #5
0
 /**
  * Set the Admin Theme :
  * - checks if the required template exists
  * - set the admin theme variables
  * - set the admin theme constants
  * - Register all the needed CSS/JS files
  */
 public function setAdminTheme()
 {
     $sAdminThemeName = getGlobalSetting('admintheme');
     // We retrieve the admin theme in config ( {{settings_global}} or config-defaults.php )
     $sStandardTemplateRootDir = Yii::app()->getConfig("styledir");
     // Path for the standard Admin Themes
     $sUserTemplateDir = Yii::app()->getConfig('uploaddir') . DIRECTORY_SEPARATOR . 'admintheme';
     // Path for the user Admin Themes
     // Check if the required theme is a standard one
     if ($this->isStandardAdminTheme($sAdminThemeName)) {
         $sTemplateDir = $sStandardTemplateRootDir;
         // It's standard, so it will be in standard path
         $sTemplateUrl = Yii::app()->getConfig('styleurl') . $sAdminThemeName;
         // Available via a standard URL
     } else {
         // If it's not a standard theme, we bet it's a user one.
         // In fact, it could also be a old 2.06 admin theme just aftet an update (it will then be caught as "non existent" in the next if statement")
         $sTemplateDir = $sUserTemplateDir;
         $sTemplateUrl = Yii::app()->getConfig('uploadurl') . DIRECTORY_SEPARATOR . 'admintheme' . DIRECTORY_SEPARATOR . $sAdminThemeName;
     }
     // If the theme directory doesn't exist, it can be that:
     // - user updated from 2.06 and still have old theme configurated in database
     // - user deleted a custom theme
     // In any case, we just set Sea Green as the template to use
     if (!is_dir($sTemplateDir . DIRECTORY_SEPARATOR . $sAdminThemeName)) {
         $sAdminThemeName = 'Sea_Green';
         $sTemplateDir = $sStandardTemplateRootDir;
         $sTemplateUrl = Yii::app()->getConfig('styleurl') . DIRECTORY_SEPARATOR . $sAdminThemeName;
         setGlobalSetting('admintheme', 'Sea_Green');
     }
     // Now that we are sure we have an existing template, we can set the variables of the AdminTheme
     $this->sTemplateUrl = $sTemplateUrl;
     $this->name = $sAdminThemeName;
     $this->path = $sTemplateDir . DIRECTORY_SEPARATOR . $this->name;
     // This is necessary because a lot of files still use "adminstyleurl".
     // TODO: replace everywhere the call to Yii::app()->getConfig('adminstyleurl) by $oAdminTheme->sTemplateUrl;
     Yii::app()->setConfig('adminstyleurl', $this->sTemplateUrl);
     //////////////////////
     // Config file loading
     $bOldEntityLoaderState = libxml_disable_entity_loader(true);
     // @see: http://phpsecurity.readthedocs.io/en/latest/Injection-Attacks.html#xml-external-entity-injection
     $sXMLConfigFile = file_get_contents(realpath($this->path . '/config.xml'));
     // Now that entity loader is disabled, we can't use simplexml_load_file; so we must read the file with file_get_contents and convert it as a string
     // Simple Xml is buggy on PHP < 5.4. The [ array -> json_encode -> json_decode ] workaround seems to be the most used one.
     // @see: http://php.net/manual/de/book.simplexml.php#105330 (top comment on PHP doc for simplexml)
     $this->config = json_decode(json_encode((array) simplexml_load_string($sXMLConfigFile), 1));
     // If developers want to test asset manager with debug mode on
     self::$use_asset_manager = isset($this->config->engine->use_asset_manager_in_debug_mode) ? $this->config->engine->use_asset_manager_in_debug_mode == 'true' : 'false';
     $this->defineConstants();
     // Define the (still) necessary constants
     $this->registerStylesAndScripts();
     // Register all CSS and JS
     libxml_disable_entity_loader($bOldEntityLoaderState);
     // Put back entity loader to its original state, to avoid contagion to other applications on the server
     return $this;
 }
Example #6
0
 /**
  * First call to the server : This function requests the latest update informations from the update server necessary to build the update buttons.
  * If any error occured (server not answering, no curl, servor returns error, etc.), the view check_updates/update_buttons/_updatesavailable_error will be rendered by the controller.
  *
  * @param boolean $crosscheck if it checks for info for both stable and unstable branches
  * @return array Contains update information or error object
  */
 public function getUpdateInfo($crosscheck = "1")
 {
     if ($this->build != '') {
         $crosscheck = (int) $crosscheck;
         $getters = '/index.php?r=updates/updateinfo&currentbuild=' . $this->build . '&id=' . md5(getGlobalSetting('SessionName')) . '&crosscheck=' . $crosscheck;
         $content = $this->_performRequest($getters);
     } else {
         $content = new stdClass();
         $content->result = FALSE;
         $content->error = "no_build";
     }
     return $content;
 }
Example #7
0
 public function run()
 {
     App()->loadHelper('surveytranslator');
     App()->getClientScript()->registerPackage('panel-clickable');
     App()->getClientScript()->registerPackage('panels-animation');
     $aData['issuperadmin'] = false;
     if (Permission::model()->hasGlobalPermission('superadmin', 'read')) {
         $aData['issuperadmin'] = true;
     }
     // We get the last survey visited by user
     $setting_entry = 'last_survey_' . Yii::app()->user->getId();
     $lastsurvey = getGlobalSetting($setting_entry);
     if ($lastsurvey != null) {
         $aData['showLastSurvey'] = true;
         $iSurveyID = $lastsurvey;
         $surveyinfo = Survey::model()->findByPk($iSurveyID)->surveyinfo;
         $aData['surveyTitle'] = $surveyinfo['surveyls_title'] . "(" . gT("ID") . ":" . $iSurveyID . ")";
         $aData['surveyUrl'] = $this->getController()->createUrl("admin/survey/sa/view/surveyid/{$iSurveyID}");
     } else {
         $aData['showLastSurvey'] = false;
     }
     // We get the last question visited by user
     $setting_entry = 'last_question_' . Yii::app()->user->getId();
     $lastquestion = getGlobalSetting($setting_entry);
     // the question group of this question
     $setting_entry = 'last_question_gid_' . Yii::app()->user->getId();
     $lastquestiongroup = getGlobalSetting($setting_entry);
     // the sid of this question : last_question_sid_1
     $setting_entry = 'last_question_sid_' . Yii::app()->user->getId();
     $lastquestionsid = getGlobalSetting($setting_entry);
     if ($lastquestion != null && $lastquestiongroup != null) {
         $baselang = Survey::model()->findByPk($iSurveyID)->language;
         $aData['showLastQuestion'] = true;
         $qid = $lastquestion;
         $gid = $lastquestiongroup;
         $sid = $lastquestionsid;
         $qrrow = Question::model()->findByAttributes(array('qid' => $qid, 'gid' => $gid, 'sid' => $sid, 'language' => $baselang));
         $aData['last_question_name'] = $qrrow['title'];
         if ($qrrow['question']) {
             $aData['last_question_name'] .= ' : ' . $qrrow['question'];
         }
         $aData['last_question_link'] = $this->getController()->createUrl("admin/questions/sa/view/surveyid/{$iSurveyID}/gid/{$gid}/qid/{$qid}");
     } else {
         $aData['showLastQuestion'] = false;
     }
     $aData['countSurveyList'] = count(getSurveyList(true));
     $this->_renderWrappedTemplate('super', 'welcome', $aData);
 }
Example #8
0
 /**
  * Helper function to let a plugin put content
  * into the side-body easily.
  * 
  * @param int $surveyId
  * @param string $plugin Name of the plugin class
  * @param string $method Name of the plugin method
  * @return void
  */
 public function sidebody($surveyId, $plugin, $method)
 {
     $aData = array();
     $surveyId = sanitize_int($surveyId);
     $surveyinfo = getSurveyInfo($surveyId);
     $aData['surveyid'] = $surveyId;
     $aData['surveybar']['buttons']['view'] = true;
     $aData['title_bar']['title'] = $surveyinfo['surveyls_title'] . "(" . gT("ID") . ":" . $surveyId . ")";
     $content = $this->getContent($surveyId, $plugin, $method);
     $aData['sidemenu'] = array();
     $aData['sidemenu']['state'] = false;
     $aData['sideMenuBehaviour'] = getGlobalSetting('sideMenuBehaviour');
     $aData['content'] = $content;
     $aData['activated'] = $surveyinfo['active'];
     $this->_renderWrappedTemplate(null, array('super/sidebody'), $aData);
 }
Example #9
0
 /**
  * Set the Admin Theme :
  * - checks if the required template exists
  * - set the admin theme variables
  * - set the admin theme constants
  * - Register all the needed CSS/JS files
  */
 public function setAdminTheme()
 {
     $sAdminThemeName = getGlobalSetting('admintheme');
     // We retrieve the admin theme in config ( {{settings_global}} or config-defaults.php )
     $sStandardTemplateRootDir = Yii::app()->getConfig("styledir");
     // Path for the standard Admin Themes
     $sUserTemplateDir = Yii::app()->getConfig('uploaddir') . DIRECTORY_SEPARATOR . 'admintheme';
     // Path for the user Admin Themes
     // Check if the required theme is a standard one
     if ($this->isStandardAdminTheme($sAdminThemeName)) {
         $sTemplateDir = $sStandardTemplateRootDir;
         // It's standard, so it will be in standard path
         $sTemplateUrl = Yii::app()->getConfig('styleurl') . $sAdminThemeName;
         // Available via a standard URL
     } else {
         // If it's not a standard theme, we bet it's a user one.
         // In fact, it could also be a old 2.06 admin theme just aftet an update (it will then be caught as "non existent" in the next if statement")
         $sTemplateDir = $sUserTemplateDir;
         $sTemplateUrl = Yii::app()->getConfig('uploadurl') . DIRECTORY_SEPARATOR . 'admintheme' . DIRECTORY_SEPARATOR . $sAdminThemeName;
     }
     // If the theme directory doesn't exist, it can be that:
     // - user updated from 2.06 and still have old theme configurated in database
     // - user deleted a custom theme
     // In any case, we just set Sea Green as the template to use
     if (!is_dir($sTemplateDir . DIRECTORY_SEPARATOR . $sAdminThemeName)) {
         $sAdminThemeName = 'Sea_Green';
         $sTemplateDir = $sStandardTemplateRootDir;
         $sTemplateUrl = Yii::app()->getConfig('styleurl') . DIRECTORY_SEPARATOR . $sAdminThemeName;
         setGlobalSetting('admintheme', 'Sea_Green');
     }
     // Now that we are sure we have an existing template, we can set the variables of the AdminTheme
     $this->sTemplateUrl = $sTemplateUrl;
     $this->name = $sAdminThemeName;
     $this->path = $sTemplateDir . DIRECTORY_SEPARATOR . $this->name;
     // This is necessary because a lot of files still use "adminstyleurl".
     // TODO: replace everywhere the call to Yii::app()->getConfig('adminstyleurl) by $oAdminTheme->sTemplateUrl;
     Yii::app()->setConfig('adminstyleurl', $this->sTemplateUrl);
     // We load the admin theme's configuration file.
     $this->config = simplexml_load_file($this->path . '/config.xml');
     // If developers want to test asset manager with debug mode on
     $this->use_asset_manager = $this->config->engine->use_asset_manager_in_debug_mode == 'true';
     $this->defineConstants();
     // Define the (still) necessary constants
     $this->registerStylesAndScripts();
     // Register all CSS and JS
     return $this;
 }
 private function _displaySettings()
 {
     Yii::app()->loadHelper('surveytranslator');
     // Save refurl from where global settings screen is called!
     // Unless it's called from global settings...
     $refurl = Yii::app()->getRequest()->getUrlReferrer();
     // Some URLs are not to be allowed to refered back to.
     // These exceptions can be added to the $aReplacements array
     $aReplacements = array('admin/update/sa/step4b' => 'admin/sa/index', 'admin/user/sa/adduser' => 'admin/user/sa/index', 'admin/user/sa/setusertemplates' => 'admin/user/sa/index');
     $refurl = str_replace(array_keys($aReplacements), array_values($aReplacements), $refurl);
     // Don't update session variable if refurl is empty (happens when user clicks Save)
     if ($refurl !== "") {
         Yii::app()->session['refurl'] = htmlspecialchars($refurl);
         //just to be safe!
     }
     $data['title'] = "hi";
     $data['message'] = "message";
     foreach ($this->_checkSettings() as $key => $row) {
         $data[$key] = $row;
     }
     Yii::app()->loadLibrary('Date_Time_Converter');
     $dateformatdetails = getDateFormatData(Yii::app()->session['dateformat']);
     $datetimeobj = new date_time_converter(dateShift(getGlobalSetting("updatelastcheck"), 'Y-m-d H:i:s', getGlobalSetting('timeadjust')), 'Y-m-d H:i:s');
     $data['updatelastcheck'] = $datetimeobj->convert($dateformatdetails['phpdate'] . " H:i:s");
     $data['updateavailable'] = getGlobalSetting("updateavailable") && Yii::app()->getConfig("updatable");
     $data['updatable'] = Yii::app()->getConfig("updatable");
     $data['updateinfo'] = getGlobalSetting("updateinfo");
     $data['updatebuild'] = getGlobalSetting("updatebuild");
     $data['updateversion'] = getGlobalSetting("updateversion");
     $data['aUpdateVersions'] = json_decode(getGlobalSetting("updateversions"), true);
     $data['allLanguages'] = getLanguageData(false, Yii::app()->session['adminlang']);
     if (trim(Yii::app()->getConfig('restrictToLanguages')) == '') {
         $data['restrictToLanguages'] = array_keys($data['allLanguages']);
         $data['excludedLanguages'] = array();
     } else {
         $data['restrictToLanguages'] = explode(' ', trim(Yii::app()->getConfig('restrictToLanguages')));
         $data['excludedLanguages'] = array_diff(array_keys($data['allLanguages']), $data['restrictToLanguages']);
     }
     $data['fullpagebar']['savebutton']['form'] = 'frmglobalsettings';
     $data['fullpagebar']['saveandclosebutton']['form'] = 'frmglobalsettings';
     $data['fullpagebar']['closebutton']['url'] = 'admin/';
     $this->_renderWrappedTemplate('', 'globalSettings_view', $data);
 }
 public function DoLogin()
 {
     $clang = $this->getController()->lang;
     $user = $_POST['email'];
     $pass = $_POST['password'];
     //$spass = hash('sha256', $pass);
     $spwd = urlencode(base64_encode($pass));
     $sql = "SELECT * FROM {{view_panel_list_master}} WHERE email = '{$user}' AND password = '******'";
     $result = Yii::app()->db->createCommand($sql)->query();
     $count = $result->rowCount;
     if ($count > 0) {
         $sresult = $result->readAll();
         if ($sresult[0]['status'] == 'E') {
             Yii::app()->session['plid'] = $sresult[0]['panel_list_id'];
             Yii::app()->session['plname'] = $sresult[0]['full_name'];
             Yii::app()->session['plemail'] = $sresult[0]['email'];
             Yii::app()->session['pluser'] = $sresult[0]['first_name'];
             Yii::app()->session['session_hash'] = hash('sha256', getGlobalSetting('SessionName') . $sresult[0]['first_name'] . $sresult[0]['panel_list_id']);
             $this->_doRedirect();
         } elseif ($sresult[0]['status'] == 'C') {
             $message = $clang->gT('Your Account Is canceled');
             $message .= '<br/>';
             $message .= $clang->gT('Please contact support');
             App()->user->setFlash('loginError', $message);
             $this->getController()->redirect(array('/pl/authentication/sa/login'));
         } elseif ($sresult[0]['status'] == 'D') {
             $message = $clang->gT('Your Account Is Disable By Administrator');
             App()->user->setFlash('loginError', $message);
             $this->getController()->redirect(array('/pl/authentication/sa/login'));
         } else {
             $aData['Pending'] = true;
             $aData['success'] = false;
             $aData['panellist_id'] = $sresult[0]['panel_list_id'];
             $this->_renderWrappedTemplate('', 'view_registration', $aData);
         }
     } else {
         $message = $clang->gT('Incorrect username and/or password!');
         App()->user->setFlash('loginError', $message);
         $this->getController()->redirect(array('/pl/authentication/sa/login'));
     }
 }
 private function _displaySettings()
 {
     Yii::app()->loadHelper('surveytranslator');
     //save refurl from where global settings screen is called!
     $refurl = Yii::app()->getRequest()->getUrlReferrer();
     // Some URLs are not to be allowed to refered back to.
     // These exceptions can be added to the $aReplacements array
     $aReplacements = array('admin/user/adduser' => 'admin/user/index', 'admin/user/sa/adduser' => 'admin/user/sa/index', 'admin/user/sa/setusertemplates' => 'admin/user/sa/index', 'admin/user/setusertemplates' => 'admin/user/sa/index');
     $refurl = str_replace(array_keys($aReplacements), array_values($aReplacements), $refurl);
     Yii::app()->session['refurl'] = htmlspecialchars($refurl);
     //just to be safe!
     $data['clang'] = $this->getController()->lang;
     $data['title'] = "hi";
     $data['message'] = "message";
     foreach ($this->_checkSettings() as $key => $row) {
         $data[$key] = $row;
     }
     $data['thisupdatecheckperiod'] = getGlobalSetting('updatecheckperiod');
     Yii::app()->loadLibrary('Date_Time_Converter');
     $dateformatdetails = getDateFormatData(Yii::app()->session['dateformat']);
     $datetimeobj = new date_time_converter(getGlobalSetting("updatelastcheck"), 'Y-m-d H:i:s');
     $data['updatelastcheck'] = $datetimeobj->convert($dateformatdetails['phpdate'] . " H:i:s");
     $data['updateavailable'] = getGlobalSetting("updateavailable") && Yii::app()->getConfig("updatable");
     $data['updatable'] = Yii::app()->getConfig("updatable");
     $data['updateinfo'] = getGlobalSetting("updateinfo");
     $data['updatebuild'] = getGlobalSetting("updatebuild");
     $data['updateversion'] = getGlobalSetting("updateversion");
     $data['allLanguages'] = getLanguageData(false, Yii::app()->session['adminlang']);
     if (trim(Yii::app()->getConfig('restrictToLanguages')) == '') {
         $data['restrictToLanguages'] = array_keys($data['allLanguages']);
         $data['excludedLanguages'] = array();
     } else {
         $data['restrictToLanguages'] = explode(' ', trim(Yii::app()->getConfig('restrictToLanguages')));
         $data['excludedLanguages'] = array_diff(array_keys($data['allLanguages']), $data['restrictToLanguages']);
     }
     $this->_renderWrappedTemplate('', 'globalSettings_view', $data);
 }
/**
* 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;
}
/**
* 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;
}
Example #15
0
 public function dumplabel()
 {
     $lid = sanitize_int(Yii::app()->request->getParam('lid'));
     // DUMP THE RELATED DATA FOR A SINGLE QUESTION INTO A SQL FILE FOR IMPORTING LATER ON OR
     // ON ANOTHER SURVEY SETUP DUMP ALL DATA WITH RELATED QID FROM THE FOLLOWING TABLES
     // 1. questions
     // 2. answers
     $lids = returnGlobal('lids');
     if (!$lid && !$lids) {
         die('No LID has been provided. Cannot dump label set.');
     }
     if ($lid) {
         $lids = array($lid);
     }
     $lids = array_map('sanitize_int', $lids);
     $fn = "limesurvey_labelset_" . implode('_', $lids) . ".lsl";
     $xml = getXMLWriter();
     $this->_addHeaders($fn, "text/html/force-download", "Mon, 26 Jul 1997 05:00:00 GMT", "cache");
     $xml->openURI('php://output');
     $xml->setIndent(TRUE);
     $xml->startDocument('1.0', 'UTF-8');
     $xml->startElement('document');
     $xml->writeElement('LimeSurveyDocType', 'Label set');
     $xml->writeElement('DBVersion', getGlobalSetting("DBVersion"));
     // Label sets table
     $lsquery = "SELECT * FROM {{labelsets}} WHERE lid=" . implode(' or lid=', $lids);
     buildXMLFromQuery($xml, $lsquery, 'labelsets');
     // Labels
     $lquery = "SELECT lid, code, title, sortorder, language, assessment_value FROM {{labels}} WHERE lid=" . implode(' or lid=', $lids);
     buildXMLFromQuery($xml, $lquery, 'labels');
     $xml->endElement();
     // close columns
     $xml->endDocument();
     exit;
 }
/**
* enforceSSLMode() $force_ssl is on or off, it checks if the current
* request is to HTTPS (or not). If $force_ssl is on, and the
* request is not to HTTPS, it redirects the request to the HTTPS
* version of the URL, if the request is to HTTPS, it rewrites all
* the URL variables so they also point to HTTPS.
*/
function enforceSSLMode()
{
    $bSSLActive = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != "off" || isset($_SERVER['HTTP_FORWARDED_PROTO']) && $_SERVER['HTTP_FORWARDED_PROTO'] == "https" || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == "https";
    if (Yii::app()->getConfig('ssl_emergency_override') !== true) {
        $force_ssl = strtolower(getGlobalSetting('force_ssl'));
    } else {
        $force_ssl = 'off';
    }
    if ($force_ssl == 'on' && !$bSSLActive) {
        SSLRedirect('s');
    }
    if ($force_ssl == 'off' && $bSSLActive) {
        SSLRedirect('');
    }
}
Example #17
0
function do_shortfreetext($ia)
{
    global $thissurvey;
    $sGoogleMapsAPIKey = trim(Yii::app()->getConfig("googleMapsAPIKey"));
    if ($sGoogleMapsAPIKey != '') {
        $sGoogleMapsAPIKey = '&key=' . $sGoogleMapsAPIKey;
    }
    $extraclass = "";
    $aQuestionAttributes = getQuestionAttributeValues($ia[0]);
    if ($aQuestionAttributes['numbers_only'] == 1) {
        $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']);
        $sSeparator = $sSeparator['separator'];
        $extraclass .= " numberonly";
        $checkconditionFunction = "fixnum_checkconditions";
    } else {
        $checkconditionFunction = "checkconditions";
    }
    if (intval(trim($aQuestionAttributes['maximum_chars'])) > 0) {
        // Only maxlength attribute, use textarea[maxlength] jquery selector for textarea
        $maximum_chars = intval(trim($aQuestionAttributes['maximum_chars']));
        $maxlength = "maxlength='{$maximum_chars}' ";
        $extraclass .= " maxchars maxchars-" . $maximum_chars;
    } else {
        $maxlength = "";
    }
    if (trim($aQuestionAttributes['text_input_width']) != '') {
        $tiwidth = $aQuestionAttributes['text_input_width'];
        $extraclass .= " inputwidth-" . trim($aQuestionAttributes['text_input_width']);
    } else {
        $tiwidth = 50;
    }
    if (trim($aQuestionAttributes['prefix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') {
        $prefix = $aQuestionAttributes['prefix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']];
        $extraclass .= " withprefix";
    } else {
        $prefix = '';
    }
    if (trim($aQuestionAttributes['suffix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') {
        $suffix = $aQuestionAttributes['suffix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']];
        $extraclass .= " withsuffix";
    } else {
        $suffix = '';
    }
    if ($thissurvey['nokeyboard'] == 'Y') {
        includeKeypad();
        $kpclass = "text-keypad";
        $extraclass .= " inputkeypad";
    } else {
        $kpclass = "";
    }
    if (trim($aQuestionAttributes['display_rows']) != '') {
        //question attribute "display_rows" is set -> we need a textarea to be able to show several rows
        $drows = $aQuestionAttributes['display_rows'];
        //if a textarea should be displayed we make it equal width to the long text question
        //this looks nicer and more continuous
        if ($tiwidth == 50) {
            $tiwidth = 40;
        }
        //NEW: textarea instead of input=text field
        // --> START NEW FEATURE - SAVE
        $answer = "<p class='question answer-item text-item {$extraclass}'><label for='answer{$ia[1]}' class='hide label'>" . gT('Your answer') . "</label>" . '<textarea class="textarea ' . $kpclass . '" name="' . $ia[1] . '" id="answer' . $ia[1] . '" ' . 'rows="' . $drows . '" cols="' . $tiwidth . '" ' . $maxlength . ' onkeyup="' . $checkconditionFunction . '(this.value, this.name, this.type);">';
        // --> END NEW FEATURE - SAVE
        if ($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]) {
            $dispVal = str_replace("\\", "", $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]);
            if ($aQuestionAttributes['numbers_only'] == 1) {
                $dispVal = str_replace('.', $sSeparator, $dispVal);
            }
            $answer .= $dispVal;
        }
        $answer .= "</textarea></p>\n";
    } elseif ((int) $aQuestionAttributes['location_mapservice'] == 1) {
        $mapservice = $aQuestionAttributes['location_mapservice'];
        $currentLocation = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]];
        $currentLatLong = null;
        $floatLat = 0;
        $floatLng = 0;
        // Get the latitude/longtitude for the point that needs to be displayed by default
        if (strlen($currentLocation) > 2) {
            $currentLatLong = explode(';', $currentLocation);
            $currentLatLong = array($currentLatLong[0], $currentLatLong[1]);
        } else {
            if ((int) $aQuestionAttributes['location_nodefaultfromip'] == 0) {
                $currentLatLong = getLatLongFromIp(getIPAddress());
            }
            if (!isset($currentLatLong) || $currentLatLong == false) {
                $floatLat = 0;
                $floatLng = 0;
                $LatLong = explode(" ", trim($aQuestionAttributes['location_defaultcoordinates']));
                if (isset($LatLong[0]) && isset($LatLong[1])) {
                    $floatLat = $LatLong[0];
                    $floatLng = $LatLong[1];
                }
                $currentLatLong = array($floatLat, $floatLng);
            }
        }
        // 2 - city; 3 - state; 4 - country; 5 - postal
        $strBuild = "";
        if ($aQuestionAttributes['location_city']) {
            $strBuild .= "2";
        }
        if ($aQuestionAttributes['location_state']) {
            $strBuild .= "3";
        }
        if ($aQuestionAttributes['location_country']) {
            $strBuild .= "4";
        }
        if ($aQuestionAttributes['location_postal']) {
            $strBuild .= "5";
        }
        $currentLocation = $currentLatLong[0] . " " . $currentLatLong[1];
        $answer = "\n        <script type=\"text/javascript\">\n        zoom['{$ia['1']}'] = {$aQuestionAttributes['location_mapzoom']};\n        </script>\n\n        <div class=\"question answer-item geoloc-item {$extraclass}\">\n        <input type=\"hidden\" name=\"{$ia['1']}\" id=\"answer{$ia['1']}\" value=\"{$_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]}\">\n\n        <input class=\"text location " . $kpclass . "\" type=\"text\" size=\"20\" name=\"{$ia['1']}_c\"\n        id=\"answer{$ia['1']}_c\" value=\"{$currentLocation}\"\n        onchange=\"{$checkconditionFunction}(this.value, this.name, this.type)\" />\n\n        <input type=\"hidden\" name=\"boycott_{$ia['1']}\" id=\"boycott_{$ia['1']}\"\n        value = \"{$strBuild}\" >\n\n        <input type=\"hidden\" name=\"mapservice_{$ia['1']}\" id=\"mapservice_{$ia['1']}\"\n        class=\"mapservice\" value = \"{$aQuestionAttributes['location_mapservice']}\" >\n        <div id=\"gmap_canvas_{$ia['1']}_c\" style=\"width: {$aQuestionAttributes['location_mapwidth']}px; height: {$aQuestionAttributes['location_mapheight']}px\"></div>\n        </div>";
        Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "map.js");
        if ($aQuestionAttributes['location_mapservice'] == 1 && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != "off") {
            Yii::app()->getClientScript()->registerScriptFile("https://maps.googleapis.com/maps/api/js?sensor=false{$sGoogleMapsAPIKey}");
        } else {
            if ($aQuestionAttributes['location_mapservice'] == 1) {
                Yii::app()->getClientScript()->registerScriptFile("http://maps.googleapis.com/maps/api/js?sensor=false{$sGoogleMapsAPIKey}");
            } elseif ($aQuestionAttributes['location_mapservice'] == 2) {
                Yii::app()->getClientScript()->registerScriptFile("http://www.openlayers.org/api/OpenLayers.js");
            }
        }
        if (isset($aQuestionAttributes['hide_tip']) && $aQuestionAttributes['hide_tip'] == 0) {
            $answer .= "<div class=\"questionhelp\">" . gT('Drag and drop the pin to the desired location. You may also right click on the map to move the pin.') . '</div>';
            $question_text['help'] = gT('Drag and drop the pin to the desired location. You may also right click on the map to move the pin.');
        }
    } elseif ((int) $aQuestionAttributes['location_mapservice'] == 100) {
        $currentLocation = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]];
        $currentCenter = $currentLatLong = null;
        // Get the latitude/longtitude for the point that needs to be displayed by default
        if (strlen($currentLocation) > 2 && strpos($currentLocation, ";")) {
            $currentLatLong = explode(';', $currentLocation);
            $currentCenter = $currentLatLong = array($currentLatLong[0], $currentLatLong[1]);
        } elseif ((int) $aQuestionAttributes['location_nodefaultfromip'] == 0) {
            $currentCenter = $currentLatLong = getLatLongFromIp(getIPAddress());
        }
        // If it's not set : set the center to the default position, but don't set the marker
        if (!$currentLatLong) {
            $currentLatLong = array("", "");
            $currentCenter = explode(" ", trim($aQuestionAttributes['location_defaultcoordinates']));
            if (count($currentCenter) != 2) {
                $currentCenter = array("", "");
            }
        }
        // 2 - city; 3 - state; 4 - country; 5 - postal
        // TODO : move it to aThisMapScriptVar and use geoname reverse geocoding (http://www.geonames.org/export/reverse-geocoding.html)
        $strBuild = "";
        /*if ($aQuestionAttributes['location_city'])
              $strBuild .= "2";
          if ($aQuestionAttributes['location_state'])
              $strBuild .= "3";
          if ($aQuestionAttributes['location_country'])
              $strBuild .= "4";
          if ($aQuestionAttributes['location_postal'])
              $strBuild .= "5";*/
        $aGlobalMapScriptVar = array('geonameUser' => getGlobalSetting('GeoNamesUsername'), 'geonameLang' => Yii::app()->language);
        $aThisMapScriptVar = array('zoomLevel' => $aQuestionAttributes['location_mapzoom'], 'latitude' => $currentCenter[0], 'longitude' => $currentCenter[1]);
        App()->getClientScript()->registerPackage('leaflet');
        Yii::app()->getClientScript()->registerScript('sGlobalMapScriptVar', "LSmap=" . ls_json_encode($aGlobalMapScriptVar) . ";\nLSmaps= new Array();", CClientScript::POS_HEAD);
        Yii::app()->getClientScript()->registerScript('sThisMapScriptVar' . $ia[1], "LSmaps['{$ia[1]}']=" . ls_json_encode($aThisMapScriptVar), CClientScript::POS_HEAD);
        Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "map.js");
        Yii::app()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl') . 'map.css');
        $answer = "\n        <div class=\"question answer-item geoloc-item {$extraclass}\">\n            <input type=\"hidden\"  name=\"{$ia['1']}\" id=\"answer{$ia['1']}\" value=\"{$_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]}\"><!-- No javascript need a way to answer -->\n            <input type=\"hidden\" class=\"location\" name=\"{$ia['1']}_c\" id=\"answer{$ia['1']}_c\" value=\"{$currentLatLong[0]} {$currentLatLong[1]}\" />\n\n            <ul class=\"coordinates-list\">\n                <li class=\"coordinate-item\">" . gt("Latitude:") . "<input class=\"coords text\" type=\"text\" name=\"{$ia['1']}_c1\" id=\"answer_lat{$ia['1']}_c\"  value=\"{$currentLatLong[0]}\" /></li>\n                <li class=\"coordinate-item\">" . gt("Longitude:") . "<input class=\"coords text\" type=\"text\" name=\"{$ia['1']}_c2\" id=\"answer_lng{$ia['1']}_c\" value=\"{$currentLatLong[1]}\" /></li>\n            </ul>\n\n            <input type=\"hidden\" name=\"boycott_{$ia['1']}\" id=\"boycott_{$ia['1']}\" value = \"{$strBuild}\" > \n            <input type=\"hidden\" name=\"mapservice_{$ia['1']}\" id=\"mapservice_{$ia['1']}\" class=\"mapservice\" value = \"{$aQuestionAttributes['location_mapservice']}\" >\n\n            <div>\n                <div class=\"geoname_restrict\">\n                    <input type=\"checkbox\" id=\"restrictToExtent_{$ia[1]}\"> <label for=\"restrictToExtent_{$ia[1]}\">" . gt("Restrict search place to map extent") . "</label>\n                </div>\n                <div class=\"geoname_search\" >\n                    <input id=\"searchbox_{$ia[1]}\" placeholder=\"" . gt("Search") . "\" width=\"15\">\n                </div>\n            </div>\n            <div id=\"map_{$ia[1]}\" style=\"width: 100%; height: {$aQuestionAttributes['location_mapheight']}px;\">\n        </div>\n        ";
        if (isset($aQuestionAttributes['hide_tip']) && $aQuestionAttributes['hide_tip'] == 0) {
            $answer .= "<div class=\"questionhelp\">" . gT('Click to set the location or drag and drop the pin. You may may also enter coordinates') . '</div>';
            $question_text['help'] = gT('Click to set the location or drag and drop the pin. You may may also enter coordinates');
        }
    } else {
        //no question attribute set, use common input text field
        $answer = "<p class=\"question answer-item text-item {$extraclass}\">\n" . "<label for='answer{$ia[1]}' class='hide label'>" . gT('Your answer') . "</label>" . "{$prefix}\t<input class=\"text {$kpclass}\" type=\"text\" size=\"{$tiwidth}\" name=\"{$ia['1']}\" id=\"answer{$ia['1']}\"";
        $dispVal = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]];
        if ($aQuestionAttributes['numbers_only'] == 1) {
            $dispVal = str_replace('.', $sSeparator, $dispVal);
        }
        $dispVal = htmlspecialchars($dispVal, ENT_QUOTES, 'UTF-8');
        $answer .= " value=\"{$dispVal}\"";
        $answer .= " {$maxlength} onkeyup=\"{$checkconditionFunction}(this.value, this.name, this.type)\"/>\n\t{$suffix}\n</p>\n";
    }
    if (trim($aQuestionAttributes['time_limit']) != '') {
        $answer .= return_timer_script($aQuestionAttributes, $ia, "answer" . $ia[1]);
    }
    $inputnames[] = $ia[1];
    return array($answer, $inputnames);
}
Example #18
0
 protected function postLogin()
 {
     $user = $this->getUser();
     App()->user->login($this);
     // Check for default password
     if ($this->password === 'password') {
         Yii::app()->setFlashMessage(gT("Warning: You are still using the default password ('password'). Please change your password and re-login again."), 'warning');
     }
     if ((int) App()->request->getPost('width', '1280') < 1280) {
         Yii::app()->setFlashMessage(gT("Your browser screen size is too small to use the administration properly. The minimum size required is 1280*1024 px."), 'error');
     }
     // Do session setup
     Yii::app()->session['loginID'] = (int) $user->uid;
     Yii::app()->session['user'] = $user->users_name;
     Yii::app()->session['full_name'] = $user->full_name;
     Yii::app()->session['htmleditormode'] = $user->htmleditormode;
     Yii::app()->session['templateeditormode'] = $user->templateeditormode;
     Yii::app()->session['questionselectormode'] = $user->questionselectormode;
     Yii::app()->session['dateformat'] = $user->dateformat;
     Yii::app()->session['session_hash'] = hash('sha256', getGlobalSetting('SessionName') . $user->users_name . $user->uid);
     // Perform language settings
     if (App()->request->getPost('loginlang', 'default') != 'default') {
         $user->lang = sanitize_languagecode(App()->request->getPost('loginlang'));
         $user->save();
         $sLanguage = $user->lang;
     } else {
         if ($user->lang == 'auto' || $user->lang == '') {
             $sLanguage = getBrowserLanguage();
         } else {
             $sLanguage = $user->lang;
         }
     }
     Yii::app()->session['adminlang'] = $sLanguage;
     App()->setLanguage($sLanguage);
 }
Example #19
0
eT("URL:");
?>
</label>
    <div class="col-sm-8">
        <?php 
echo $this->createAbsoluteUrl("admin/remotecontrol");
?>
    </div>
</div>

<div class="form-group">
    <label class="col-sm-4 control-label"  for='rpc_publish_api'><?php 
eT("Publish API on /admin/remotecontrol:");
?>
</label>
    <div class="col-sm-6">
        <?php 
$this->widget('yiiwheels.widgets.switch.WhSwitch', array('name' => 'rpc_publish_api', 'id' => 'rpc_publish_api', 'value' => getGlobalSetting('rpc_publish_api'), 'onLabel' => gT('On'), 'offLabel' => gT('Off')));
?>
    </div>
</div>

<?php 
if (Yii::app()->getConfig("demoMode") == true) {
    ?>
    <p><?php 
    eT("Note: Demo mode is activated. Marked (*) settings can't be changed.");
    ?>
</p>
    <?php 
}
Example #20
0
 /**
  * survey::_generalTabNewSurvey()
  * Load "General" tab of new survey screen.
  * @return
  */
 private function _generalTabNewSurvey()
 {
     //Use the current user details for the default administrator name and email for this survey
     $user = User::model()->findByPk(Yii::app()->session['loginID']);
     $owner = $user->attributes;
     //Degrade gracefully to $siteadmin details if anything is missing.
     if (empty($owner['full_name'])) {
         $owner['full_name'] = getGlobalSetting('siteadminname');
     }
     if (empty($owner['email'])) {
         $owner['email'] = getGlobalSetting('siteadminemail');
     }
     //Bounce setting by default to global if it set globally
     if (getGlobalSetting('bounceaccounttype') != 'off') {
         $owner['bounce_email'] = getGlobalSetting('siteadminbounce');
     } else {
         $owner['bounce_email'] = $owner['email'];
     }
     $aData['action'] = "newsurvey";
     $aData['owner'] = $owner;
     $aLanguageDetails = getLanguageDetails(Yii::app()->session['adminlang']);
     $aData['sRadixDefault'] = $aLanguageDetails['radixpoint'];
     $aData['sDateFormatDefault'] = $aLanguageDetails['dateformat'];
     foreach (getRadixPointData() as $index => $radixptdata) {
         $aRadixPointData[$index] = $radixptdata['desc'];
     }
     $aData['aRadixPointData'] = $aRadixPointData;
     foreach (getDateFormatData(0, Yii::app()->session['adminlang']) as $index => $dateformatdata) {
         $aDateFormatData[$index] = $dateformatdata['dateformat'];
     }
     $aData['aDateFormatData'] = $aDateFormatData;
     return $aData;
 }
Example #21
0
 /**
  * Prints the update notification
  *
  * @access protected
  * @return mixed
  */
 public function getUpdateNotification()
 {
     $crosscheck = getGlobalSetting('updatenotification') == "both" ? 1 : 0;
     $updates = $this->getUpdateInfo($crosscheck = "1");
     $update_available = FALSE;
     if ($updates->result) {
         unset($updates->result);
         if (count($updates) > 0) {
             $update_available = TRUE;
             $security_update_available = FALSE;
             foreach ($updates as $update) {
                 if ($update->security_update) {
                     $security_update_available = TRUE;
                 }
             }
         }
         $updates = array('result' => $update_available, 'security_update' => $security_update_available);
     }
     return (object) $updates;
 }
Example #22
0
eT("Off");
?>
</option>
        <option value='SSL'
            <?php 
if (getGlobalSetting('bounceencryption') == 'SSL') {
    echo " selected='selected'";
}
?>
            ><?php 
eT("SSL");
?>
</option>
        <option value='TLS'
            <?php 
if (getGlobalSetting('bounceencryption') == 'TLS') {
    echo " selected='selected'";
}
?>
            ><?php 
eT("TLS");
?>
</option>
    </select></li></ul>

<p><br/><input type='button' onclick='$("#frmglobalsettings").submit();' class='standardbtn' value='<?php 
eT("Save settings");
?>
' /><br /></p>
<?php 
if (Yii::app()->getConfig("demoMode") == true) {
Example #23
0
 /**
  * This function has a special rendering, because the ComfortUpdate server can choose what it's going to show :
  * the welcome message or the subscribe message or the updater update, etc.
  * The same system is used for the static views (update key, etc.)
  *
  * @return html the welcome message
  */
 public function getwelcome()
 {
     // We get the update key in the database. If it's empty, getWelcomeMessage will return subscription
     $updateKey = getGlobalSetting("update_key");
     //$updateKey = SettingGlobal::model()->findByPk('update_key')->stg_value;
     $updateModel = new UpdateForm();
     $destinationBuild = $_REQUEST['destinationBuild'];
     $welcome = (array) $updateModel->getWelcomeMessage($updateKey, $destinationBuild);
     $welcome['destinationBuild'] = $destinationBuild;
     $welcome = (object) $welcome;
     return $this->_renderWelcome($welcome);
 }
Example #24
0
 /**
  * Load CodeMirror editor and various files information.
  *
  * @access protected
  * @param string $templatename
  * @param string $screenname
  * @param string $editfile
  * @param string $templates
  * @param string $files
  * @param string $cssfiles
  * @param array $otherfiles
  * @param array $myoutput
  * @return void
  */
 protected function _templatesummary($templatename, $screenname, $editfile, $templates, $files, $cssfiles, $otherfiles, $myoutput)
 {
     $tempdir = Yii::app()->getConfig("tempdir");
     $tempurl = Yii::app()->getConfig("tempurl");
     Yii::app()->loadHelper("admin/template");
     $aData = array();
     $time = date("ymdHis");
     // Prepare textarea class for optional javascript
     $templateclasseditormode = getGlobalSetting('defaulttemplateeditormode');
     // default
     if (Yii::app()->session['templateeditormode'] == 'none') {
         $templateclasseditormode = 'none';
     }
     $aData['templateclasseditormode'] = $templateclasseditormode;
     // The following lines are forcing the browser to refresh the templates on each save
     @($fnew = fopen("{$tempdir}/template_temp_{$time}.html", "w+"));
     $aData['time'] = $time;
     if (!$fnew) {
         $aData['filenotwritten'] = true;
     } else {
         @fwrite($fnew, getHeader());
         foreach ($cssfiles as $cssfile) {
             $myoutput = str_replace($cssfile['name'], $cssfile['name'] . "?t={$time}", $myoutput);
         }
         $myoutput = implode("\n", $myoutput);
         App()->getClientScript()->registerPackage('jqueryui');
         App()->getClientScript()->registerPackage('jquery-touch-punch');
         App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "survey_runtime.js");
         App()->getClientScript()->render($myoutput);
         @fwrite($fnew, $myoutput);
         @fclose($fnew);
     }
     if (Yii::app()->session['templateeditormode'] !== 'default') {
         $sTemplateEditorMode = Yii::app()->session['templateeditormode'];
     } else {
         $sTemplateEditorMode = getGlobalSetting('templateeditormode', 'full');
     }
     $sExtension = substr(strrchr($editfile, '.'), 1);
     switch ($sExtension) {
         case 'css':
             $sEditorFileType = 'css';
             break;
         case 'pstpl':
             $sEditorFileType = 'html';
             break;
         case 'js':
             $sEditorFileType = 'javascript';
             break;
         default:
             $sEditorFileType = 'html';
             break;
     }
     $aData['clang'] = $this->getController()->lang;
     $aData['screenname'] = $screenname;
     $aData['editfile'] = $editfile;
     $aData['tempdir'] = $tempdir;
     $aData['templatename'] = $templatename;
     $aData['templates'] = $templates;
     $aData['files'] = $files;
     $aData['cssfiles'] = $cssfiles;
     $aData['otherfiles'] = $otherfiles;
     $aData['tempurl'] = $tempurl;
     $aData['time'] = $time;
     $aData['sEditorFileType'] = $sEditorFileType;
     $aData['sTemplateEditorMode'] = $sTemplateEditorMode;
     $aViewUrls['templatesummary_view'][] = $aData;
     return $aViewUrls;
 }
    <div class="box w98_per effect7">
        <h3>My Surveys</h3>
        <p style="display: inline-block">
        <table class="InfoForm" style="width: 95%; margin: 0px auto;">
            <tr>
                <th>Name</th>
                <th>Status</th>
                <th>Point</th>
                <th>Point Awarded</th>
                <th>Note</th>
            </tr>

            <?php 
$status_test = getGlobalSetting('project_status_run');
$status_run = getGlobalSetting('project_status_test');
$status_completed = getGlobalSetting('project_status_completed');
//$sql = "select * from {{panellist_project}} where panellist_id = '" . $_SESSION['plid'] . "' and status <> 'A' order by project_id desc";
$sql = "SELECT project_id,project_url,points,status FROM {{panellist_project}}\n                    WHERE panellist_id = '" . $_SESSION['plid'] . "' AND status <> 'A'\n                    UNION ALL \n                    SELECT project_id,project_url,points,status FROM {{panellist_project}}\n                    WHERE panellist_id = '" . $_SESSION['plid'] . "' AND status = 'A' \n                    AND project_id IN (SELECT project_id FROM {{project_master}} WHERE project_status_id NOT IN ('{$status_test}','{$status_run}'))\n                    ORDER BY project_id DESC";
$query_details = Yii::app()->db->createCommand($sql)->query()->readAll();
if (count($query_details) > 0) {
    foreach ($query_details as $key => $value) {
        //$ProjectSql = "SELECT Name,PFName,points,Status,trueup from projects_master where ID = '" . $value['project_id'] . "'";
        $ProjectSql = "select project_name, friendly_name,reward_points,project_status_id,trueup from {{project_master}} where project_id = '" . $value['project_id'] . "' ";
        $valueproj = Yii::app()->db->createCommand($ProjectSql)->queryRow();
        $serveryStatus = $value['status'];
        $recordTrueup = FALSE;
        $check_trueup_exist_sql = "SELECT pp.project_id,pp.project_url,prd.rectify_id\n                                    from {{panellist_project}} pp, {{panellist_redirects}} prd\n                                    where pp.panellist_id = prd.panellist_id\n                                    and pp.project_id = prd.project_id\n                                    and pp.panellist_id = '" . $_SESSION['plid'] . "'\n                                    and pp.project_id = '" . $value['project_id'] . "'\n                                    and prd.rectify_id <> '' \n                                    order by project_id desc;";
        $check_trueup_exist_qur = Yii::app()->db->createCommand($check_trueup_exist_sql)->query()->readAll();
        $rows = 0;
        if (count($check_trueup_exist_qur) > 0) {
            $recordTrueup = TRUE;
$pmquery = "SELECT * FROM {{view_contacts}} WHERE contact_title_ID LIKE '%{$Project_Manager}%'";
$pmresult = Yii::app()->db->createCommand($pmquery)->query()->readAll();
//Checked
$projmanager_list = CHtml::listData($pmresult, 'contact_id', 'full_name');
echo CHtml::dropDownList('project_manager', '', $projmanager_list, array('prompt' => 'Select Project Manager'));
?>
        </td>
        <td style="text-align: right;">
            <label for='sales_person'><?php 
$clang->eT("Sales Person : ");
?>
</label>
        </td>
        <td>
            <?php 
$Sales_Person = getGlobalSetting('Sales_Person');
$spquery = "SELECT * FROM {{view_contacts}} WHERE contact_title_ID NOT LIKE '%{$Project_Manager}%'";
$spresult = Yii::app()->db->createCommand($spquery)->query()->readAll();
//Checked
$salesperson_list = CHtml::listData($spresult, 'contact_id', 'full_name');
echo CHtml::dropDownList('sales_person', '', $salesperson_list, array('prompt' => 'Select Sales Person'));
?>
        </td>
    </tr>
    <tr>
        <td style="text-align: right;">
            <label for='country'><?php 
$clang->eT("Country : ");
?>
</label>
        </td>
</table>
<p  style="padding-top: 1em;">
    <input type='submit' value='<?php 
$clang->eT("Save");
?>
' />
    <input type='hidden' name='action' value='editvendor' />
    &nbsp;&nbsp;
    <a href="<?php 
echo $this->createUrl('admin/project/sa/modifyproject/project_id/' . $project_id . '/action/modifyproject');
?>
" class="limebutton">Cancel</a>
</p>
</form>
<?php 
if (getGlobalSetting('Own_Panel') == $vendor_arr_single[0]['vendor_id']) {
    ?>
    <div class='header ui-widget-header'>
        <?php 
    $clang->eT("Query and Count");
    ?>
        <span style="float: right">
            <?php 
    //                $imghtml = CHtml::image($imageurl . 'add.png');
    //                echo "<div id='your-form-block-id'>";
    //                echo CHtml::beginForm();
    //                echo CHtml::link($imghtml, array('admin/project/sa/add_query/prjid/' . $project_id), array('class' => 'class-link'));
    //                echo CHtml::endForm();
    //                echo "</div>";
    //
    ?>
Example #28
0
function questionExport($action, $iSurveyID, $gid, $qid)
{
    $fn = "limesurvey_question_{$qid}.lsq";
    $xml = getXMLWriter();
    header("Content-Type: application/force-download");
    header("Content-Disposition: attachment; filename={$fn}");
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
    // Date in the past
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Pragma: cache");
    // HTTP/1.0
    $xml->openURI('php://output');
    $xml->setIndent(true);
    $xml->startDocument('1.0', 'UTF-8');
    $xml->startElement('document');
    $xml->writeElement('LimeSurveyDocType', 'Question');
    $xml->writeElement('DBVersion', getGlobalSetting('DBVersion'));
    $xml->startElement('languages');
    $aLanguages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
    $aLanguages[] = Survey::model()->findByPk($iSurveyID)->language;
    foreach ($aLanguages as $sLanguage) {
        $xml->writeElement('language', $sLanguage);
    }
    $xml->endElement();
    questionGetXMLStructure($xml, $gid, $qid);
    $xml->endElement();
    // close columns
    $xml->endDocument();
    exit;
}
Example #29
0
    exit;
}
// Bouceprocessing
if($subaction=='bounceprocessing')
{
    if($thissurvey['bounceprocessing'] != 'N' && bHasSurveyPermission($surveyid,'tokens','update'))
    {
        $bouncetotal=0;
        $checktotal=0;
        if($thissurvey['bounceprocessing']=='G')
        {
            $accounttype=getGlobalSetting('bounceaccounttype');
            $hostname=getGlobalSetting('bounceaccounthost');
            $username=getGlobalSetting('bounceaccountuser');
            $pass=getGlobalSetting('bounceaccountpass');
            $hostencryption=getGlobalSetting('bounceencryption');

        }
        else
        {
            $accounttype=$thissurvey['bounceaccounttype'];
            $hostname=$thissurvey['bounceaccounthost'];
            $username=$thissurvey['bounceaccountuser'];
            $pass=$thissurvey['bounceaccountpass'];
            $hostencryption=$thissurvey['bounceaccountencryption'];

        }
        @list($hostname,$port) = split(':', $hostname);
            if(empty($port))
            {
              if($accounttype=="IMAP")
    echo $allLanguages[$sLanguageCode]['description'];
    ?>
</option><?php 
}
?>
                                </select>
                            </td>
                        </tr>
                    </table>
                </li>
            </ul>
        </div>
        <div id='interfaces'>
            <ul>
                <?php 
$RPCInterface = getGlobalSetting('RPCInterface');
?>
                <li><label for='RPCInterface'><?php 
$clang->eT("RPC interface enabled:");
?>
</label>
                    <select id='RPCInterface' name='RPCInterface'>
                        <option value='off'
                            <?php 
if ($RPCInterface == 'off') {
    echo " selected='selected'";
}
?>
                            ><?php 
$clang->eT("Off");
?>