diff --git a/application/config/simpletester.php b/application/config/simpletester.php
new file mode 100644
index 00000000000..582cbf878dc
--- /dev/null
+++ b/application/config/simpletester.php
@@ -0,0 +1,85 @@
+simpletester->Run();
+|
+*/
+$config['noautorun'] = FALSE;
+
+/*
+|--------------------------------------------------------------------------
+| Test files extension
+|--------------------------------------------------------------------------
+|
+| If your php files have a different extension, php5 for example,
+| specify it here (without dot). All files ending with this extension will
+| be added to the test suite.
+|
+*/
+$config['fileExtension'] = 'php';
+
+/*
+|--------------------------------------------------------------------------
+| Test title
+|--------------------------------------------------------------------------
+|
+| Here you can specify the title of the test suite. Will be displayed for
+| example in the MinimalReporter when a test fails.
+|
+*/
+$config['testTitle'] = 'CodeIgnited Unit Tests';
diff --git a/application/controllers/survey.php b/application/controllers/survey.php
index ee1854fe860..00205c2d9d9 100644
--- a/application/controllers/survey.php
+++ b/application/controllers/survey.php
@@ -16,924 +16,738 @@
class survey extends LSCI_Controller {
- function __construct()
- {
- parent::__construct();
- }
-
- public function _remap($method, $params = array())
- {
- array_unshift($params, $method);
- return call_user_func_array(array($this, "action"), $params);
- }
-
- function action()
- {
- global $surveyid, $thistpl, $totalquestions;
- global $thissurvey, $thisstep;
- global $clienttoken, $tokensexist, $token;
-
- //Replace $_GET:
- $arg_list = func_get_args();
- if($arg_list[0]==__CLASS__) array_shift($arg_list);
- if(count($arg_list)%2 == 0) {
- for ($i = 0; $i < count($arg_list); $i+=2) {
- //Sanitize input from URL with returnglobal
- $param[$arg_list[$i]] = returnglobal($arg_list[$i], $arg_list[$i+1]);
- }
- }
+ function __construct()
+ {
+ parent::__construct();
+ }
- @ini_set('session.gc_maxlifetime', $this->config->item('sess_expiration'));
-
- //Load helpers, libraries and config vars
- $this->load->helper("database");
- $this->load->helper("frontend");
- $this->load->helper("surveytranslator");
-
- $relativeurl = $this->config->item("relativeurl");
- $defaultlang = $this->config->item("defaultlang");
- $siteadminname = $this->config->item("siteadminname");
- $siteadminemail = $this->config->item("siteadminemail");
- $sitename = $this->config->item("sitename");
- $standardtemplaterootdir = $this->config->item("standardtemplaterootdir");
- $dbprefix = $this->db->dbprefix;
-
- $this->load->library("Dtexts");
-
- $_POST=$this->input->post();
- //$_SESSION=$this->session->userdata;
-
- $surveyid = isset($param['sid']) ? $param['sid'] : returnglobal('sid');
- $loadname= isset($param['loadname']) ? $param['loadname'] : returnglobal('loadname');
- $loadpass= isset($param['loadpass']) ? $param['loadpass'] : returnglobal('loadpass');
- $scid= isset($param['scid']) ? $param['scid'] : returnglobal('scid');
- $thisstep= isset($param['thisstep']) ? $param['thisstep'] : returnglobal('thisstep');
- $move = isset($param['move']) ? sanitize_paranoid_string($param['move']) : sanitize_paranoid_string(returnglobal('move'));
- $clienttoken= isset($param['token']) ? sanitize_token($param['token']) : sanitize_token(returnglobal('token'));
-
- if(!isset($param['action']))
- $param['action'] = isset($_POST['action']) ? $_POST['action'] : null;
- if(!isset($param['newtest']))
- $param['newtest'] = isset($_POST['newtest']) ? $_POST['newtest'] : null;
- if(!isset($param['gid']))
- $param['gid'] = isset($_POST['gid']) ? $_POST['gid'] : null;
-
- if (!isset($thisstep))
- {
- $thisstep = "";
- }
+ public function _remap($method, $params = array())
+ {
+ array_unshift($params, $method);
+ return call_user_func_array(array($this, "action"), $params);
+ }
- //This next line ensures that the $surveyid value is never anything but a number.
- $surveyid=sanitize_int($surveyid);
+ function action()
+ {
+ global $surveyid, $thistpl, $totalquestions;
+ global $thissurvey, $thisstep;
+ global $clienttoken, $tokensexist, $token;
- // Compute the Session name
- // Session name is based:
- // * on this specific limesurvey installation (Value SessionName in DB)
- // * on the surveyid (from Get or Post param). If no surveyid is given we are on the public surveys portal
+ @ini_set('session.gc_maxlifetime', $this->config->item('sess_expiration'));
- $sSessionname=getGlobalSetting('SessionName');
- if ($sSessionname!='')
- {
- if ($surveyid)
- {
- $sSessionname = $sSessionname.'-runtime-'.$surveyid;
- }
- else
- {
- $sSessionname = $sSessionname.'-runtime-publicportal';
- }
- }
- else
- {
- $sSessionname = "LimeSurveyRuntime-$surveyid";
- }
+ $this->_loadRequiredHelpersAndLibraries();
- // Establish / Switch to survey session
- // Import data from current session (if available) to survey
- // session if the survey session has no data.
+ $_POST = $this->input->post();
+ //$_SESSION = $this->session->userdata;
+ $param = $this->_getParameters(func_get_args(), $_POST);
- $__SESSION = array(); // session data copy store
- $oSess = new LS_PHP_Session();
- if ($oSess->changeTo($sSessionname))
+ $surveyid = $param['sid'];
+ $thisstep = $param['thisstep'];
+ $move = $param['move'];
+ $clienttoken = $param['token'];
+ $standardtemplaterootdir = $this->config->item("standardtemplaterootdir");
+
+ // unused vars in this method (used in methods using compacted method vars)
+ $loadname = $param['loadname'];
+ $loadpass = $param['loadpass'];
+ $sitename = $this->config->item("sitename");
+ $relativeurl = $this->config->item("relativeurl");
+
+ $this->_setSessionToSurvey($surveyid);
+
+ list($surveyExists, $isSurveyActive) = $this->_surveyExistsAndIsActive($surveyid);
+
+ // collect all data in this method to pass on later
+ $redata = compact(array_keys(get_defined_vars()));
+
+ if ( $this->_isClientTokenDifferentFromSessionToken($clienttoken) )
{
- // Needed to call session_start() below.
- $__SESSION =& $_SESSION; // reference current session data.
- unset($_SESSION);
- $_SESSION = array();
+ $clang = $this->_loadLimesurveyLang($surveyid);
+ $asMessage = array(
+ $clang->gT('Token mismatch'),
+ $clang->gT("The token you provided doesn't match the one in your session."),
+ $clang->gT("Please wait to begin with a new session.")
+ );
+ $this->_createNewUserSessionAndRedirect($surveyid, $redata, $asMessage);
}
- else
+
+ if ( $this->_isSurveyFinished() )
{
- session_name($sSessionname);
+ $clang = $this->_loadLimesurveyLang($surveyid);
+ $asMessage = array(
+ $clang->gT("Previous session is set to be finished."),
+ $clang->gT("Your browser reports that it was used previously to answer this survey. We are resetting the session so that you can start from the beginning."),
+ $clang->gT("Please wait to begin with a new session.")
+ );
+ $this->_createNewUserSessionAndRedirect($surveyid, $redata, $asMessage);
}
- unset($oSess);
- session_set_cookie_params(0,$relativeurl);
- if (empty($_SESSION)) // the $_SESSION variable can be empty if register_globals is on
+
+ if ($this->_isPreviewAction($param) && !$this->_canUserPreviewSurvey($surveyid)){
+ $clang = $this->_loadLimesurveyLang($surveyid);
+ $this->_printMessage(
+ $clang->gT("Error"),
+ $clang->gT("We are sorry but you don't have permissions to do this.")
+ );
+ $this->_killPage($redata, __LINE__);
+ }
+
+ if ( $this->_surveyCantBeViewedWithCurrentPreviewAccess($surveyid, $isSurveyActive, $surveyExists) )
{
- @session_start();
- if (empty($_SESSION)) // if this session is new, import old session
+ // admin session and permission have not already been imported
+ // for this particular survey
+ if ( !isset($_SESSION['USER_RIGHT_PREVIEW']) || $_SESSION['USER_RIGHT_PREVIEW'] != $surveyid)
{
- $_SESSION = $__SESSION;
- unset($__SESSION);
+ // Store initial session name
+ $initial_session_name = session_name();
+
+ // One way (not implemented here) would be to start the
+ // user session from a duplicate of the admin session
+ // - destroy the new session
+ // - load admin session (with correct session name)
+ // - close admin session
+ // - change used session name to default
+ // - open new session (takes admin session id)
+ // - regenerate brand new session id for this session
+
+ // The solution implemented here is to copy some
+ // fields from the admin session to the new session
+ // - first destroy the new (empty) user session
+ // - then open admin session
+ // - record interresting values from the admin session
+ // - duplicate admin session under another name and Id
+ // - destroy the duplicated admin session
+ // - start a brand new user session
+ // - copy interresting values in this user session
+
+ @session_destroy(); // make it silent because for
+ // some strange reasons it fails sometimes
+ // which is not a problem
+ // but if it throws an error then future
+ // session functions won't work because
+ // headers are already sent.
+ if (isset($stg_SessionName) && $stg_SessionName)
+ {
+ @session_name($stg_SessionName);
+ }
+ else
+ {
+ session_name("LimeSurveyAdmin");
+ }
+ session_start(); // Loads Admin Session
+
+ $previewright=false;
+ $savesessionvars=Array();
+ if (isset($_SESSION['loginID']))
+ {
+ $rightquery="SELECT uid FROM ".($this->db->dbprefix('survey_permissions'))." WHERE sid=".$this->db->escape($surveyid)." AND uid = ".$this->db->escape($_SESSION['loginID'].' group by uid');
+ $rightresult = db_execute_assoc($rightquery); //Checked
+
+ // Currently it is enough to be listed in the survey
+ // user operator list to get preview access
+ if ($rightresult->num_rows() > 0 || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1)
+ {
+ $previewright=true;
+ $savesessionvars["USER_RIGHT_PREVIEW"]=$surveyid;
+ $savesessionvars["loginID"]=$_SESSION['loginID'];
+ $savesessionvars["user"]=$_SESSION['user'];
+ }
+ }
+
+ // change session name and id
+ // then delete this new session
+ // ==> the original admin session remains valid
+ // ==> it is possible to start a new session
+ session_name($initial_session_name);
+ if ($sessionhandler=='db')
+ {
+ adodb_session_regenerate_id();
+ }
+ elseif (session_regenerate_id() === false)
+ {
+ safe_die("Error Regenerating Session Id");
+ }
+ @session_destroy();
+
+ // start new session
+ @session_start();
+ // regenerate id so that the header geenrated by previous
+ // regenerate_id is overwritten
+ // needed after clearall
+ if ($sessionhandler=='db')
+ {
+ adodb_session_regenerate_id();
+ }
+ elseif (session_regenerate_id() === false)
+ {
+ safe_die("Error Regenerating Session Id");
+ }
+
+ if ( $previewright === true)
+ {
+ foreach ($savesessionvars as $sesskey => $sessval)
+ {
+ $_SESSION[$sesskey]=$sessval;
+ }
+ }
+ }
+ else
+ { // already authorized
+ $previewright = true;
}
- $this->session->bind_userdata();
- }
- // First check if survey is active
- // if not: copy some vars from the admin session
- // to a new user session
+ if ($previewright === false)
+ {
+ // print an error message
+ if (isset($_REQUEST['rootdir']))
+ {
+ safe_die('You cannot start this script directly');
+ }
+ $clang = $this->_loadLimesurveyLang($surveyid);
+ //A nice exit
+ sendcacheheaders();
+ doHeader();
- if ($surveyid)
- {
- $issurveyactive=false;
- $aRow=db_execute_assoc("SELECT * FROM ".$this->db->dbprefix('surveys')." WHERE sid=$surveyid")->row_array();
- if (isset($aRow['active']))
- {
- $surveyexists=true;
- if($aRow['active']=='Y')
- {
- $issurveyactive=true;
- }
- }
- else
- {
- $surveyexists=false;
- }
- }
+ $redata = compact(array_keys(get_defined_vars()));
+ $this->_printTemplateContent($this->config->item("standardtemplaterootdir").'/default/startpage.pstpl', $redata, __LINE__);
+ $this->_printMessage(
+ $clang->gT("Error"),
+ $clang->gT("We are sorry but you don't have permissions to do this."),
+ sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail'])
+ );
+
+ $this->_killPage($redata, __LINE__);
+ }
+ }
- if ($clienttoken != '' && isset($_SESSION['token']) &&
- $clienttoken != $_SESSION['token'])
- {
- $baselang = GetBaseLanguageFromSurveyID($surveyid);
- $this->load->library('Limesurvey_lang',array("langcode"=>$baselang));
- $clang = $this->limesurvey_lang;
- // Let's first regenerate a session id
- killSession();
- // Let's redirect the client to the same URL after having reseted the session
- //header("Location: $rooturl/index.php?" .$_SERVER['QUERY_STRING']);
- sendcacheheaders();
- doHeader();
- $redata = compact(array_keys(get_defined_vars()));
- echo templatereplace(file_get_contents("$standardtemplaterootdir/default/startpage.pstpl"),array(),$redata,'survey[159]');
- echo "\t
\n"
- ."\t
\n"
- ."\t".$clang->gT("Token mismatch")."
\n"
- ."\t".$clang->gT("The token you provided doesn't match the one in your session.")."
\n"
- ."\t".$clang->gT("Please wait to begin with a new session.")."
\n"
- ."\t
\n"
- ."\t
\n";
-
- echo templatereplace(file_get_contents("$standardtemplaterootdir/default/endpage.pstpl"),array(),$redata,'survey[168]');
- doFooter();
- exit;
- }
+ if (isset($_SESSION['srid']))
+ {
+ $saved_id = $_SESSION['srid'];
+ }
- if (isset($_SESSION['finished']) && $_SESSION['finished'] === true)
- {
- $baselang = GetBaseLanguageFromSurveyID($surveyid);
- $this->load->library('Limesurvey_lang',array("langcode"=>$baselang));
- $clang = $this->limesurvey_lang;
- // Let's first regenerate a session id
- killSession();
- // Let's redirect the client to the same URL after having reseted the session
- //header("Location: " .$this->config->site_url()."/".$this->uri->uri_string());
- sendcacheheaders();
- doHeader();
+ if (!isset($_SESSION['s_lang']) && (isset($move)) )
+ // geez ... a session time out! RUN!
+ {
+ if (isset($param['rootdir']))
+ {
+ safe_die('You cannot start this script directly');
+ }
+ $clang = $this->_loadLimesurveyLang($surveyid);
+ //A nice exit
+ sendcacheheaders();
+ doHeader();
$redata = compact(array_keys(get_defined_vars()));
- echo templatereplace(file_get_contents("$standardtemplaterootdir/default/startpage.pstpl"),array(),$redata,'survey[186]');
- echo "\t\n"
- ."\t
\n"
- ."\t".$clang->gT("Previous session is set to be finished.")."
\n"
- ."\t".$clang->gT("Your browser reports that it was used previously to answer this survey. We are resetting the session so that you can start from the beginning.")."
\n"
- ."\t".$clang->gT("Please wait to begin with a new session.")."
\n"
- ."\t
\n"
- ."\t
\n";
-
- echo templatereplace(file_get_contents("$standardtemplaterootdir/default/endpage.pstpl"),array(),$redata,'survey[195]');
- doFooter();
- exit;
- }
- $previewgrp = false;
- if (isset($param['action']) && ($param['action'] == 'previewgroup')){
- $rightquery="SELECT uid FROM {$dbprefix}survey_permissions WHERE sid=".$this->db->escape($surveyid)." AND uid = ".$this->db->escape($this->session->userdata('loginID')).' group by uid';
- $rightresult = db_execute_assoc($rightquery);
- if ($rightresult->num_rows() > 0 || $this->session->userdata('USER_RIGHT_SUPERADMIN') == 1)
- {
- $previewgrp = true;
- }
- else
- {
- $baselang = GetBaseLanguageFromSurveyID($surveyid);
- $this->load->library('Limesurvey_lang',array("langcode"=>$baselang));
- show_error("\t".$this->limesurvey_lang->gT("ERROR")."
\n"
- ."\t".$this->limesurvey_lang->gT("We are sorry but you don't have permissions to do this.")."
\n");
- }
- }
+ $this->_printTemplateContent($this->config->item("standardtemplaterootdir").'/default/startpage.pstpl', $redata, __LINE__);
+ $this->_printMessage(
+ $clang->gT("Error"),
+ $clang->gT("We are sorry but your session has expired."),
+ $clang->gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection."),
+ sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail'])
+ );
+
+ $this->_killPage($redata, __LINE__);
+ };
+
+ // Set the language of the survey, either from POST, GET parameter of session var
+ if (isset($_POST['lang']) && $_POST['lang']!='') // this one comes from the language question
+ {
+ $templang = sanitize_languagecode($_POST['lang']);
+ $clang = SetSurveyLanguage( $surveyid, $templang);
+ UpdateSessionGroupList($surveyid, $templang); // to refresh the language strings in the group list session variable
- if (($surveyid &&
- $issurveyactive===false && $surveyexists &&
- isset ($surveyPreview_require_Auth) &&
- $surveyPreview_require_Auth == true) && $previewgrp == false)
- {
- // admin session and permission have not already been imported
- // for this particular survey
- if ( !isset($_SESSION['USER_RIGHT_PREVIEW']) ||
- $_SESSION['USER_RIGHT_PREVIEW'] != $surveyid)
- {
- // Store initial session name
- $initial_session_name=session_name();
-
- // One way (not implemented here) would be to start the
- // user session from a duplicate of the admin session
- // - destroy the new session
- // - load admin session (with correct session name)
- // - close admin session
- // - change used session name to default
- // - open new session (takes admin session id)
- // - regenerate brand new session id for this session
-
- // The solution implemented here is to copy some
- // fields from the admin session to the new session
- // - first destroy the new (empty) user session
- // - then open admin session
- // - record interresting values from the admin session
- // - duplicate admin session under another name and Id
- // - destroy the duplicated admin session
- // - start a brand new user session
- // - copy interresting values in this user session
-
- @session_destroy(); // make it silent because for
- // some strange reasons it fails sometimes
- // which is not a problem
- // but if it throws an error then future
- // session functions won't work because
- // headers are already sent.
- if (isset($stg_SessionName) && $stg_SessionName)
- {
- @session_name($stg_SessionName);
- }
- else
- {
- session_name("LimeSurveyAdmin");
- }
- session_start(); // Loads Admin Session
-
- $previewright=false;
- $savesessionvars=Array();
- if (isset($_SESSION['loginID']))
- {
- $rightquery="SELECT uid FROM {$dbprefix}survey_permissions WHERE sid=".$this->db->escape($surveyid)." AND uid = ".$this->db->escape($_SESSION['loginID'].' group by uid');
- $rightresult = db_execute_assoc($rightquery); //Checked
-
- // Currently it is enough to be listed in the survey
- // user operator list to get preview access
- if ($rightresult->num_rows() > 0 || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1)
- {
- $previewright=true;
- $savesessionvars["USER_RIGHT_PREVIEW"]=$surveyid;
- $savesessionvars["loginID"]=$_SESSION['loginID'];
- $savesessionvars["user"]=$_SESSION['user'];
- }
- }
-
- // change session name and id
- // then delete this new session
- // ==> the original admin session remains valid
- // ==> it is possible to start a new session
- session_name($initial_session_name);
- if ($sessionhandler=='db')
- {
- adodb_session_regenerate_id();
- }
- elseif (session_regenerate_id() === false)
- {
- safe_die("Error Regenerating Session Id");
- }
- @session_destroy();
-
- // start new session
- @session_start();
- // regenerate id so that the header geenrated by previous
- // regenerate_id is overwritten
- // needed after clearall
- if ($sessionhandler=='db')
- {
- adodb_session_regenerate_id();
- }
- elseif (session_regenerate_id() === false)
- {
- safe_die("Error Regenerating Session Id");
- }
-
- if ( $previewright === true)
- {
- foreach ($savesessionvars as $sesskey => $sessval)
- {
- $_SESSION[$sesskey]=$sessval;
- }
- }
- }
- else
- { // already authorized
- $previewright = true;
- }
-
- if ($previewright === false)
- {
- // print an error message
- if (isset($_REQUEST['rootdir']))
- {
- safe_die('You cannot start this script directly');
- }
- //require_once(dirname(__FILE__).'/classes/core/language.php');
- $baselang = GetBaseLanguageFromSurveyID($surveyid);
- $this->load->library('Limesurvey_lang',array("langcode"=>$baselang));
- $clang = $this->limesurvey_lang;
- //A nice exit
- sendcacheheaders();
- doHeader();
+ UpdateFieldArray(); // to refresh question titles and question text
+ }
+ else if (isset($param['lang']) && $surveyid)
+ {
+ $templang = sanitize_languagecode($param['lang']);
+ $clang = SetSurveyLanguage( $surveyid, $templang);
+ UpdateSessionGroupList($surveyid, $templang); // to refresh the language strings in the group list session variable
+ UpdateFieldArray(); // to refresh question titles and question text
+ }
- $redata = compact(array_keys(get_defined_vars()));
- echo templatereplace(file_get_contents("$standardtemplaterootdir/default/startpage.pstpl"),array(),$redata,'survey[340]');
- echo "\t\n"
- ."\t
\n"
- ."\t".$clang->gT("ERROR")."
\n"
- ."\t".$clang->gT("We are sorry but you don't have permissions to do this.")."
\n"
- ."\t".sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$siteadminname,encodeEmail($siteadminemail))."
\n"
- ."\t
\n"
- ."\t
\n";
-
- echo templatereplace(file_get_contents("$standardtemplaterootdir/default/endpage.pstpl"),array(),$redata,'survey[349]');
- doFooter();
- exit;
- }
- }
- if (isset($_SESSION['srid']))
- {
- $saved_id = $_SESSION['srid'];
- }
+ if (isset($_SESSION['s_lang']))
+ {
+ $clang = SetSurveyLanguage( $surveyid, $_SESSION['s_lang']);
+ }
+ elseif (isset($surveyid) && $surveyid)
+ {
+ $baselang = GetBaseLanguageFromSurveyID($surveyid);
+ $clang = SetSurveyLanguage( $surveyid, $baselang);
+ }
+ else
+ {
+ $baselang = $this->config->item("defaultlang");
+ }
- if (!isset($_SESSION['s_lang']) && (isset($move)) )
- // geez ... a session time out! RUN!
- {
- if (isset($param['rootdir']))
- {
- safe_die('You cannot start this script directly');
- }
- //require_once(dirname(__FILE__).'/classes/core/language.php');
- $baselang = GetBaseLanguageFromSurveyID($surveyid);
- $this->load->library('Limesurvey_lang',array("langcode"=>$baselang));
- $clang = $this->limesurvey_lang;
- //A nice exit
- sendcacheheaders();
- doHeader();
+ if (isset($param['embedded_inc']))
+ {
+ safe_die('You cannot start this script directly');
+ }
- $redata = compact(array_keys(get_defined_vars()));
- echo templatereplace(file_get_contents("$standardtemplaterootdir/default/startpage.pstpl"),array(),$redata,'survey[375]');
- echo "\t\n"
- ."\t
\n"
- ."\t".$clang->gT("ERROR")."
\n"
- ."\t".$clang->gT("We are sorry but your session has expired.")."
\n"
- ."\t".$clang->gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection.")."
\n"
- ."\t".sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$siteadminname,$siteadminemail)."
\n"
- ."\t
\n"
- ."\t
\n";
-
- echo templatereplace(file_get_contents("$standardtemplaterootdir/default/endpage.pstpl"),array(),$redata,'survey[385]');
- doFooter();
- exit;
- };
-
- // Set the language of the survey, either from POST, GET parameter of session var
- if (isset($_POST['lang']) && $_POST['lang']!='') // this one comes from the language question
- {
- $templang = sanitize_languagecode($_POST['lang']);
- $clang = SetSurveyLanguage( $surveyid, $templang);
- UpdateSessionGroupList($surveyid, $templang); // to refresh the language strings in the group list session variable
- UpdateFieldArray(); // to refresh question titles and question text
- }
- else
- if (isset($param['lang']) && $surveyid)
- {
- $templang = sanitize_languagecode($param['lang']);
- $clang = SetSurveyLanguage( $surveyid, $templang);
- UpdateSessionGroupList($surveyid, $templang); // to refresh the language strings in the group list session variable
- UpdateFieldArray(); // to refresh question titles and question text
- }
+ //CHECK FOR REQUIRED INFORMATION (sid)
+ if (!$surveyid)
+ {
+ if(isset($param['lang']))
+ {
+ $baselang = sanitize_languagecode($param['lang']);
+ }
+ elseif (!isset($baselang))
+ {
+ $baselang = $this->config->item("defaultlang");
+ }
+ $clang = $this->_loadLimesurveyLang($baselang);
+ if(!isset($defaulttemplate))
+ {
+ $defaulttemplate="default";
+ }
+ $languagechanger = makelanguagechanger();
+ //Find out if there are any publicly available surveys
+ $query = "SELECT a.sid, b.surveyls_title, a.publicstatistics
+ FROM ".$this->db->dbprefix('surveys')." AS a
+ INNER JOIN ".$this->db->dbprefix('surveys_languagesettings')." AS b
+ ON ( surveyls_survey_id = a.sid AND surveyls_language = a.language )
+ WHERE surveyls_survey_id=a.sid
+ AND surveyls_language=a.language
+ AND surveyls_language='$baselang'
+ AND a.active='Y'
+ AND a.listpublic='Y'
+ AND ((a.expires >= '".date("Y-m-d H:i")."') OR (a.expires is null))
+ AND ((a.startdate <= '".date("Y-m-d H:i")."') OR (a.startdate is null))
+ ORDER BY surveyls_title";
+ $result = db_execute_assoc($query,false,true) or die("Could not connect to database. If you try to install LimeSurvey please refer to the installation docs and/or contact the system administrator of this webpage."); //Checked
+ $list=array();
+ if($result->num_rows() > 0)
+ {
+ foreach($result->result_array() as $rows)
+ {
+ $link = "\n";
+ if ($rows['publicstatistics'] == 'Y') $link .= "(".$clang->gT('View statistics').")";
+ $link .= "\n";
+ $list[]=$link;
+ }
+ }
+ if(count($list) < 1)
+ {
+ $list[]="".$clang->gT("No available surveys")."";
+ }
+ $surveylist=array(
+ "nosid"=>$clang->gT("You have not provided a survey identification number"),
+ "contact"=>sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$this->config->item("siteadminname"),encodeEmail($this->config->item("siteadminemail"))),
+ "listheading"=>$clang->gT("The following surveys are available:"),
+ "list"=>implode("\n",$list),
+ );
+
+ $thissurvey['name'] = $this->config->item("sitename");
+ $thissurvey['templatedir'] = $defaulttemplate;
+
+ $data['thissurvey'] = $thissurvey;
+ //$data['privacy'] = $privacy;
+ $data['surveylist'] = $surveylist;
+ $data['surveyid'] = $surveyid;
+ $data['templatedir'] = sGetTemplatePath($defaulttemplate);
+ $data['templateurl'] = sGetTemplateURL($defaulttemplate)."/";
+ $data['templatename'] = $defaulttemplate;
+ $data['sitename'] = $this->config->item("sitename");
+ $data['languagechanger'] = $languagechanger;
+
+ //A nice exit
+ sendcacheheaders();
+ doHeader();
+ $this->_printTemplateContent(sGetTemplatePath($defaulttemplate)."/startpage.pstpl", $data, __LINE__);
+
+ $this->_printTemplateContent(sGetTemplatePath($defaulttemplate)."/surveylist.pstpl", $data, __LINE__);
+
+ $this->_killPage($redata, __LINE__);
+ }
- if (isset($_SESSION['s_lang']))
- {
- $clang = SetSurveyLanguage( $surveyid, $_SESSION['s_lang']);
- }
- elseif (isset($surveyid) && $surveyid)
- {
- $baselang = GetBaseLanguageFromSurveyID($surveyid);
- $clang = SetSurveyLanguage( $surveyid, $baselang);
- }
- else
- {
- $baselang=$defaultlang;
- }
+ // Get token
+ if (!isset($token))
+ {
+ $token=$clienttoken;
+ }
- if (isset($param['embedded_inc']))
- {
- safe_die('You cannot start this script directly');
- }
+ //GET BASIC INFORMATION ABOUT THIS SURVEY
+ $totalBoilerplatequestions =0;
+ $thissurvey=getSurveyInfo($surveyid, $_SESSION['s_lang']);
+ if (isset($param['newtest']) && $param['newtest'] == "Y")
+ {
+ //Removes any existing timer cookies so timers will start again
+ setcookie ("limesurvey_timers", "", time() - 3600);
+ }
- //CHECK FOR REQUIRED INFORMATION (sid)
- if (!$surveyid)
- {
- if(isset($param['lang']))
- {
- $baselang = sanitize_languagecode($param['lang']);
- }
- elseif (!isset($baselang))
- {
- $baselang=$defaultlang;
- }
- $this->load->library('Limesurvey_lang',array("langcode"=>$baselang));
- $clang = $this->limesurvey_lang;
- if(!isset($defaulttemplate))
- {
- $defaulttemplate="default";
- }
- $languagechanger = makelanguagechanger();
- //Find out if there are any publicly available surveys
- $query = "SELECT a.sid, b.surveyls_title, a.publicstatistics
- FROM ".$this->db->dbprefix('surveys')." AS a
- INNER JOIN ".$this->db->dbprefix('surveys_languagesettings')." AS b
- ON ( surveyls_survey_id = a.sid AND surveyls_language = a.language )
- WHERE surveyls_survey_id=a.sid
- AND surveyls_language=a.language
- AND surveyls_language='$baselang'
- AND a.active='Y'
- AND a.listpublic='Y'
- AND ((a.expires >= '".date("Y-m-d H:i")."') OR (a.expires is null))
- AND ((a.startdate <= '".date("Y-m-d H:i")."') OR (a.startdate is null))
- ORDER BY surveyls_title";
- $result = db_execute_assoc($query,false,true) or die("Could not connect to database. If you try to install LimeSurvey please refer to the installation docs and/or contact the system administrator of this webpage."); //Checked
- $list=array();
- if($result->num_rows() > 0)
- {
- foreach($result->result_array() as $rows)
- {
- $link = "\n";
- if ($rows['publicstatistics'] == 'Y') $link .= "(".$clang->gT('View statistics').")";
- $link .= "\n";
- $list[]=$link;
- }
- }
- if(count($list) < 1)
- {
- $list[]="".$clang->gT("No available surveys")."";
- }
- $surveylist=array(
- "nosid"=>$clang->gT("You have not provided a survey identification number"),
- "contact"=>sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$siteadminname,encodeEmail($siteadminemail)),
- "listheading"=>$clang->gT("The following surveys are available:"),
- "list"=>implode("\n",$list),
- );
-
- $thissurvey['name']=$sitename;
- $thissurvey['templatedir']=$defaulttemplate;
-
- $data['thissurvey'] = $thissurvey;
- //$data['privacy'] = $privacy;
- $data['surveylist'] = $surveylist;
- $data['surveyid'] = $surveyid;
- $data['templatedir'] = sGetTemplatePath($defaulttemplate);
- $data['templateurl'] = sGetTemplateURL($defaulttemplate)."/";
- $data['templatename'] = $defaulttemplate;
- $data['sitename'] = $sitename;
- $data['languagechanger'] = $languagechanger;
-
- //A nice exit
- sendcacheheaders();
- doHeader();
- echo templatereplace(file_get_contents(sGetTemplatePath($defaulttemplate)."/startpage.pstpl"),array(),$data,'survey[503]');
-
- echo templatereplace(file_get_contents(sGetTemplatePath($defaulttemplate)."/surveylist.pstpl"),array(),$data,'survey[505]');
-
- echo templatereplace(file_get_contents(sGetTemplatePath($defaulttemplate)."/endpage.pstpl"),array(),$data,'survey[507]');
- doFooter();
- exit;
- }
- // Get token
- if (!isset($token))
- {
- $token=$clienttoken;
- }
- //GET BASIC INFORMATION ABOUT THIS SURVEY
- $totalBoilerplatequestions =0;
- $thissurvey=getSurveyInfo($surveyid, $_SESSION['s_lang']);
+ //SEE IF SURVEY USES TOKENS AND GROUP TOKENS
+ $i = 0; //$tokensexist = 0;
+ if ($surveyExists == 1 && tableExists('tokens_'.$thissurvey['sid']))
+ {
+ $tokensexist = 1;
- if (isset($param['newtest']) && $param['newtest'] == "Y")
- {
- //Removes any existing timer cookies so timers will start again
- setcookie ("limesurvey_timers", "", time() - 3600);
- }
+ }
+ else
+ {
+ $tokensexist = 0;
+ unset($_POST['token']);
+ unset($param['token']);
+ unset($token);
+ unset($clienttoken);
+ }
- //SEE IF SURVEY USES TOKENS AND GROUP TOKENS
- $i = 0; //$tokensexist = 0;
- if ($surveyexists == 1 && tableExists('tokens_'.$thissurvey['sid']))
- {
- $tokensexist = 1;
- }
- else
- {
- $tokensexist = 0;
- unset($_POST['token']);
- unset($param['token']);
- unset($token);
- unset($clienttoken);
- }
+ //SET THE TEMPLATE DIRECTORY
+ if (!$thissurvey['templatedir'])
+ {
+ $thistpl = sGetTemplatePath($defaulttemplate);
+ }
+ else
+ {
+ $thistpl = sGetTemplatePath($thissurvey['templatedir']);
+ }
+ $timeadjust = $this->config->item("timeadjust");
+ //MAKE SURE SURVEY HASN'T EXPIRED
+ if ($thissurvey['expiry']!='' and date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust)>$thissurvey['expiry'] && $thissurvey['active']!='N')
+ {
+ sendcacheheaders();
+ doHeader();
- //SET THE TEMPLATE DIRECTORY
- if (!$thissurvey['templatedir'])
- {
- $thistpl=sGetTemplatePath($defaulttemplate);
- }
- else
- {
- $thistpl=sGetTemplatePath($thissurvey['templatedir']);
- }
+ $redata = compact(array_keys(get_defined_vars()));
+ $this->_printTemplateContent($thistpl.'/startpage.pstpl', $redata, __LINE__);
+ $this->_printMessage(
+ $clang->gT("Error"),
+ $clang->gT("This survey is no longer available."),
+ sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail'])
+ );
+
+ $this->_killPage($redata, __LINE__, $thistpl);
+ }
+ //MAKE SURE SURVEY IS ALREADY VALID
+ if ($thissurvey['startdate']!='' and date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust)<$thissurvey['startdate'] && $thissurvey['active']!='N')
+ {
+ sendcacheheaders();
+ doHeader();
- $timeadjust = $this->config->item("timeadjust");
- //MAKE SURE SURVEY HASN'T EXPIRED
- if ($thissurvey['expiry']!='' and date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust)>$thissurvey['expiry'] && $thissurvey['active']!='N')
- {
+ $redata = compact(array_keys(get_defined_vars()));
+ $this->_printTemplateContent($thistpl.'/startpage.pstpl', $redata, __LINE__);
+ $this->_printMessage(
+ $clang->gT("Error"),
+ $clang->gT("This survey is not yet started."),
+ sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail'])
+ );
+
+ $this->_killPage($redata, __LINE__, $thistpl);
+ }
- sendcacheheaders();
- doHeader();
+ //CHECK FOR PREVIOUSLY COMPLETED COOKIE
+ //If cookies are being used, and this survey has been completed, a cookie called "PHPSID[sid]STATUS" will exist (ie: SID6STATUS) and will have a value of "COMPLETE"
+ $cookiename="PHPSID".returnglobal('sid')."STATUS";
+ if (isset($_COOKIE[$cookiename]) && $_COOKIE[$cookiename] == "COMPLETE" && $thissurvey['usecookie'] == "Y" && $tokensexist != 1 && (!isset($param['newtest']) || $param['newtest'] != "Y"))
+ {
+ sendcacheheaders();
+ doHeader();
$redata = compact(array_keys(get_defined_vars()));
- echo templatereplace(file_get_contents("$thistpl/startpage.pstpl"),array(),$redata,'survey[569]');
- echo "\t\n"
- ."\t
\n"
- ."\t".$clang->gT("This survey is no longer available.")."
\n"
- ."\t".sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail']).".
\n"
- ."\t
\n"
- ."\t
\n";
-
- echo templatereplace(file_get_contents("$thistpl/endpage.pstpl"),array(),$redata,'survey[577]');
- doFooter();
- exit;
- }
+ $this->_printTemplateContent($thistpl.'/startpage.pstpl', $redata, __LINE__);
+ $this->_printMessage(
+ $clang->gT("Error"),
+ $clang->gT("You have already completed this survey."),
+ sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail'])
+ );
+
+ $this->_killPage($redata, __LINE__, $thistpl);
+ }
- //MAKE SURE SURVEY IS ALREADY VALID
- if ($thissurvey['startdate']!='' and date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust)<$thissurvey['startdate'] && $thissurvey['active']!='N')
- {
- sendcacheheaders();
- doHeader();
- $redata = compact(array_keys(get_defined_vars()));
- echo templatereplace(file_get_contents("$thistpl/startpage.pstpl"),array(),$redata,'survey[589]');
- echo "\t\n"
- ."\t
\n"
- ."\t".$clang->gT("This survey is not yet started.")."
\n"
- ."\t".sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail']).".
\n"
- ."\t
\n"
- ."\t
\n";
-
- echo templatereplace(file_get_contents("$thistpl/endpage.pstpl"),array(),$redata,'survey[597]');
- doFooter();
- exit;
- }
+ //CHECK IF SURVEY ID DETAILS HAVE CHANGED
+ if (isset($_SESSION['oldsid']))
+ {
+ $oldsid=$_SESSION['oldsid'];
+ }
- //CHECK FOR PREVIOUSLY COMPLETED COOKIE
- //If cookies are being used, and this survey has been completed, a cookie called "PHPSID[sid]STATUS" will exist (ie: SID6STATUS) and will have a value of "COMPLETE"
- $cookiename="PHPSID".returnglobal('sid')."STATUS";
- if (isset($_COOKIE[$cookiename]) && $_COOKIE[$cookiename] == "COMPLETE" && $thissurvey['usecookie'] == "Y" && $tokensexist != 1 && (!isset($param['newtest']) || $param['newtest'] != "Y"))
- {
- sendcacheheaders();
- doHeader();
+ if (!isset($oldsid))
+ {
+ $_SESSION['oldsid'] = $surveyid;
+ }
- $redata = compact(array_keys(get_defined_vars()));
- echo templatereplace(file_get_contents("$thistpl/startpage.pstpl"),array(),$redata,'survey[611]');
- echo "\t\n"
- ."\t
\n"
- ."\t".$clang->gT("Error")."
\n"
- ."\t".$clang->gT("You have already completed this survey.")."
\n"
- ."\t".sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail'])."\n"
- ."\t
\n"
- ."\t
\n";
-
- echo templatereplace(file_get_contents("$thistpl/endpage.pstpl"),array(),$redata,'survey[620]');
- doFooter();
- exit;
- }
+ if (isset($oldsid) && $oldsid && $oldsid != $surveyid)
+ {
+ $savesessionvars=Array();
+ if (isset($_SESSION['USER_RIGHT_PREVIEW']))
+ {
+ $savesessionvars["USER_RIGHT_PREVIEW"]=$surveyid;
+ $savesessionvars["loginID"]=$_SESSION['loginID'];
+ $savesessionvars["user"]=$_SESSION['user'];
+ }
+ session_unset();
+ $_SESSION['oldsid']=$surveyid;
+ foreach ($savesessionvars as $sesskey => $sessval)
+ {
+ $_SESSION[$sesskey]=$sessval;
+ }
+ }
- //CHECK IF SURVEY ID DETAILS HAVE CHANGED
- if (isset($_SESSION['oldsid']))
- {
- $oldsid=$_SESSION['oldsid'];
- }
- if (!isset($oldsid))
- {
- $_SESSION['oldsid'] = $surveyid;
- }
+ if (isset($_GET['loadall']) && $_GET['loadall'] == "reload")
+ {
+ if (returnglobal('loadname') && returnglobal('loadpass'))
+ {
+ $_POST['loadall']="reload";
+ }
+ }
- if (isset($oldsid) && $oldsid && $oldsid != $surveyid)
- {
- $savesessionvars=Array();
- if (isset($_SESSION['USER_RIGHT_PREVIEW']))
- {
- $savesessionvars["USER_RIGHT_PREVIEW"]=$surveyid;
- $savesessionvars["loginID"]=$_SESSION['loginID'];
- $savesessionvars["user"]=$_SESSION['user'];
- }
- session_unset();
- $_SESSION['oldsid']=$surveyid;
- foreach ($savesessionvars as $sesskey => $sessval)
- {
- $_SESSION[$sesskey]=$sessval;
- }
- }
+ //LOAD SAVED SURVEY
+ if (isset($_POST['loadall']) && $_POST['loadall'] == "reload")
+ {
+ $errormsg="";
+ if ( !isset($param['loadname']) || $param['loadname'] == null )
+ {
+ $errormsg .= $clang->gT("You did not provide a name")."
\n";
+ }
+ if (!isset($param['loadpass']) || $param['loadpass'] == null )
+ {
+ $errormsg .= $clang->gT("You did not provide a password")."
\n";
+ }
+ // if security question answer is incorrect
+ // Not called if scid is set in GET params (when using email save/reload reminder URL)
+ if (function_exists("ImageCreate") && captcha_enabled('saveandloadscreen',$thissurvey['usecaptcha']))
+ {
+ if ( (!isset($_POST['loadsecurity']) ||
+ !isset($_SESSION['secanswer']) ||
+ $_POST['loadsecurity'] != $_SESSION['secanswer']) &&
+ !isset($_GET['scid']))
+ {
+ $errormsg .= $clang->gT("The answer to the security question is incorrect.")."
\n";
+ }
+ }
+ // Load session before loading the values from the saved data
+ if (isset($_GET['loadall']))
+ {
+ buildsurveysession();
+ }
- if (isset($_GET['loadall']) && $_GET['loadall'] == "reload")
- {
- if (returnglobal('loadname') && returnglobal('loadpass'))
- {
- $_POST['loadall']="reload";
- }
- }
+ $_SESSION['holdname'] = $param['loadname']; //Session variable used to load answers every page.
+ $_SESSION['holdpass'] = $param['loadpass']; //Session variable used to load answers every page.
- //LOAD SAVED SURVEY
- if (isset($_POST['loadall']) && $_POST['loadall'] == "reload")
- {
- $errormsg="";
- // if (loadname is not set) or if ((loadname is set) and (loadname is NULL))
- if (!isset($loadname) || (isset($loadname) && ($loadname == null)))
- {
- $errormsg .= $clang->gT("You did not provide a name")."
\n";
- }
- // if (loadpass is not set) or if ((loadpass is set) and (loadpass is NULL))
- if (!isset($loadpass) || (isset($loadpass) && ($loadpass == null)))
- {
- $errormsg .= $clang->gT("You did not provide a password")."
\n";
- }
-
- // if security question answer is incorrect
- // Not called if scid is set in GET params (when using email save/reload reminder URL)
- if (function_exists("ImageCreate") && captcha_enabled('saveandloadscreen',$thissurvey['usecaptcha']))
- {
- if ( (!isset($_POST['loadsecurity']) ||
- !isset($_SESSION['secanswer']) ||
- $_POST['loadsecurity'] != $_SESSION['secanswer']) &&
- !isset($_GET['scid']))
- {
- $errormsg .= $clang->gT("The answer to the security question is incorrect.")."
\n";
- }
- }
-
- // Load session before loading the values from the saved data
- if (isset($_GET['loadall']))
- {
- buildsurveysession();
- }
-
- $_SESSION['holdname']=$loadname; //Session variable used to load answers every page.
- $_SESSION['holdpass']=$loadpass; //Session variable used to load answers every page.
-
- if ($errormsg == "") loadanswers();
- $move = "movenext";
-
- if ($errormsg)
- {
- $_POST['loadall'] = $clang->gT("Load Unfinished Survey");
- }
- }
- //Allow loading of saved survey
- if (isset($_POST['loadall']) && $_POST['loadall'] == $clang->gT("Load Unfinished Survey"))
- {
- $vars = compact(array_keys(get_defined_vars()));
- $this->load->library("load_answers");
- $this->load_answers->run($vars);
- }
+ if ($errormsg == "") loadanswers();
+ $move = "movenext";
+ if ($errormsg)
+ {
+ $_POST['loadall'] = $clang->gT("Load Unfinished Survey");
+ }
+ }
+ //Allow loading of saved survey
+ if (isset($_POST['loadall']) && $_POST['loadall'] == $clang->gT("Load Unfinished Survey"))
+ {
+ $redata = compact(array_keys(get_defined_vars()));
+ $this->load->library("load_answers");
+ $this->load_answers->run($redata);
+ }
- //Check if TOKEN is used for EVERY PAGE
- //This function fixes a bug where users able to submit two surveys/votes
- //by checking that the token has not been used at each page displayed.
- // bypass only this check at first page (Step=0) because
- // this check is done in buildsurveysession and error message
- // could be more interresting there (takes into accound captcha if used)
- if ($tokensexist == 1 && isset($token) && $token &&
- isset($_SESSION['step']) && $_SESSION['step']>0 && db_tables_exist($dbprefix.'tokens_'.$surveyid))
- {
- //check if tokens actually haven't been already used
- $areTokensUsed = usedTokens(trim(strip_tags(returnglobal('token'))),$surveyid);
- // check if token actually does exist
- // check also if it is allowed to change survey after completion
- if ($thissurvey['alloweditaftercompletion'] == 'Y' ) {
- $tkquery = "SELECT * FROM ".$this->db->dbprefix('tokens_'.$surveyid)." WHERE token=".$this->db->escape($token)." ";
- } else {
- $tkquery = "SELECT * FROM ".$this->db->dbprefix('tokens_'.$surveyid)." WHERE token=".$this->db->escape($token)." AND (completed = 'N' or completed='')";
- }
- $tkresult = db_execute_assoc($tkquery); //Checked
- $tokendata = $tkresult->row_array();
- if ($tkresult->num_rows()==0 || $areTokensUsed)
- {
- sendcacheheaders();
- doHeader();
- //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
+
+ //Check if TOKEN is used for EVERY PAGE
+ //This function fixes a bug where users able to submit two surveys/votes
+ //by checking that the token has not been used at each page displayed.
+ // bypass only this check at first page (Step=0) because
+ // this check is done in buildsurveysession and error message
+ // could be more interresting there (takes into accound captcha if used)
+ if ($tokensexist == 1 && isset($token) && $token &&
+ isset($_SESSION['step']) && $_SESSION['step']>0 && db_tables_exist($this->db->dbprefix('tokens_'.$surveyid)))
+ {
+ //check if tokens actually haven't been already used
+ $areTokensUsed = usedTokens(trim(strip_tags(returnglobal('token'))),$surveyid);
+ // check if token actually does exist
+ // check also if it is allowed to change survey after completion
+ if ($thissurvey['alloweditaftercompletion'] == 'Y' ) {
+ $tkquery = "SELECT * FROM ".$this->db->dbprefix('tokens_'.$surveyid)." WHERE token=".$this->db->escape($token)." ";
+ } else {
+ $tkquery = "SELECT * FROM ".$this->db->dbprefix('tokens_'.$surveyid)." WHERE token=".$this->db->escape($token)." AND (completed = 'N' or completed='')";
+ }
+ $tkresult = db_execute_assoc($tkquery); //Checked
+ $tokendata = $tkresult->row_array();
+ if ($tkresult->num_rows()==0 || $areTokensUsed)
+ {
+ sendcacheheaders();
+ doHeader();
+ //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
$redata = compact(array_keys(get_defined_vars()));
- echo templatereplace(file_get_contents("$thistpl/startpage.pstpl"),array(),$redata,'survey[745]');
- echo templatereplace(file_get_contents("$thistpl/survey.pstpl"),array(),$redata,'survey[746]');
- echo "\t\n"
- ."\t
\n"
- ."\t".$clang->gT("This is a controlled survey. You need a valid token to participate.")."
\n"
- ."\t".$clang->gT("The token you have provided is either not valid, or has already been used.")."\n"
- ."\t".sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']
- ." ("
- ."{$thissurvey['adminemail']})")."\n"
- ."\t
\n"
- ."\t
\n";
-
- echo templatereplace(file_get_contents("$thistpl/endpage.pstpl"),array(),$redata,'survey[757]');
- killSession();
- doFooter();
- exit;
- }
- }
- if ($tokensexist == 1 && isset($token) && $token && db_tables_exist($dbprefix.'tokens_'.$surveyid)) //check if token is in a valid time frame
- {
- // check also if it is allowed to change survey after completion
- if ($thissurvey['alloweditaftercompletion'] == 'Y' ) {
- $tkquery = "SELECT * FROM ".$this->db->dbprefix('tokens_'.$surveyid)." WHERE token=".$this->db->escape($token)." ";
- } else {
- $tkquery = "SELECT * FROM ".$this->db->dbprefix('tokens_'.$surveyid)." WHERE token=".$this->db->escape($token)." AND (completed = 'N' or completed='')";
- }
- $tkresult = db_execute_assoc($tkquery); //Checked
- $tokendata = $tkresult->row_array();
- if (isset($tokendata['validfrom']) && (trim($tokendata['validfrom'])!='' && $tokendata['validfrom']>date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust)) ||
- isset($tokendata['validuntil']) && (trim($tokendata['validuntil'])!='' && $tokendata['validuntil']_printTemplateContent($thistpl.'/startpage.pstpl', $redata, __LINE__);
+ $this->_printTemplateContent($thistpl.'/survey.pstpl', $redata, __LINE__);
+ $this->_printMessage(
+ null,
+ $clang->gT("This is a controlled survey. You need a valid token to participate."),
+ sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']." ("."{$thissurvey['adminemail']})")
+ );
+
+ $this->_killPage($redata, __LINE__, $thistpl, true);
+ }
+ }
+ if ($tokensexist == 1 && isset($token) && $token && db_tables_exist($this->db->dbprefix('tokens_'.$surveyid))) //check if token is in a valid time frame
+ {
+ // check also if it is allowed to change survey after completion
+ if ($thissurvey['alloweditaftercompletion'] == 'Y' ) {
+ $tkquery = "SELECT * FROM ".$this->db->dbprefix('tokens_'.$surveyid)." WHERE token=".$this->db->escape($token)." ";
+ } else {
+ $tkquery = "SELECT * FROM ".$this->db->dbprefix('tokens_'.$surveyid)." WHERE token=".$this->db->escape($token)." AND (completed = 'N' or completed='')";
+ }
+ $tkresult = db_execute_assoc($tkquery); //Checked
+ $tokendata = $tkresult->row_array();
+ if (isset($tokendata['validfrom']) && (trim($tokendata['validfrom'])!='' && $tokendata['validfrom']>date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust)) ||
+ isset($tokendata['validuntil']) && (trim($tokendata['validuntil'])!='' && $tokendata['validuntil']\n"
- ."\t\n"
- ."\t".$clang->gT("We are sorry but you are not allowed to enter this survey.")."
\n"
- ."\t".$clang->gT("Your token seems to be valid but can be used only during a certain time period.")."
\n"
- ."\t".sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']
- ." ("
- ."{$thissurvey['adminemail']})")."\n"
- ."\t
\n"
- ."\t\n";
-
- echo templatereplace(file_get_contents("$thistpl/endpage.pstpl"),array(),$redata,'survey[793]');
- doFooter();
- killSession();
- exit;
- }
- }
+ $this->_printTemplateContent($thistpl.'/startpage.pstpl', $redata, __LINE__);
+ $this->_printTemplateContent($thistpl.'/survey.pstpl', $redata, __LINE__);
+ $this->_printMessage(
+ null,
+ $clang->gT("We are sorry but you are not allowed to enter this survey."),
+ $clang->gT("Your token seems to be valid but can be used only during a certain time period."),
+ sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']." ("."{$thissurvey['adminemail']})")
+ );
+ $this->_killPage($redata, __LINE__, $thistpl, true);
+ }
+ }
- //Clear session and remove the incomplete response if requested.
- if (isset($move) && $move == "clearall")
- {
- $s_lang = $_SESSION['s_lang'];
- if (isset($_SESSION['srid']))
- {
- // find out if there are any fuqt questions - checked
- $fieldmap = createFieldMap($surveyid);
- foreach ($fieldmap as $field)
- {
- if ($field['type'] == "|" && !strpos($field['fieldname'], "_filecount"))
- {
- if (!isset($qid)) { $qid = array(); }
- $qid[] = $field['fieldname'];
- }
- }
-
- // if yes, extract the response json to those questions
- if (isset($qid))
- {
- $query = "SELECT * FROM ".$this->db->dbprefix("survey_".$surveyid)." WHERE id=".$_SESSION['srid'];
- $result = db_execute_assoc($query);
- foreach($result->result_array() as $row)
- {
- foreach ($qid as $question)
- {
- $json = $row[$question];
- if ($json == "" || $json == NULL)
- continue;
-
- // decode them
- $phparray = json_decode($json);
-
- foreach ($phparray as $metadata)
- {
- $target = $this->config->item("uploaddir")."/surveys/".$surveyid."/files/";
- // delete those files
- unlink($target.$metadata->filename);
- }
- }
- }
- }
- // done deleting uploaded files
-
-
- // delete the response but only if not already completed
- db_execute_assoc('DELETE FROM '.$this->db->dbprefix('survey_'.$surveyid).' WHERE id='.$_SESSION['srid']." AND submitdate IS NULL");
-
- // also delete a record from saved_control when there is one
- db_execute_assoc('DELETE FROM '.$this->db->dbprefix('saved_control'). ' WHERE srid='.$_SESSION['srid'].' AND sid='.$surveyid);
- }
- session_unset();
- session_destroy();
- setcookie(session_name(),"EXPIRED",time()-120);
- sendcacheheaders();
- if (isset($_GET['redirect']))
- {
- session_write_close();
- header("Location: {$_GET['redirect']}");
- }
- doHeader();
+
+
+ //Clear session and remove the incomplete response if requested.
+ if (isset($move) && $move == "clearall")
+ {
+ $s_lang = $_SESSION['s_lang'];
+ if (isset($_SESSION['srid']))
+ {
+ // find out if there are any fuqt questions - checked
+ $fieldmap = createFieldMap($surveyid);
+ foreach ($fieldmap as $field)
+ {
+ if ($field['type'] == "|" && !strpos($field['fieldname'], "_filecount"))
+ {
+ if (!isset($qid)) { $qid = array(); }
+ $qid[] = $field['fieldname'];
+ }
+ }
+
+ // if yes, extract the response json to those questions
+ if (isset($qid))
+ {
+ $query = "SELECT * FROM ".$this->db->dbprefix("survey_".$surveyid)." WHERE id=".$_SESSION['srid'];
+ $result = db_execute_assoc($query);
+ foreach($result->result_array() as $row)
+ {
+ foreach ($qid as $question)
+ {
+ $json = $row[$question];
+ if ($json == "" || $json == NULL)
+ continue;
+
+ // decode them
+ $phparray = json_decode($json);
+
+ foreach ($phparray as $metadata)
+ {
+ $target = $this->config->item("uploaddir")."/surveys/".$surveyid."/files/";
+ // delete those files
+ unlink($target.$metadata->filename);
+ }
+ }
+ }
+ }
+ // done deleting uploaded files
+
+
+ // delete the response but only if not already completed
+ db_execute_assoc('DELETE FROM '.$this->db->dbprefix('survey_'.$surveyid).' WHERE id='.$_SESSION['srid']." AND submitdate IS NULL");
+
+ // also delete a record from saved_control when there is one
+ db_execute_assoc('DELETE FROM '.$this->db->dbprefix('saved_control'). ' WHERE srid='.$_SESSION['srid'].' AND sid='.$surveyid);
+ }
+ session_unset();
+ session_destroy();
+ setcookie(session_name(),"EXPIRED",time()-120);
+ sendcacheheaders();
+ if (isset($_GET['redirect']))
+ {
+ session_write_close();
+ header("Location: {$_GET['redirect']}");
+ }
+ doHeader();
$redata = compact(array_keys(get_defined_vars()));
- echo templatereplace(file_get_contents("$thistpl/startpage.pstpl"),array(),$redata,'survey[864]');
- echo "\n\n\n"
- ."\t\n\n";
-
- //Present the clear all page using clearall.pstpl template
- echo templatereplace(file_get_contents("$thistpl/clearall.pstpl"),array(),$redata,'survey[876]');
-
- echo templatereplace(file_get_contents("$thistpl/endpage.pstpl"),array(),$redata,'survey[878]');
- doFooter();
- exit;
- }
+ $this->_printTemplateContent($thistpl.'/startpage.pstpl', $redata, __LINE__);
+ echo "\n\n\n"
+ ."\t\n\n";
+
+ //Present the clear all page using clearall.pstpl template
+ $this->_printTemplateContent($thistpl.'/clearall.pstpl', $redata, __LINE__);
+
+ $this->_killPage($redata, __LINE__, $thistpl);
+ }
- if (isset($param['newtest']) && $param['newtest'] == "Y")
- {
- $savesessionvars=Array();
- if (isset($_SESSION['USER_RIGHT_PREVIEW']))
- {
- $savesessionvars["USER_RIGHT_PREVIEW"]=$surveyid;
- $savesessionvars["loginID"]=$_SESSION['loginID'];
- $savesessionvars["user"]=$_SESSION['user'];
- }
- session_unset();
- $_SESSION['oldsid']=$surveyid;
- foreach ($savesessionvars as $sesskey => $sessval)
- {
- $_SESSION[$sesskey]=$sessval;
- }
- //DELETE COOKIE (allow to use multiple times)
- setcookie($cookiename, "INCOMPLETE", time()-120);
- //echo "Reset Cookie!";
- }
+ if (isset($param['newtest']) && $param['newtest'] == "Y")
+ {
+ $savesessionvars=Array();
+ if (isset($_SESSION['USER_RIGHT_PREVIEW']))
+ {
+ $savesessionvars["USER_RIGHT_PREVIEW"]=$surveyid;
+ $savesessionvars["loginID"]=$_SESSION['loginID'];
+ $savesessionvars["user"]=$_SESSION['user'];
+ }
+ session_unset();
+ $_SESSION['oldsid']=$surveyid;
+ foreach ($savesessionvars as $sesskey => $sessval)
+ {
+ $_SESSION[$sesskey]=$sessval;
+ }
+ //DELETE COOKIE (allow to use multiple times)
+ setcookie($cookiename, "INCOMPLETE", time()-120);
+ //echo "Reset Cookie!";
+ }
- //Check to see if a refering URL has been captured.
- GetReferringUrl();
- // Let's do this only if
- // - a saved answer record hasn't been loaded through the saved feature
- // - the survey is not anonymous
- // - the survey is active
- // - a token information has been provided
- // - the survey is setup to allow token-response-persistence
+ //Check to see if a refering URL has been captured.
+ GetReferringUrl();
+ // Let's do this only if
+ // - a saved answer record hasn't been loaded through the saved feature
+ // - the survey is not anonymous
+ // - the survey is active
+ // - a token information has been provided
+ // - the survey is setup to allow token-response-persistence
- if ($thissurvey['tokenanswerspersistence'] == 'Y' && !isset($_SESSION['srid']) && $thissurvey['anonymized'] == "N" && $thissurvey['active'] == "Y" && isset($token) && $token !='')
- {
+ if ($thissurvey['tokenanswerspersistence'] == 'Y' && !isset($_SESSION['srid']) && $thissurvey['anonymized'] == "N" && $thissurvey['active'] == "Y" && isset($token) && $token !='')
+ {
- // load previous answers if any (dataentry with nosubmit)
- $srquery="SELECT id FROM {$thissurvey['tablename']}"
- . " WHERE {$thissurvey['tablename']}.token='".$this->db->escape($token)."' order by id desc";
+ // load previous answers if any (dataentry with nosubmit)
+ $srquery="SELECT id FROM {$thissurvey['tablename']}"
+ . " WHERE {$thissurvey['tablename']}.token='".$this->db->escape($token)."' order by id desc";
$result = db_select_limit_assoc($srquery,1);
if ($result->num_rows()>0)
@@ -941,67 +755,303 @@ function action()
$row=reset($result->result_array());
if($row['submitdate']=='' || ($row['submitdate']!='' && $thissurvey['alloweditaftercompletion'] == 'Y'))
$_SESSION['srid'] = $row['id'];
- }
- buildsurveysession();
- loadanswers();
- }
+ }
+ buildsurveysession();
+ loadanswers();
+ }
- // SAVE POSTED ANSWERS TO DATABASE IF MOVE (NEXT,PREV,LAST, or SUBMIT) or RETURNING FROM SAVE FORM
- if (isset($move) || isset($_POST['saveprompt']))
- {
- $args = compact(array_keys(get_defined_vars()));
- //save.php
- $this->load->library("Save");
- $this->save->run($args);
-
- // RELOAD THE ANSWERS INCASE SOMEONE ELSE CHANGED THEM
- if ($thissurvey['active'] == "Y" &&
- ( $thissurvey['allowsave'] == "Y" || $thissurvey['tokenanswerspersistence'] == "Y") )
- {
- loadanswers();
- }
- }
+ // SAVE POSTED ANSWERS TO DATABASE IF MOVE (NEXT,PREV,LAST, or SUBMIT) or RETURNING FROM SAVE FORM
+ if (isset($move) || isset($_POST['saveprompt']))
+ {
+ $redata = compact(array_keys(get_defined_vars()));
+ //save.php
+ $this->load->library("Save");
+ $this->save->run($redata);
- if (isset($_REQUEST['action']) && ($_REQUEST['action'] == 'previewgroup')){
- $thissurvey['format'] = 'G';
- buildsurveysession();
- }
+ // RELOAD THE ANSWERS INCASE SOMEONE ELSE CHANGED THEM
+ if ($thissurvey['active'] == "Y" &&
+ ( $thissurvey['allowsave'] == "Y" || $thissurvey['tokenanswerspersistence'] == "Y") )
+ {
+ loadanswers();
+ }
+ }
- sendcacheheaders();
+ if (isset($_REQUEST['action']) && ($_REQUEST['action'] == 'previewgroup')){
+ $thissurvey['format'] = 'G';
+ buildsurveysession();
+ }
- //Send local variables to the appropriate survey type
- $args = compact(array_keys(get_defined_vars()));
+ sendcacheheaders();
- //CALL APPROPRIATE SCRIPT
- switch ($thissurvey['format'])
- {
- case "A": //All in one
- //require_once("survey.php");
- $this->load->library("Survey_format");
- $this->survey_format->run($args);
- break;
- case "S": //One at a time
- //require_once("question.php");
- $this->load->library("Question_format");
- $this->question_format->run($args);
- break;
- case "G": //Group at a time
- $this->load->library("Group_format");
- $this->group_format->run($args);
- break;
- default:
- //require_once("question.php");
- $this->load->library("Question_format");
- $this->question_format->run($args);
- }
+ //Send local variables to the appropriate survey type
+ $redata = compact(array_keys(get_defined_vars()));
+
+ //CALL APPROPRIATE SCRIPT
+ switch ($thissurvey['format'])
+ {
+ case "A": //All in one
+ //require_once("survey.php");
+ $this->load->library("Survey_format");
+ $this->survey_format->run($redata);
+ break;
+ case "S": //One at a time
+ //require_once("question.php");
+ $this->load->library("Question_format");
+ $this->question_format->run($redata);
+ break;
+ case "G": //Group at a time
+ $this->load->library("Group_format");
+ $this->group_format->run($redata);
+ break;
+ default:
+ //require_once("question.php");
+ $this->load->library("Question_format");
+ $this->question_format->run($redata);
+ }
if (isset($_POST['saveall']) || isset($flashmessage))
{
echo "";
}
+ }
+
+ function _getParameters($args = array(), $post = array())
+ {
+ $param = array();
+ if($args[0]==__CLASS__) array_shift($args);
+ if(count($args)%2 == 0) {
+ for ($i = 0; $i < count($args); $i+=2) {
+ //Sanitize input from URL with returnglobal
+ $param[$args[$i]] = returnglobal($args[$i], $args[$i+1]);
+ }
+ }
+
+ if( !isset($param['action']) )
+ $param['action'] = isset($post['action']) ? $post['action'] : null;
+ if( !isset($param['newtest']) )
+ $param['newtest'] = isset($post['newtest']) ? $post['newtest'] : null;
+ if( !isset($param['gid']) )
+ $param['gid'] = isset($post['gid']) ? $post['gid'] : null;
+
+ if ( !isset($param['sid']) )
+ $param['sid'] = returnglobal('sid');
+ if ( !isset($param['loadname']) )
+ $param['loadname'] = returnglobal('loadname');
+ if ( !isset($param['loadpass']) )
+ $param['loadpass'] = returnglobal('loadpass');
+ if ( !isset($param['scid']) )
+ $param['scid'] = returnglobal('scid');
+ if ( !isset($param['thisstep']) )
+ $param['thisstep'] = returnglobal('thisstep');
+ if ( !isset($param['move']) )
+ $param['move'] = returnglobal('move');
+ if ( !isset($param['token']) )
+ $param['token'] = returnglobal('token');
+
+ if ( !isset($param['thisstep']) )
+ $param['thisstep'] = '';
+
+ return $param;
+ }
+
+ function _getSessionName($surveyId)
+ {
+ // Compute the Session name
+ // Session name is based:
+ // * on this specific limesurvey installation (Value SessionName in DB)
+ // * on the surveyid (from Get or Post param). If no surveyid is given we are on the public surveys portal
+ $sSessionname = getGlobalSetting('SessionName');
+ if ($sSessionname != '')
+ {
+ if ($surveyId)
+ {
+ return $sSessionname.'-runtime-'.$surveyId;
+ }
+ return $sSessionname.'-runtime-publicportal';
+ }
+ return 'LimeSurveyRuntime-'.$surveyId;
+ }
+
+ function _setSessionToSurvey($surveyId)
+ {
+ $sSessionname = $this->_getSessionName($surveyId);
+
+ // Establish / Switch to survey session
+ // Import data from current session (if available) to survey
+ // session if the survey session has no data.
- }
+ $__SESSION = array(); // session data copy store
+ $oSess = new LS_PHP_Session();
+ if ($oSess->changeTo($sSessionname))
+ {
+ // Needed to call session_start() below.
+ $__SESSION =& $_SESSION; // reference current session data.
+ unset($_SESSION);
+ $_SESSION = array();
+ }
+ else
+ {
+ session_name($sSessionname);
+ }
+ unset($oSess);
+
+ session_set_cookie_params(0,$this->config->item("relativeurl"));
+ if (empty($_SESSION)) // the $_SESSION variable can be empty if register_globals is on
+ {
+ @session_start();
+ if (empty($_SESSION)) // if this session is new, import old session
+ {
+ $_SESSION = $__SESSION;
+ unset($__SESSION);
+ }
+ $this->session->bind_userdata(); // que?
+ }
+ }
+
+ function _loadRequiredHelpersAndLibraries()
+ {
+ //Load helpers, libraries and config vars
+ $this->load->helper("database");
+ $this->load->helper("frontend");
+ $this->load->helper("surveytranslator");
+ $this->load->library("Dtexts");
+ }
+
+ function _loadLimesurveyLang($mvSurveyIdOrBaseLang)
+ {
+ if ( is_int($mvSurveyIdOrBaseLang) )
+ {
+ $baselang = GetBaseLanguageFromSurveyID($surveyId);
+ }
+ else
+ {
+ $baselang = $mvSurveyIdOrBaseLang;
+ }
+
+ $this->load->library('Limesurvey_lang',array("langcode"=>$baselang));
+
+ return $this->limesurvey_lang;
+ }
+
+ function _surveyExistsAndIsActive($surveyId)
+ {
+ $isSurveyActive = false;
+ $surveyExists = false;
+
+ if ($surveyId)
+ {
+ $aRow = db_execute_assoc("SELECT active FROM ".$this->db->dbprefix('surveys')." WHERE sid='".$surveyId."'")->row_array();
+ if (isset($aRow['active']))
+ {
+ $surveyExists = true;
+ if($aRow['active'] == 'Y')
+ {
+ $isSurveyActive = true;
+ }
+ }
+ }
+
+ return array($surveyExists, $isSurveyActive);
+ }
+
+
+ function _isClientTokenDifferentFromSessionToken($clientToken)
+ {
+ return $clientToken != '' && isset($_SESSION['token']) && $clientToken != $_SESSION['token'];
+ }
+
+ function _isSurveyFinished()
+ {
+ return isset($_SESSION['finished']) && $_SESSION['finished'] === true;
+ }
+
+ function _isPreviewAction($param = array())
+ {
+ return isset($param['action']) && $param['action'] == 'previewgroup';
+ }
+
+ function _surveyCantBeViewedWithCurrentPreviewAccess($surveyid, $bIsSurveyActive, $bSurveyExists)
+ {
+ $bSurveyPreviewRequireAuth = $this->config->item('surveyPreview_require_Auth');
+ return $surveyid && $bIsSurveyActive === false && $bSurveyExists && isset($bSurveyPreviewRequireAuth) && $bSurveyPreviewRequireAuth == true && !$this->_canUserPreviewSurvey($surveyid);
+ }
+
+ function _canUserPreviewSurvey($surveyId)
+ {
+ if ( !isset($_SESSION['loginID'], $_SESSION['USER_RIGHT_SUPERADMIN']) )
+ return false;
+
+ $rightresult = db_execute_assoc(
+ "SELECT uid
+ FROM ".($this->db->dbprefix('survey_permissions'))."
+ WHERE sid = '".$this->db->escape($surveyId)."'
+ AND uid = '".$this->db->escape($_SESSION['loginID'])."'
+ GROUP BY uid");
+ if ($rightresult->num_rows() > 0 || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1)
+ {
+ return true;
+ }
+ return false;
+ }
+
+ function _killPage(&$redata, $iDebugLine, $sTemplateDir = null, $bKillSession = false)
+ {
+ if ( $sTemplateDir == null )
+ $sTemplateDir = $this->config->item("standardtemplaterootdir");
+
+ $this->_printTemplateContent($sTemplateDir.'/default/endpage.pstpl', $redata, $iDebugLine);
+ doFooter();
+ if ( $bKillSession )
+ killSession();
+ exit;
+ }
+
+ function _createNewUserSessionAndRedirect($surveyId, &$redata, $asMessage = array())
+ {
+ $baselang = GetBaseLanguageFromSurveyID($surveyId);
+ $this->load->library('Limesurvey_lang',array("langcode"=>$baselang));
+ $clang = $this->limesurvey_lang;
+ // Let's first regenerate a session id
+ killSession();
+ // Let's redirect the client to the same URL after having reseted the session
+ //header("Location: $rooturl/index.php?" .$_SERVER['QUERY_STRING']);
+ sendcacheheaders();
+ doHeader();
+
+ $template = $this->config->item("standardtemplaterootdir").'/default/startpage.pstpl';
+ $this->_printTemplateContent($template, $redata, __LINE__);
+
+ $this->_printMessage($asMessage);
+
+ $this->_killPage($redata, __LINE__);
+ }
+
+ function _printMessage($asLines)
+ {
+ if ( func_num_args() > 1 )
+ $asLines = func_get_args();
+
+ if ( size($asLines) == 0 )
+ return;
+
+ $sError = array_shift($asLines);
+
+ echo "\t\n";
+ echo "\t
\n";
+ if ( $sError != null )
+ {
+ echo "\t".$sError."
\n";
+ }
+ echo "\t".implode ("
\n\t", $asLines)."
\n";
+ echo "\t
\n";
+ echo "\t
\n";
+ }
+
+ function _printTemplateContent($sTemplateFile, &$redata, $iDebugLine = -1)
+ {
+ echo templatereplace(file_get_contents($sTemplateFile),array(),$redata,'survey['.$iDebugLine.']');
+ }
}
-/* End of file welcome.php */
-/* Location: ./application/controllers/welcome.php */
\ No newline at end of file
+/* End of file survey.php */
+/* Location: ./application/controllers/survey.php */
\ No newline at end of file
diff --git a/application/helpers/replacements_helper.php b/application/helpers/replacements_helper.php
index bd87a263349..1fae9fe12a9 100644
--- a/application/helpers/replacements_helper.php
+++ b/application/helpers/replacements_helper.php
@@ -60,7 +60,7 @@ function templatereplace($line, $replacements=array(),&$redata=array(), $debugSr
'thissurvey',
'token',
'totalBoilerplatequestions',
- 'totalquestions ',
+ 'totalquestions',
);
$varsPassed = array();
diff --git a/application/libraries/Group_format.php b/application/libraries/Group_format.php
index 12bee4fce93..5baab7703a2 100644
--- a/application/libraries/Group_format.php
+++ b/application/libraries/Group_format.php
@@ -14,11 +14,11 @@
*/
class Group_format {
-
+
function run($args) {
-
+
global $surveyid, $thissurvey, $totalquestions, $token;
-
+
extract($args);
@@ -29,8 +29,8 @@ function run($args) {
$_POST = $CI->input->post();
$allowmandbackwards = $CI->config->item("allowmandbackwards");
-
-
+
+
//Security Checked: POST, GET, SESSION, REQUEST, returnglobal, DB
$previewgrp = false;
if (isset($param['action']) && ($param['action']=='previewgroup')){
@@ -40,7 +40,7 @@ function run($args) {
if ($param['newtest']=="Y")
setcookie("limesurvey_timers", "0");
$show_empty_group = false;
-
+
if ($previewgrp)
{
$totalquestions = buildsurveysession($surveyid);
@@ -59,14 +59,14 @@ function run($args) {
if(isset($thissurvey['showwelcome']) && $thissurvey['showwelcome'] == 'N') {
//If explicitply set, hide the welcome screen
$_SESSION['step'] = 1;
- }
+ }
}
-
+
if (!isset($_SESSION['totalsteps'])) {$_SESSION['totalsteps']=0;}
if (!isset($_SESSION['maxstep'])) {$_SESSION['maxstep']=0;}
if (!isset($gl)) {$gl=array('null');}
$_SESSION['prevstep']=$_SESSION['step'];
-
+
//Move current step ###########################################################################
if (isset($move) && $move == 'moveprev' && ($thissurvey['allowprev']=='Y' || $thissurvey['allowjumps']=='Y'))
{
@@ -83,18 +83,18 @@ function run($args) {
if ($move > 0 && (($move <= $_SESSION['step']) || (isset($_SESSION['maxstep']) && $move <= $_SESSION['maxstep'])))
$_SESSION['step'] = $move;
}
-
+
// We do not keep the participant session anymore when the same browser is used to answer a second time a survey (let's think of a library PC for instance).
// Previously we used to keep the session and redirect the user to the
// submit page.
//if (isset($_SESSION['finished'])) {$move='movesubmit'; }
-
+
if ($_SESSION['step'] == 0) {
display_first_page();
exit;
}
-
-
+
+
//CHECK IF ALL MANDATORY QUESTIONS HAVE BEEN ANSWERED ############################################
//First, see if we are moving backwards or doing a Save so far, and its OK not to check:
if ($allowmandbackwards==1 && (
@@ -107,24 +107,24 @@ function run($args) {
{
$backok="N";
}
-
+
//Now, we check mandatory questions if necessary
//CHECK IF ALL CONDITIONAL MANDATORY QUESTIONS THAT APPLY HAVE BEEN ANSWERED
// TODO - Modify this to ensure that irrelevant mandatories are not required
$notanswered=addtoarray_single(checkmandatorys($move,$backok),checkconditionalmandatorys($move,$backok));
-
+
//CHECK INPUT
$notvalidated=aCheckInput($surveyid, $move, $backok);
-
+
// CHECK UPLOADED FILES
$filenotvalidated = checkUploadedFileValidity($surveyid, $move, $backok);
-
+
//SEE IF THIS GROUP SHOULD DISPLAY
$show_empty_group = false;
-
+
if ($_SESSION['step']==0)
$show_empty_group = true;
-
+
if (isset($move) && $_SESSION['step'] != 0 && $move != "movesubmit")
{
while(isset($_SESSION['grouplist'][$_SESSION['step']-1]) && checkgroupfordisplay($_SESSION['grouplist'][$_SESSION['step']-1][0],($thissurvey['anonymized']!='N'),$thissurvey['sid']) === false)
@@ -144,7 +144,7 @@ function run($args) {
// or create an empty page giving the user the explicit option to submit.
if (isset($show_empty_group_if_the_last_group_is_hidden) && $show_empty_group_if_the_last_group_is_hidden == true)
{
-
+
$show_empty_group = true;
break;
} else
@@ -156,7 +156,7 @@ function run($args) {
}
}
}
-
+
//SUBMIT ###############################################################################
if ((isset($move) && $move == "movesubmit") && (!isset($notanswered) || !$notanswered) && (!isset($notvalidated) || !$notvalidated ) && (!isset($filenotvalidated) || !$filenotvalidated))
{
@@ -168,7 +168,7 @@ function run($args) {
$_SESSION['insertarray'][] = "refurl";
}
}
-
+
//COMMIT CHANGES TO DATABASE
if ($thissurvey['active'] != "Y") //If survey is not active, don't really commit
{
@@ -181,19 +181,19 @@ function run($args) {
{
killSession();
}
-
+
sendcacheheaders();
doHeader();
$redata = compact(array_keys(get_defined_vars()));
echo templatereplace(file_get_contents("$thistpl/startpage.pstpl"),array(),$redata,'Group_format[189]');
-
+
//Check for assessments
if ($thissurvey['assessments']== "Y" && $assessments)
{
echo templatereplace(file_get_contents("$thistpl/assessment.pstpl"),array(),$redata,'Group_format[194]');
}
-
+
// fetch all filenames from $_SESSIONS['files'] and delete them all
// from the /upload/tmp/ directory
/*echo "";print_r($_SESSION);echo "
";
@@ -219,7 +219,7 @@ function run($args) {
$cookiename="PHPSID".returnglobal('sid')."STATUS";
setcookie("$cookiename", "COMPLETE", time() + 31536000); //Cookie will expire in 365 days
}
-
+
//Before doing the "templatereplace()" function, check the $thissurvey['url']
//field for limereplace stuff, and do transformations!
$thissurvey['surveyls_url']=dTexts::run($thissurvey['surveyls_url']);
@@ -228,7 +228,7 @@ function run($args) {
$redata = compact(array_keys(get_defined_vars()));
$content='';
$content .= templatereplace(file_get_contents("$thistpl/startpage.pstpl"),array(),$redata,'Group_format[230]');
-
+
//Check for assessments
if ($thissurvey['assessments']== "Y")
{
@@ -239,22 +239,22 @@ function run($args) {
$content .= templatereplace(file_get_contents("$thistpl/assessment.pstpl"),array(),$redata,'Group_format[238]');
}
}
-
+
//Update the token if needed and send a confirmation email
if (isset($clienttoken) && $clienttoken)
{
submittokens();
}
-
+
//Send notifications
-
+
SendSubmitNotifications();
-
+
$redata = compact(array_keys(get_defined_vars()));
$content='';
$content .= templatereplace(file_get_contents("$thistpl/startpage.pstpl"),array(),$redata,'Group_format[255]');
-
+
//echo $thissurvey['url'];
//Check for assessments
if ($thissurvey['assessments']== "Y")
@@ -266,8 +266,8 @@ function run($args) {
$content .= templatereplace(file_get_contents("$thistpl/assessment.pstpl"),array(),$redata,'Group_format[266]');
}
}
-
-
+
+
if (trim(strip_tags($thissurvey['surveyls_endtext']))=='')
{
$completed = "
".$clang->gT("Thank you!")."
\n\n"
@@ -277,7 +277,7 @@ function run($args) {
{
$completed = $thissurvey['surveyls_endtext'];
}
-
+
// Link to Print Answer Preview **********
if ($thissurvey['printanswers']=='Y')
{
@@ -287,9 +287,9 @@ function run($args) {
."
\n";
}
//*****************************************
-
+
if ($thissurvey['publicstatistics']=='Y' && $thissurvey['printanswers']=='Y') {$completed .='
'.$clang->gT("or");}
-
+
// Link to Public statistics **********
if ($thissurvey['publicstatistics']=='Y')
{
@@ -299,10 +299,10 @@ function run($args) {
."
\n";
}
//*****************************************
-
+
$_SESSION['finished']=true;
$_SESSION['sid']=$surveyid;
-
+
sendcacheheaders();
//Automatically redirect the page to the "url" setting for the survey
@@ -315,20 +315,20 @@ function run($args) {
$url=str_replace("{TOKEN}",$clienttoken, $url); // to activate the TOKEN in the END URL
$url=str_replace("{SID}", $surveyid, $url); // to activate the SID in the END URL
$url=str_replace("{LANG}", $clang->getlangcode(), $url); // to activate the LANG in the END URL
-
+
header("Location: {$url}");
}
-
-
+
+
//if($thissurvey['printanswers'] != 'Y' && $thissurvey['usecookie'] != 'Y' && $tokensexist !=1)
if($thissurvey['printanswers'] != 'Y')
{
killSession();
}
-
+
doHeader();
echo $content;
-
+
}
$redata = compact(array_keys(get_defined_vars()));
@@ -341,7 +341,7 @@ function run($args) {
}
//SEE IF $surveyid EXISTS ####################################################################
- if ($surveyexists <1)
+ if ($surveyExists <1)
{
//SURVEY DOES NOT EXIST. POLITELY EXIT.
$redata = compact(array_keys(get_defined_vars()));
@@ -352,14 +352,14 @@ function run($args) {
doFooter();
exit;
}
-
+
//GET GROUP DETAILS
-
+
if ($previewgrp)
{
setcookie("limesurvey_timers", "0");
$_SESSION['step'] = $param['gid']+1;
-
+
foreach($_SESSION['grouplist'] as $index=>$group)
{
if ($group[0]==$param['gid']){
@@ -367,7 +367,7 @@ function run($args) {
break;
}
}
-
+
$gid=$_SESSION['grouplist'][$grouparrayno][0];
$groupname=$_SESSION['grouplist'][$grouparrayno][1];
$groupdescription=$_SESSION['grouplist'][$grouparrayno][2];
@@ -388,21 +388,21 @@ function run($args) {
$groupdescription=$_SESSION['grouplist'][$grouparrayno][2];
}
}
-
+
//Setup an inverted fieldnamesInfo for quick lookup of field answers.
$aFieldnamesInfoInv = aArrayInvert($_SESSION['fieldnamesInfo']);
if ($_SESSION['step'] > $_SESSION['maxstep'])
{
$_SESSION['maxstep'] = $_SESSION['step'];
}
-
+
//******************************************************************************************************
//PRESENT SURVEY
//******************************************************************************************************
-
-
-
-
+
+
+
+
//require_once("qanda.php"); //This should be qanda.php when finished
$CI->load->helper("qanda");
setNoAnswerMode($thissurvey);
@@ -413,26 +413,26 @@ function run($args) {
$conmandatoryfns=array();
$conditions=array();
$inputnames=array();
-
+
$qtypesarray = array();
-
+
$qnumber = 0;
//This re-starts the group, after checking relevance, so get consistent and unduplcated set of replacement functions
LimeExpressionManager::StartProcessingPage();
LimeExpressionManager::StartProcessingGroup($gid,($thissurvey['anonymized']!="N"),$thissurvey['sid']);
-
+
foreach ($_SESSION['fieldarray'] as $key=>$ia)
{
$qtypesarray[$ia[1]] = $ia[4];
++$qnumber;
$ia[9] = $qnumber; // incremental question count;
-
+
if ((isset($ia[10]) && $ia[10] == $gid) || (!isset($ia[10]) && $ia[5] == $gid))
{
if(IsSet($hideQuestion[$ia[0]]) && $hideQuestion[$ia[0]]==true){
continue;
}
-
+
$qidattributes=getQuestionAttributeValues($ia[0]);
if ($ia[4] != '*' && ($qidattributes===false || $qidattributes['hidden']==1)) {
// Should we really skip the question here, maybe the result won't be stored if we do that
@@ -443,7 +443,7 @@ function run($args) {
// It prevents further calls to checkquestionfordisplay if using PREVIOUS button
// from the LimeSurvey Navigator Toolbar
// $_SESSION['fieldarray'][$key][7]='N';
-
+
//Get the answers/inputnames
list($plus_qanda, $plus_inputnames)=retrieveAnswers($ia);
if ($plus_qanda)
@@ -456,25 +456,25 @@ function run($args) {
{
$inputnames = addtoarray_single($inputnames, $plus_inputnames);
}
-
+
//Display the "mandatory" popup if necessary
if (isset($notanswered))
{
list($mandatorypopup, $popup)=mandatory_popup($ia, $notanswered);
}
-
+
//Display the "validation" popup if necessary
if (isset($notvalidated))
{
list($validationpopup, $vpopup)=validation_popup($ia, $notvalidated);
}
-
+
// Display the "file validation" popup if necessary
if (isset($filenotvalidated))
{
list($filevalidationpopup, $fpopup) = file_validation_popup($ia, $filenotvalidated);
}
-
+
//Get list of mandatory questions
list($plusman, $pluscon)=create_mandatorylist($ia);
if ($plusman !== null)
@@ -489,7 +489,7 @@ function run($args) {
$conmandatorys=addtoarray_single($conmandatorys, $plus_conman);
$conmandatoryfns=addtoarray_single($conmandatoryfns, $plus_conmanfns);
}
-
+
//Build an array containing the conditions that apply for this page
$plus_conditions=retrieveConditionInfo($ia); //Returns false if no conditions
if ($plus_conditions)
@@ -500,7 +500,7 @@ function run($args) {
if ($ia[4] == "|")
$upload_file = TRUE;
} //end iteration
-
+
if (isset($thissurvey['showprogress']) && $thissurvey['showprogress'] == 'Y')
{
if ($show_empty_group)
@@ -513,22 +513,22 @@ function run($args) {
}
}
$languagechanger = makelanguagechanger();
-
+
//READ TEMPLATES, INSERT DATA AND PRESENT PAGE
sendcacheheaders();
doHeader();
-
+
if (isset($popup)) {echo $popup;}
if (isset($vpopup)) {echo $vpopup;}
if (isset($fpopup)) {echo $fpopup;}
-
+
//foreach(file("$thistpl/startpage.pstpl") as $op)
//{
// echo templatereplace($op);
//}
$redata = compact(array_keys(get_defined_vars()));
echo templatereplace(file_get_contents("$thistpl/startpage.pstpl"),array(),$redata,'Group_format[530]');
-
+
//ALTER PAGE CLASS TO PROVIDE WHOLE-PAGE ALTERNATION
if ($_SESSION['step'] != $_SESSION['prevstep'] ||
(isset($_SESSION['stepno']) && $_SESSION['stepno'] % 2))
@@ -542,9 +542,9 @@ function run($args) {
. "\n";
}
}
-
+
$hiddenfieldnames=implode("|", $inputnames);
-
+
if (isset($upload_file) && $upload_file)
echo "