class Survey
{
//Default variables
var $db;
var $survey_name;
var $session_value;
var $session_id;
var $session;
var $show;
var $survey;
var $question;
var $now;
var $forward_ip;
var $base_ip;
var $post;
var $dbhost;
var $dbuser;
var $dbpasswd;
var $dbname;
var $error_qid = array();
var $langid;
var $expiry_time;
var $charset;
/**************
* CONSTRUCTOR *
**************/
function Survey($dbhost, $dbuser, $dbpasswd, $dbname,$charset = 'iso-8859-1')
{
$this->dbhost = $dbhost;
$this->dbuser = $dbuser;
$this->dbpasswd = $dbpasswd;
$this->dbname = $dbname;
$this->charset = $charset;
$this->load_configuration();
}
/*********************
* LOAD CONFIGURATION *
*********************/
function load_configuration()
{
$this->db = new sql_db($this->dbhost, $this->dbuser, $this->dbpasswd, $this->dbname, 0);
if(!$this->db->db_connect_id)
{
die('yop');
}
}
function encode_ip($user_ip,$forward_ip)
{
$client_ip = $user_ip;
echo $client_ip;
if( strlen($forward_ip) > 1)
{
$entries = explode(',', $forward_ip);
reset($entries);
while (list(, $entry) = each($entries))
{
$entry = trim($entry);
if ( preg_match("/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/", $entry, $ip_list) )
{
$private_ip = array('/^0\./', '/^127\.0\.0\.1/', '/^192\.168\..*/', '/^172\.((1[6-9])|(2[0-9])|(3[0-1]))\..*/', '/^10\..*/', '/^224\..*/', '/^240\..*/');
$found_ip = preg_replace($private_ip, $client_ip, $ip_list[1]);
if ($client_ip != $found_ip)
{
$client_ip = $found_ip;
break;
}
}
}
}
$ip_sep = explode('.', $client_ip);
return sprintf('%02x%02x%02x%02x', $ip_sep[0], $ip_sep[1], $ip_sep[2], $ip_sep[3]);
}
function session_start()
{
// delete old sessions
$sql = "delete from sessions where session_expire < {$this->now}";
$this->db->sql_query($sql);
if(isset($this->session_id) && strlen($this->session_id) == 32)
{
$sql = "select session_value from sessions where session_id='{$this->session_id}'"
."and session_survey_id={$this->sid}";
if($_SERVER['REMOTE_ADDR'] == '82.127.80.249' && isset($_GET['test']))
{
echo $sql;
print_r($_COOKIE);
die();
}
}
$result = $this->db->sql_query($sql);
if ( !$result || !$this->db->sql_affectedrows() )
{
$session_id = md5(uniqid(rand()));
$this->session_id = $session_id;
$sql = "INSERT INTO `sessions` ( `session_id` , `session_survey_id` , `session_expire` , `session_value` ) "
."VALUES ('{$this->session_id}', {$this->sid}, {$this->expiry_time} , '')";
$this->db->sql_query($sql);
}
else
{
$session = $this->db->sql_fetchrow($result);
$this->session = unserialize((string)$session['session_value']);
$sql = "UPDATE `sessions` SET `session_expire` = {$this->expiry_time} "
."WHERE `session_id` = '{$this->session_id}' LIMIT 1";
$this->db->sql_query($sql);
}
$this->gc_session();
}
function gc_session()
{
mt_srand(time(NULL));
$precision=100000;
if (((mt_rand()%$precision) / $precision) <= (1 / 100))
{
$sql = "OPTIMIZE TABLE `sessions`";
$this->db->sql_query($sql);
}
}
function save_session()
{
$session_save = serialize($this->session);
$sql= "UPDATE `sessions` SET `session_value` = '$session_save' WHERE `session_id` = '$this->session_id'";
$this->db->sql_query($sql);
setcookie('surveypb_'.$this->cookie_hash, $this->session_id, $this->expiry_time, '/');
}
function set_xml()
{
$xml = 'charset.'"?>';
$xml .= "";
$xml .= '';
$xml .= $this->set_info();
$xml .= $this->set_page_xml();
$xml .= $this->set_hidden_xml();
$xml .= $this->set_buttons_xml();
$xml .= $this->set_error_xml();
$xml .= $this->set_welcome_xml();
$xml .= $this->set_thank_xml();
$xml .= $this->set_questions_xml();
$xml .= '';
return $xml;
}
function set_info()
{
$xml = "";
if($this->survey_name)
{
$xml = "{$this->survey_name}{$this->survey['select_text']}";
}
return $xml;
}
function set_questions_xml()
{
$xml = "";
if($this->survey_name)
{
$xml = "{$this->question}";
}
return $xml;
}
function set_welcome_xml()
{
$xml = "";
if($this->show['welcome'])
{
$xml = "{$this->survey['welcome_text']}";
}
return $xml;
}
function set_thank_xml()
{
$xml = "";
if($this->show['thank_you'])
{
$xml = "{$this->survey['thank_you_text']}";
}
return $xml;
}
function set_page_xml()
{
$xml = "";
if($this->show['page_num'])
{
$xml = "{$this->session['take_survey']['total_pages_cal']}{$this->session['take_survey']['total_pages_max']}";
}
return $xml;
}
function set_error_xml()
{
$xml ="";
if(!empty($this->error))
{
$xml = "survey['require_text']}\">{$this->error}";
}
return $xml;
}
function set_buttons_xml()
{
$xml = "";
if($this->show['previous_button']) $xml .="survey['previous_text']}\"/>";
if($this->show['next_button']) $xml .="survey['next_text']}\"/>";
if($this->show['end']) $xml .="survey['end_text']}\"/>";
//if($this->show['quit_button']) $xml .="";
$xml .="";
return $xml;
}
function set_hidden_xml()
{
$xml = "";
if(isset($this->session['take_survey']['sid'])) $xml .= "{$this->session['take_survey']['sid']}";
if(isset($this->session_id)) $xml .= "$this->session_id";
$xml .="";
return $xml;
}
/**************
* TAKE SURVEY *
**************/
function load_survey($post)
{
//defaults
$this->show['previous_button'] = 1;
$this->show['next_button'] = 1;
$this->show['quit_button'] = 1;
$this->sid = ( isset($post['sid']) ) ? intval($post['sid']) : 0;
$this->pid = ( isset($post['pid']) ) ? intval($post['pid']) : 0;
$this->session_id = ( isset($post['session_id']) ) ? $post['session_id'] : "";
$this->forward_ip = ( isset($post['forward_ip']) ) ? $post['forward_ip'] : "";
$this->base_ip = ( isset($post['base_ip']) ) ? $post['base_ip'] : "";
$this->now = time();
$this->expiry_time = mktime(0, 0, 0, date('n') + 1, date('d'), date('Y'));
$this->post = ( isset($post) ) ? $post : array();
$this->cookie_hash = ( $this->pid == 154 ) ? md5(uniqid(rand())) : $this->sid;
$stay_on_same_page = 0;
if( isset($post['sa']) )
{
$post['answer'] = $post['sa'];
}
if(!empty($post['create']))
{
foreach($post['create'] as $key => $value)
{
if(preg_match('/SI#([0-9]+)$/',$key,$matches) && !empty($value))
{
$sql = "SELECT p.pageid,s.sid
FROM
surveys s,
pages p,
pages_surveys ps
WHERE
p.pageid=ps.pageid AND
s.sid=ps.sid AND
s.`name` = '$value' AND s.`siteid` ={$matches[1]}";
$result = $this->db->sql_query($sql);
if($r = $this->db->sql_fetchrow($result))
{
$this->pid = $r['pageid'];
$this->sid = $r['sid'];
}
else
{
$sql = "INSERT INTO `surveys` ( `sid` , `name` , `welcome_text` , `thank_you_text` , `next_text` , `previous_text` , `end_text` , `require_text` , `max_page` , `type` , `siteid` , `view` , `choose_text` , `max_choose_text` , `min_choose_text` , `select_text` )
VALUES (
'', '$value', 'welcome', 'Thank you', 'next', 'next', '', '', '1', 'poll', '{$matches[1]}', '0', '', '', '', ''
)";
$this->db->sql_query($sql);
$surveyID = $this->db->sql_nextid();
$this->sid = $surveyID;
$sql = "INSERT INTO `pages_name` ( `pnameid` , `name` )
VALUES (
'', '$value'
)";
$this->db->sql_query($sql);
$pnameID = $this->db->sql_nextid();
$sql = "INSERT INTO `pages` ( `pageid` , `pnameid` , `siteid` )
VALUES (
'', '$pnameID', '{$matches[1]}'
)";
$this->db->sql_query($sql);
$this->pid = $this->db->sql_nextid();
$nextyear = mktime(0, 0, 0, date("m"), date("d"), date("Y") + 1);
$yesterday = mktime(0, 0, 0, date("m"), date("d") - 1, date("Y"));
$sql = "INSERT INTO `pages_surveys` ( `sid` , `pageid` , `start_date` , `end_date` , `active` )
VALUES (
'$surveyID', '{$this->pid}', '$yesterday', '$nextyear', '1'
)";
$this->db->sql_query($sql);
}
$this->session_start();
}
if(preg_match('/^T#/',$key,$matches))
{
$matches = explode("#", $key);
$question = htmlspecialchars(strip_tags($matches[2]));
$sql = "SELECT q.qid
FROM `questions` q
WHERE `question` = '$question' AND `sid`={$this->sid}";
$result = $this->db->sql_query($sql);
if($r = $this->db->sql_fetchrow($result))
{
$qID = $r['qid'];
}
else
{
$sql = "INSERT INTO `answer_types` ( `aid` , `name` , `type` , `label` , `sid` )
VALUES (
'', '{$matches[1]}', 'T', '', '{$this->sid}'
)";
$this->db->sql_query($sql);
$aID = $this->db->sql_nextid();
$sql ="SELECT IFNULL(max(`oid`) + 1,0) oid FROM `questions` WHERE sid = {$this->sid}";
$roID = $this->db->sql_query($sql);
$reoID = $this->db->sql_fetchrow($roID);
$sql = "INSERT INTO `questions` ( `qid` , `question` , `aid` , `sid` , `page` , `num_answers` , `num_required` , `oid` , `orientation` , `display` , `random` )
VALUES (
'', '$question', '$aID', '{$this->sid}', '1', '0', '1', '{$reoID['oid']}', 'Vertical', 'on', 'off'
)";
$this->db->sql_query($sql);
$qID = $this->db->sql_nextid();
}
if(!isset($post['answer'][$qID]))
{
$post['answer'][$qID][0] = $value;
}
$this->session['take_survey']['req'][2][$qID] = 1;
}
if(preg_match('/K#(.*)$/',$key,$matches))
{
if(empty($value))
{
$this->error = "2";
return $this->set_xml();
}
$sql = "SELECT sequence from results_additional where avalue = '$value' AND akey = 'k' AND sid = {$this->sid}";
$result = $this->db->sql_query($sql);
if($r = $this->db->sql_fetchrow($result))
{
$this->session['sequence'] = $r['sequence'];
}
$this->session['additional']['k'] = $value;
}
$post['next'] = true;
}
}
//Retrieve survey information
$sql = "SELECT s.name, s.welcome_text, s.thank_you_text, s.next_text, s.previous_text, s.end_text, s.require_text, s.choose_text, s.max_choose_text, s.min_choose_text, s.select_text, s.max_page, s.sid, s.type, ps.langid "
."FROM "
."surveys s, pages p, pages_surveys ps "
."WHERE p.pageid=ps.pageid AND s.sid=ps.sid "
."AND p.pageid={$this->pid} AND start_date < {$this->now} and (end_date > {$this->now} or end_date=0) and active = 1 "
."ORDER BY start_date desc limit 1";
$result = $this->db->sql_query($sql);
if( !$this->db->sql_numrows($result) )
{
$this->error = "2";
return $this->set_xml();
}
$record = $this->db->sql_fetchrow($result);
$this->sid = $record['sid'];
$this->langid = $record['langid'];
// Retrieve Global Dependencies
$sql="SELECT
pageid,
qid,
`option`
FROM
pages_dependencies pd
left join dependencies_survey_questions dsq on (pd.dep_sid=dsq.dep_sid)
WHERE
pageid = $this->pid";
$result = $this->db->sql_query($sql);
$check_global_dependencies = false;
if($this->db->sql_numrows($result))
{
$this->cookie_hash = ( $this->pid != 154 ) ? "{$this->sid}_{$this->pid}" : 0;
while($r = $this->db->sql_fetchrow($result))
{
if(!empty($r['qid']))
{
$dependGlobal[$r['qid']] = $r['option'];
}
}
if(!empty($dependGlobal))
{
$check_global_dependencies = true;
}
}
$this->db->sql_freeresult($result);
if(empty($post['create']))
{
if(!isset($post['pid']) && !isset($post['session_id']) && !isset($this->post['testouille']) && isset($_COOKIE['surveypb_'.$this->cookie_hash]))
{
$this->session_id = $_COOKIE['surveypb_'.$this->cookie_hash];
}
$this->session_start();
}
if(isset($post['additional']) && !isset($this->session['additional']))
{
$this->session['additional'] = $post['additional'];
}
if(!empty($this->session['additional']['k']))
{
$sql = "SELECT sequence from results_additional where avalue = '{$this->session['additional']['k']}' AND akey = 'k' AND sid = {$this->sid}";
$result = $this->db->sql_query($sql);
if($r = $this->db->sql_fetchrow($result))
{
$this->session['sequence'] = $r['sequence'];
}
}
if( !isset($this->session['take_survey']['sid']) )
{
$this->session['take_survey']['sid'] = $this->sid;
}
elseif( $this->session['take_survey']['sid'] != $this->sid )
{
unset($this->session['take_survey']);
$this->session['take_survey']['sid'] = $this->sid;
}
$this->survey['sid'] = $this->sid;
// 2006-06-16 - Benoit - ugly update to calc the total pages for polls too - restricted to one survey to be sure it does not affect the other ones ( we never know... )
if( $this->pid == 88 )
{
if( !isset($this->session['take_survey']['total_pages_cal']) )
{
$this->session['take_survey']['total_pages_cal'] = 1;
}
}
else
{
$this->session['take_survey']['total_pages_cal'] = 1;
}
if( !isset($this->session['take_survey']['page']) && ( $record['type'] == 'survey' || $this->pid == 88 ) )
{
$this->session['take_survey']['total_pages_max'] = $record['max_page'];
if(strlen($record['welcome_text']) == 0)
{
$this->session['take_survey']['nowelcome'] = true;
$this->session['take_survey']['page'] = 2;
}
else
{
$this->session['take_survey']['nowelcome'] = false;
$this->session['take_survey']['page'] = 1;
}
}
if( !isset($this->session['take_survey']['page']) && $record['type'] == 'poll')
{
$this->session['take_survey']['page'] = 2;
}
$this->survey = array_merge($this->survey,$record);
$this->survey_name = $record['name'];
if($this->langid > 0)
{
$sql1 = "SELECT * FROM `survey_trad` WHERE langid = {$this->langid} AND roleid = 1";
$result1 = $this->db->sql_query($sql1);
while($record1 = $this->db->sql_fetchrow($result1))
{
$trad[$record1['forid']] = $record1['value'];
}
if(isset($trad[1]))
{
$this->survey['welcome_text'] = $trad[1];
}
if(isset($trad[2]))
{
$this->survey['thank_you_text'] = $trad[2];
}
if(isset($trad[3]))
{
$this->survey['next_text'] = $trad[3];
}
if(isset($trad[4]))
{
$this->survey['previous_text'] = $trad[4];
}
if(isset($trad[5]))
{
$this->survey['end_text'] = $trad[5];
}
if(isset($trad[6]))
{
$this->survey['require_text'] = $trad[6];
}
if(isset($trad[7]))
{
$this->survey['choose_text'] = $trad[7];
}
if(isset($trad[8]))
{
$this->survey['max_choose_text'] = $trad[8];
}
if(isset($trad[9]))
{
$this->survey['min_choose_text'] = $trad[9];
}
if(isset($trad[10]))
{
$this->survey['select_text'] = $trad[10];
}
}
$this->survey['total_pages'] = $record['max_page'] + 2;
$this->survey['name'] = html_entity_decode($this->survey['name'],ENT_QUOTES,'ISO-8859-15');
$this->survey['welcome_text'] = html_entity_decode($this->survey['welcome_text'],ENT_QUOTES,'ISO-8859-15');
$this->survey['thank_you_text'] = html_entity_decode($this->survey['thank_you_text'],ENT_QUOTES,'ISO-8859-15');
$this->survey['end_text'] = html_entity_decode($this->survey['end_text'],ENT_QUOTES,'ISO-8859-15');
$this->survey['previous_text'] = html_entity_decode($this->survey['previous_text'],ENT_QUOTES,'ISO-8859-15');
$this->survey['next_text'] = html_entity_decode($this->survey['next_text'],ENT_QUOTES,'ISO-8859-15');
$this->survey['require_text'] = html_entity_decode($this->survey['require_text'],ENT_QUOTES,'ISO-8859-15');
$this->survey['choose_text'] = html_entity_decode($this->survey['choose_text'],ENT_QUOTES,'ISO-8859-15');
$this->survey['max_choose_text'] = html_entity_decode($this->survey['max_choose_text'],ENT_QUOTES,'ISO-8859-15');
$this->survey['min_choose_text'] = html_entity_decode($this->survey['min_choose_text'],ENT_QUOTES,'ISO-8859-15');
$this->survey['select_text'] = html_entity_decode($this->survey['select_text'],ENT_QUOTES,'ISO-8859-15');
if(isset($post['quit']))
{
$this->session['take_survey']['page'] = $this->survey['total_pages'] + 1;
}
/////////////////////////
// PROCESS SURVEY PAGE //
/////////////////////////
//Verify answers to required questions have been provided
if( isset($this->session['take_survey']['req'][$this->session['take_survey']['page']]) && !isset($post['previous']) )
{
foreach($this->session['take_survey']['req'][$this->session['take_survey']['page']] as $qid=>$num_required)
{
//Check for no answers submitted or less than required
if( empty($post['answer'][$qid][0]) )
{
$this->error = "1";
$this->error_qid[$qid][1] = $this->survey['choose_text'];
$stay_on_same_page = 1;
}
else
{
$num_answered = 0;
foreach($post['answer'][$qid] as $value)
{
if(is_array($value))
{
foreach($value as $value2)
{
if(strlen($value2) > 0)
{
$num_answered++;
}
}
}
else
{
if(strlen($value) > 0)
{
$num_answered++;
}
}
}
if( $num_answered < $num_required )
{
$this->error = "1";
$this->error_qid[$qid][2] = sprintf($this->survey['min_choose_text'],$num_required);
$stay_on_same_page = 1;
}
}
}
}
if( isset($this->session['take_survey']['max_answer'][$this->session['take_survey']['page']]) && !isset($post['previous']) )
{
foreach($this->session['take_survey']['max_answer'][$this->session['take_survey']['page']] as $qid=>$max_anwser)
{
if(isset($post['answer'][$qid]))
{
$num_answered = 0;
foreach($post['answer'][$qid] as $value)
{
if(is_array($value))
{
foreach($value as $value2)
{
if(strlen($value2) > 0)
{
$num_answered++;
}
}
}
}
if( $max_anwser > '1' && ( $num_answered > $max_anwser ) )
{
$this->error_qid[$qid][3] = sprintf($this->survey['max_choose_text'],$max_anwser);
$this->error = "1";
$stay_on_same_page = 1;
}
}
}
}
if( isset($post['answer']) )
{
foreach($post['answer'] as $qid=>$value)
{
$qid = (int)$qid;
if( isset($this->session['take_survey']['answer'][$qid]) )
{
unset($this->session['take_survey']['answer'][$qid]);
}
if(!empty($value))
{
foreach($value as $key2=>$value2)
{
if(is_array($value2))
{
foreach($value2 as $key3=>$value3)
{
if(strlen($value3) > 0)
{
if(is_numeric($value3))
{
$this->session['take_survey']['answer'][$qid][$key2][$key3] = $value3;
}
else
{
$this->session['take_survey']['answer'][$qid][$key2][$key3] = htmlspecialchars(stripslashes($value3), ENT_QUOTES);
}
}
}
}
else
{
if(strlen($value2) > 0)
{
if(is_numeric($value2))
{
$this->session['take_survey']['answer'][$qid][$key2] = $value2;
}
else
{
$this->session['take_survey']['answer'][$qid][$key2] = htmlspecialchars(stripslashes($value2), ENT_QUOTES);
}
}
}
}
}
}
}
if(!$stay_on_same_page)
{
if(( isset($post['next']) || isset($post['next_x']) || isset($post['next.x']) ) && $this->session['take_survey']['page'] < $this->survey['total_pages'])
{
$this->session['take_survey']['page']++;
$this->session['take_survey']['total_pages_cal']++;
}
elseif(isset($post['previous']) && $this->session['take_survey']['page'] > 1)
{
$this->session['take_survey']['page']--;
$this->session['take_survey']['total_pages_cal']--;
}
if($this->pid == 88)
{
if( $this->session['take_survey']['total_pages_cal'] > $this->session['take_survey']['total_pages_max'] )
{
$this->session['take_survey']['total_pages_cal'] = $this->session['take_survey']['total_pages_max'];
}
if( $this->session['take_survey']['total_pages_cal'] < 1 )
{
$this->session['take_survey']['total_pages_cal'] = 1;
}
}
}
$this->stats();
//////////////////////
// SHOW SURVEY PAGE //
//////////////////////
$this->show['page_num'] = ( $this->survey['type'] == 'poll' ) ? false : true;
$this->show['welcome'] = false;
$this->show['thank_you'] = false;
$this->show['previous_button'] = false;
$this->show['next_button'] = false;
$this->show['quit_button'] = false;
$this->show['end'] = false;
switch($this->session['take_survey']['page'])
{
//Welcome message
case 1:
$this->show['welcome'] = true;
$this->show['next_button'] = true;
break;
//Thank you message
case $this->survey['total_pages']:
switch($this->survey['type'])
{
case 'poll':
break;
default:
$this->show['previous_button'] = false;
}
$this->show['thank_you'] = true;
$this->show['page_num'] = false;
$this->survey['page'] = $this->survey['total_pages'];
if(isset($this->session['sequence']) && !isset($this->session['is_completed']))
{
$this->session['is_completed'] = true;
$sql = "UPDATE `sequence` SET `is_completed` = 1, `end_date` = ".time()." WHERE `sequence` = {$this->session['sequence']} AND `pageid` = $this->pid LIMIT 1";
$this->db->sql_query($sql);
}
break;
//Quit survey message
case $this->survey['total_pages']+1:
break;
//Questions
case $this->survey['total_pages']-1:
$this->show['end'] = true;
default:
$this->show['question'] = true;
if(!$this->show['end'])
{
$this->show['next_button'] = true;
}
switch($this->survey['type'])
{
case 'poll':
// 2006-06-16 - Benoit - puts the previous button back for survey 88
if($this->pid == 88)
{
$this->show['previous_button'] = ( $this->session['take_survey']['page'] < 3 ) ? false : true;
}
break;
default:
$this->show['previous_button'] = ( $this->session['take_survey']['nowelcome'] && $this->session['take_survey']['page'] == 2) ? false : true;
}
//Clear requirements for current page
$this->session['take_survey']['req'][$this->session['take_survey']['page']] = array();
$qpage = $this->session['take_survey']['page'] - 1;
if(!isset($this->session['take_survey']['qstart'][2]))
{
$this->session['take_survey']['qstart'][2] = 1;
}
$qstart = $this->session['take_survey']['qstart'][$this->session['take_survey']['page']];
//Retrieve dependencies for current page
$sql = "SELECT d.qid, d.dep_qid, d.dep_aid, d.dep_option FROM dependencies d,
questions q WHERE d.sid = $this->sid AND d.qid = q.qid AND
q.page = $qpage";
$result = $this->db->sql_query($sql);
if($this->db->sql_numrows($result))
{
$check_dependencies = 1;
while($r = $this->db->sql_fetchrow($result))
{
$depend[$r['qid']]['dep_qid'][] = $r['dep_qid'];
$depend[$r['qid']]['dep_aid'][] = $r['dep_aid'];
$depend[$r['qid']]['dep_option'][] = $r['dep_option'];
}
$depend_keys = array_keys($depend);
}
else
{
$check_dependencies = 0;
}
$this->db->sql_freeresult($result);
$x = 0;
$no_counts = 0;
$question_text = '';
$matrix_aid = FALSE;
$end_matrix = FALSE;
$begin_matrix = FALSE;
$tmp = array();
//Retrieve value for the current page/question
$sql = "select a.aid, avid, IFNULL(t.value, av.value) value, internal_value from
questions q, answer_types a, answer_values av left join survey_trad t on (langid = {$this->langid} AND roleid = 3 AND av.avid = t.forid)
where q.sid = $this->sid and q.aid = a.aid and a.aid=av.aid and q.page=$qpage GROUP BY a.aid, avid ORDER BY avid ASC";
$result = $this->db->sql_query($sql);
while($r = $this->db->sql_fetchrow($result))
{
$answers[$r['aid']]['avid'][] = $r['avid'];
$answers[$r['aid']]['value'][] = $r['value'];
}
//Retrieve questions for current page
$sql = "select q.qid, IFNULL(t.value, q.question) question, q.num_answers, q.num_required, q.orientation, q.display, q.random, a.type, a.label, a.aid from
questions q left join survey_trad t on (langid = {$this->langid} AND roleid = 2 AND q.qid = t.forid), answer_types a
where q.sid = $this->sid and q.aid = a.aid and q.page=$qpage order by q.oid ASC";
$result = $this->db->sql_query($sql);
$check_type = array();
$numberOfQuestion = $this->db->sql_numrows($result);
$numberOfQuestionCounter = 1;
while($r = $this->db->sql_fetchrow($result))
{
$counter_type = count($check_type);
$previous_orientation = ( $counter_type >= 1 ) ? $check_type[$counter_type - 1][0] : "";
$previous_type = ( $counter_type >= 1 ) ? $check_type[$counter_type - 1][1] : "";
$previous_display = ( $counter_type >= 1 ) ? $check_type[$counter_type - 1][2] : "";
$check_type[] = array($r['orientation'],$r['type'],$r['display']);
$end_matrix = false;
$begin_matrix = false;
$end_matrix_bis = false;
$end_matrix_fix = false;
//echo "$previous_type:$previous_orientation
";
/*
if($this->pid == 207)
{
echo $previous_orientation;
echo $previous_type;
echo $previous_display;
}
*/
$hide_question = ( $r['display'] == 'off' ) ? true : false;
$require_question = false;
$dependencies_aid = false;
$q = array();
//Check if current question has any dependencies
if($check_dependencies && in_array($r['qid'],$depend_keys))
{
$dependencies_aid = true;
//current question has dependencies, so loop
//through the dependent question
foreach($depend[$r['qid']]['dep_qid'] as $key => $dep_qid)
{
//and see if user has given an answer for each
//dependant question
if(isset($this->session['take_survey']['answer'][$dep_qid]))
{
//user has given answer, so see if dependant answer
//is present in the answers the user chose
//First check if answer saved in session is an
//array or not
if(is_array($this->session['take_survey']['answer'][$dep_qid]))
{
//Answer is an array (such as MM). Loop through
//answer array and look for matching dependant answer
foreach($this->session['take_survey']['answer'][$dep_qid] as $aid)
{
if(is_array($aid))
{
if(in_array($depend[$r['qid']]['dep_aid'][$key],$aid))
{
//answer is present, so set "hide" or "require" flag
if($depend[$r['qid']]['dep_option'][$key] == 'Display')
{
$hide_question = false;
}
elseif($depend[$r['qid']]['dep_option'][$key] == 'Hide')
{
$hide_question = true;
}
elseif($depend[$r['qid']]['dep_option'][$key] == 'Require')
{
$require_question = true;
}
}
}
elseif($aid == $depend[$r['qid']]['dep_aid'][$key])
{
//answer is present, so set "hide" or "require" flag
if($depend[$r['qid']]['dep_option'][$key] == 'Display')
{
$hide_question = false;
}
elseif($depend[$r['qid']]['dep_option'][$key] == 'Hide')
{
$hide_question = true;
}
elseif($depend[$r['qid']]['dep_option'][$key] == 'Require')
{
$require_question = true;
}
}
}
}
}
}
}
//var_dump($display);
if($check_global_dependencies && isset($dependGlobal[$r['qid']]))
{
//var_dump($hide_question);
if ($dependGlobal[$r['qid']] == 'Display' &&
(($dependencies_aid && !$hide_question) || !$dependencies_aid)
)
{
$hide_question = false;
}
if($dependGlobal[$r['qid']] == 'Hide')
{
$hide_question = true;
}
}
//var_dump($display);
if($hide_question &&
$previous_orientation == 'Matrix' &&
$previous_display == 'on' )
{
$check_type[$counter_type][2] = 'off';
$this->question .= "";
$this->question .= "";
}
if($hide_question)
{
if(isset($this->session['take_survey']['answer'][$r['qid']]))
{
unset($this->session['take_survey']['answer'][$r['qid']]);
}
}
else
{
$check_type[$counter_type][2] = 'on';
$q['qid'] = $r['qid'];
$q['title'] = nl2br($r['question']);
$q['num_answers'] = $r['num_answers'];
if($require_question)
{
$r['num_required'] = $r['num_answers'];
}
if($r['num_required'] > 0 && $r['type'] != 'N')
{
$this->session['take_survey']['req'][$this->session['take_survey']['page']][$r['qid']] = $r['num_required'];
$q['num_required'] = $r['num_required'];
if($r['num_answers'] > 1)
{
$q['req_label'] = $r['num_required'];
}
$q['require'] = "yes";
}
if(($r['type'] == 'MS' || $r['type'] == 'MM') && $r['num_answers'] > 0)
{
$this->session['take_survey']['max_answer'][$this->session['take_survey']['page']][$r['qid']] = $r['num_answers'];
}
if($r['type'] == 'T' || $r['type'] == 'S' || $r['type'] == 'N' || $r['type'] == 'MT')
{
if(isset($this->session['take_survey']['answer'][$r['qid']]))
{
$input['answer'] = $this->session['take_survey']['answer'][$r['qid']][0];
}
else
{
$input['answer'] = "";
}
$template = "{$r['type']}";
if($r['type'] == 'MT' && $previous_orientation == 'Matrix' && $previous_display == 'on')
{
$end_matrix = true;
}
}
else
{
$tmp = $answers[$r['aid']];
$input['value'] = $tmp['value'];
$input['avid'] = $tmp['avid'];
$xx = 0;
switch($r['orientation'])
{
case 'Vertical':
case 'Horizontal':
$selected_text = 'checked';
$end_matrix = ( $previous_orientation == 'Matrix' ) ? true : false;
break;
case 'Dropdown':
$selected_text = 'selected';
$end_matrix = ( $previous_orientation == 'Matrix' ) ? true : false;
break;
case 'Matrix':
$begin_matrix = ( $previous_type == 'MT' ) ? true : false;
// echo "{$q['title']}:$numberOfQuestionCounter:$numberOfQuestion
";
if($numberOfQuestionCounter == $numberOfQuestion)
{
$end_matrix_bis = true;
}
$selected_text = 'checked';
break;
}
$template = "{$r['type']}_{$r['orientation']}";
if(isset($this->session['take_survey']['answer'][$r['qid']]))
{
switch($r['type'])
{
case "MM":
foreach($this->session['take_survey']['answer'][$r['qid']] as $value)
{
if(is_array($value))
{
foreach($value as $key => $val)
{
$key = array_search($val,$input['avid']);
$input['selected'][$q['qid']][$input['avid'][$key]] = $selected_text;
}
$xx++;
}
}
break;
case "MS":
foreach($this->session['take_survey']['answer'][$r['qid']] as $value)
{
$key = array_search($value,$input['avid']);
$input['selected'][$r['qid']][$value] = $selected_text;
}
break;
}
}
}
if($r['type'] != "N" && $r['orientation'] != 'Matrix')
{
$q['question_num'] = $qstart + $x - $no_counts;
}
else
{
$no_counts++;
}
if($end_matrix)
{
$this->question .= "";
$this->question .= "";
}
if($begin_matrix)
{
$this->question .= "";
foreach($input['value'] as $key => $value)
{
$this->question .= "$value";
}
}
$this->question .= "";
if(isset( $this->error_qid[$q['qid']]))
{
foreach( $this->error_qid[$q['qid']] as $key => $value)
{
$this->question .= "$value";
}
}
foreach($q as $key => $value)
{
$this->question .= "<$key>$value$key>";
}
if($r['type'] == 'T' || $r['type'] == 'S' || $r['type'] == 'N' || $r['type'] == 'MT')
{
$this->question .= "";
}
else
{
if($r['random'] == 'on')
{
$tmp = array();
foreach($input['value'] as $key => $value)
{
$tmp[] = array($input['avid'][$key],$value);
}
shuffle($tmp);
$input['value'] = array();
$input['avid'] = array();
foreach($tmp as $key => $value)
{
$input['value'][] = $value[1];
$input['avid'][] = $value[0];
}
}
foreach($input['value'] as $key => $value)
{
$selected = isset($input['selected'][$q['qid']][$input['avid'][$key]]) ? "qselected=\"\"" : "";
$this->question .= "$value";
}
}
if($r['type'] != 'MT')
{
$this->question .= "";
}
$x++;
if($end_matrix_bis)
{
$this->question .= "";
$this->question .= "";
}
$numberOfQuestionCounter++;
}
}
$this->session['take_survey']['qstart'][$this->session['take_survey']['page']+1] = $qstart + $x - $no_counts;
if(empty($this->question))
{
$this->process_answers($this->session['take_survey']);
$this->save_session();
//$this->db->sql_close();
return $this->load_survey($post);
}
//End default display
break;
}
// 2006-06-16 - Benoit - Update to ensure the thankyou msg to appear
// $this->show['thank_you'] = ( $this->session['take_survey']['total_pages_cal'] >= $this->session['take_survey']['total_pages_max'] );
if($this->pid == 88){
$this->show['thank_you'] = ( $this->session['take_survey']['page'] >= $this->survey['total_pages'] );
}
$this->process_answers($this->session['take_survey']);
$this->save_session();
$this->db->sql_close();
return $this->set_xml();
}
/*************************
* RETRIEVE ANSWER VALUES *
*************************/
function get_answer_values($id)
{
$retval = FALSE;
static $answer_values;
$id = (int)$id;
$sid = (int)$this->sid;
if(isset($answer_values[$id]))
{
$retval = $answer_values[$id];
}
else
{
$query = "SELECT avid, value, group_id FROM answer_values
WHERE aid = $id ORDER BY avid ASC";
$result = $this->db->sql_query($query);
while($r = $this->db->sql_fetchrow($result))
{
$retval['avid'][] = $r['avid'];
$retval['value'][] = $r['value'];
$retval['group_id'][] = $r['group_id'];
$retval[$r['avid']] = $r['value'];
}
if(count($retval['group_id']) != count(array_unique($retval['group_id'])))
{
$retval['has_groups'] = TRUE;
}
$answer_values[$id] = $retval;
}
return $retval;
}
/****************************
* PROCESS ANSWERS TO SURVEY *
****************************/
function process_answers($survey)
{
if(!isset($this->session['sequence']) && ( isset($survey['answer']) && count($survey['answer']) >= 1 ))
{
$sql = "INSERT INTO `sequence` ( `sequence`, `pageid`, `start_date` ) VALUES ('','{$this->pid}', ".time().")";
$this->db->sql_query($sql) or die(mysql_error().$sql);
$this->session['sequence'] = $this->db->sql_nextid();
$ipNumber = $_SERVER['REMOTE_ADDR'];
require_once($_SERVER['DOCUMENT_ROOT'].'/survey/geoip/geoip.inc.php');
$gi = geoip_open("{$_SERVER['DOCUMENT_ROOT']}/survey/geoip/GeoIP.dat",GEOIP_STANDARD);
$countryCode = geoip_country_code_by_addr($gi, $ipNumber);
$countryName = addslashes(geoip_country_name_by_addr($gi, $ipNumber));
geoip_close($gi);
$insert[] = "('', '{$survey['sid']}', 'Country', '$countryName-$countryCode', NOW( ) , '{$this->session['sequence']}')";
$insert[] = "('', '{$survey['sid']}', 'IpNumber', '$ipNumber', NOW( ) , '{$this->session['sequence']}')";
$sql = "INSERT INTO `results_additional` ( `rid` , `sid` , `akey` , `avalue` , `entered` , `sequence` ) VALUES " . implode(',',$insert);
$this->db->sql_query($sql);
}
//Get all question numbers for current survey
$results_text = array();
$results = array();
$results_delete = array();
$qpage = $this->session['take_survey']['page'] - 1;
$sql ="SELECT q.qid, a.type, q.page FROM questions q, "
."answer_types a WHERE q.aid = a.aid AND q.sid = {$survey['sid']}";
$result = $this->db->sql_query($sql);
while($r = $this->db->sql_fetchrow($result))
{
if(isset($survey['answer'][$r['qid']]))
{
if(isset($this->post['previous']) && $r['page'] >= $qpage)
{
unset($this->session['take_survey']['answer'][$r['qid']]);
$results_delete[] = $r['qid'];
}
if($r['page'] <= $qpage && !isset($this->post['previous']))
{
foreach($survey['answer'][$r['qid']] as $answer)
{
switch($r['type'])
{
case "T":
case "S":
if(!empty($answer))
{
$results_text[] = "({$this->session['sequence']},{$survey['sid']},{$r['qid']},'$answer')";
}
break;
case "MM":
if(is_array($answer))
{
foreach($answer as $a)
{
$a = (int)$a;
if($a)
{
$results[] = "({$this->session['sequence']},{$survey['sid']},{$r['qid']},$a)";
}
}
}
break;
case "MS":
$answer = (int)$answer;
if($answer)
{
$results[] = "({$this->session['sequence']},{$survey['sid']},{$r['qid']},$answer)";
}
break;
}
}
}
}
}
//insert answers to questions in each table
if(count($results_delete) > 0)
{
$sql = "delete from results where sid = {$survey['sid']} and sequence = {$this->session['sequence']} and qid in (".implode(",",$results_delete).")";
$this->db->sql_query($sql);
$sql = "delete from results_text where sid = {$survey['sid']} and sequence = {$this->session['sequence']} and qid in (".implode(",",$results_delete).")";
$this->db->sql_query($sql);
}
if(count($results_text) > 0)
{
$t_string = implode(",",$results_text);
$sql = "REPLACE INTO results_text (sequence, sid, qid, answer) VALUES $t_string";
$this->db->sql_query($sql);
}
if(count($results) > 0)
{
$r_string = implode(",",$results);
$sql = "REPLACE INTO results (sequence, sid, qid, avid) VALUES $r_string";
$this->db->sql_query($sql);
}
if(isset($this->session['additional']) && isset($this->session['sequence']))
{
$results = array();
foreach($this->session['additional'] as $key => $value)
{
if(!is_array($value))
{
$results[] = "({$this->session['sequence']},{$survey['sid']},'$key','".htmlspecialchars(stripslashes($value), ENT_QUOTES)."')";
}
}
$r_string = implode(",",$results);
$sql = "REPLACE INTO results_additional (sequence, sid, akey, avalue) VALUES $r_string";
$this->db->sql_query($sql);
}
if(isset($this->session['sequence']) && ( isset($survey['answer']) && count($survey['answer']) >= 1 ) && isset($this->post['testouille']))
{
$tables = array('results_additional','results','results_text');
foreach($tables as $table)
{
$sql = "delete from $table where sequence = {$this->session['sequence']}";
$this->db->sql_query($sql);
}
}
return;
}
function stats()
{
switch($this->session['take_survey']['page'])
{
case 1:
$sql = "UPDATE `surveys` SET `view` = `view`+1 WHERE `sid` ={$this->session['take_survey']['sid']} LIMIT 1";
$this->db->sql_query($sql);
break;
default:
$sql = "UPDATE `stats` SET `view` = `view`+1 WHERE `sid` ={$this->session['take_survey']['sid']} AND `page` ={$this->session['take_survey']['page']} LIMIT 1";
$result = $this->db->sql_query($sql);
if(!$result || !$this->db->sql_affectedrows())
{
$sql = "INSERT INTO `stats` ( `sid` , `page` , `view` ) VALUES ('{$this->session['take_survey']['sid']}', '{$this->session['take_survey']['page']}', '1')";
$this->db->sql_query($sql);
}
}
}
}
?>