Advertisement
Guest User

Untitled

a guest
Jan 2nd, 2013
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 118.74 KB | None | 0 0
  1. <!DOCTYPE html>
  2.  
  3.  
  4. <?php
  5. if ($_GET['page'] == NULL) { $pageName = 'home'; }
  6. else { $pageName = $_GET['page']; }
  7.  
  8. if ($_GET['f'] == NULL) { $f = 'root'; }
  9. else { $f = $_GET['f']; }
  10.  
  11. $backissues = 'content/backissues/';
  12. $currentIssue = 'Current_Issue';
  13.  
  14. $pageTitle = ucfirst($pageName); ;
  15. ?>
  16.  
  17.  
  18.  
  19. <html xlmns="http://www.w3.org/1999/xhtml">
  20.  
  21. <head>
  22.     <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  23.     <meta http-equiv="Content-Style-Type" content="text/css">
  24.     <meta name="description" content="Fort Wayne and northeast Indiana nightlife, entertainment, arts, attractions, venues and music">
  25.     <title>Fort Wayne Nightlife, Entertainment and Arts || <?php echo $pageTitle; ?> </title>
  26.     <link rel="stylesheet" type="text/css" href="http://whatzup.com/default.css"/> 
  27.  
  28.  
  29.  
  30. <script src="http://whatzup.com/scripts/jquery.js" type="text/javascript"></script>
  31. <script type="text/javascript">
  32.  
  33.   var _gaq = _gaq || [];
  34.   _gaq.push(['_setAccount', 'UA-29371195-1']);
  35.   _gaq.push(['_trackPageview']);
  36.  
  37.   (function() {
  38.     var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  39.     ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  40.     var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  41.   })();
  42.  
  43. </script>
  44.  
  45. <meta name="google-site-verification" content="z4LoeWV0GNLH6NTJPTXCSXjT3xO1etknN7lkypafiDU" />
  46. </head>
  47.    
  48.    
  49. <body>
  50.  
  51.  
  52.     <div class="wrapOverall">
  53.    
  54.         <div class="header"><?php include('../template/banner.php'); ?></div>
  55.        
  56.         <div id="navcon"><?php include('../template/top_navigation.php'); ?></div>
  57.        
  58.         <div class="wrapContent">
  59.        
  60.             <div class="wrapLeft">
  61.            
  62.                 <div class="sidebar"><?php include('../template/left-column.php'); ?></div>
  63.                
  64.                 <div class="content">
  65.  
  66. <?php
  67. /*
  68. * LimeSurvey
  69. * Copyright (C) 2007 The LimeSurvey Project Team / Carsten Schmitz
  70. * All rights reserved.
  71. * License: GNU/GPL License v2 or later, see LICENSE.php
  72. * LimeSurvey is free software. This version may have been modified pursuant
  73. * to the GNU General Public License, and as distributed it includes or
  74. * is derivative of works licensed under the GNU General Public License or
  75. * other free or open source software licenses.
  76. * See COPYRIGHT.php for copyright notices and details.
  77. *
  78. * $Id: index.php 12361 2012-02-05 19:40:30Z tmswhite $
  79. */
  80.  
  81. // Security Checked: POST, GET, SESSION, REQUEST, returnglobal, DB
  82.  
  83. include('http://whatzup.com/index.php');
  84.  
  85.  
  86. require_once(dirname(__FILE__).'/classes/core/startup.php');
  87.  
  88.  
  89. require_once(dirname(__FILE__).'/config-defaults.php');
  90. require_once(dirname(__FILE__).'/common.php');
  91. require_once(dirname(__FILE__).'/classes/core/language.php');
  92. @ini_set('session.gc_maxlifetime', $sessionlifetime);
  93.  
  94. $loadname=returnglobal('loadname');
  95. $loadpass=returnglobal('loadpass');
  96. $scid=returnglobal('scid');
  97. $thisstep=returnglobal('thisstep');
  98. $move=sanitize_paranoid_string(returnglobal('move'));
  99. $clienttoken=sanitize_token(returnglobal('token'));
  100.  
  101.  
  102. if (!isset($thisstep))
  103. {
  104.     $thisstep = "";
  105. }
  106.  
  107.  
  108. if (!isset($surveyid))
  109. {
  110.     $surveyid=returnglobal('sid');
  111. }
  112. else
  113. {
  114.     //This next line ensures that the $surveyid value is never anything but a number.
  115.     $surveyid=sanitize_int($surveyid);
  116. }
  117.  
  118. //LimeExpressionManager::SetSurveyId($surveyid);  // must be called early - it clears internal cache if a new survey is being used
  119.  
  120. //DEFAULT SETTINGS FOR TEMPLATES
  121. if (!$publicdir)
  122. {
  123.     $publicdir=".";
  124. }
  125.  
  126. // First check if survey is active
  127. // if not: copy some vars from the admin session
  128. // to a new user session
  129.  
  130. if ($surveyid)
  131. {
  132.     $issurveyactive=false;
  133.     $aRow=$connect->GetRow("SELECT * FROM ".db_table_name('surveys')." WHERE sid=$surveyid");
  134.     if (isset($aRow['active']))
  135.     {
  136.         $surveyexists=true;
  137.         if($aRow['active']=='Y')
  138.         {
  139.             $issurveyactive=true;
  140.         }
  141.     }
  142.     else
  143.     {
  144.         $surveyexists=false;
  145.     }
  146. }
  147.  
  148. // Compute the Session name
  149. // Session name is based:
  150. // * on this specific limesurvey installation (Value SessionName in DB)
  151. // * on the surveyid (from Get or Post param). If no surveyid is given we are on the public surveys portal
  152. $usquery = "SELECT stg_value FROM ".db_table_name("settings_global")." where stg_name='SessionName'";
  153. $usresult = db_execute_assoc($usquery,'',true);          //Checked
  154. if ($usresult)
  155. {
  156.     $usrow = $usresult->FetchRow();
  157.     $stg_SessionName=$usrow['stg_value'];
  158.     if ($surveyid && $surveyexists)
  159.     {
  160.         @session_name($stg_SessionName.'-runtime-'.$surveyid);
  161.     }
  162.     else
  163.     {
  164.         @session_name($stg_SessionName.'-runtime-publicportal');
  165.     }
  166. }
  167. else
  168. {
  169.     session_name("LimeSurveyRuntime-$surveyid");
  170. }
  171. session_set_cookie_params(0,$relativeurl.'/');
  172. if (!isset($_SESSION) || empty($_SESSION)) // the $_SESSION variable can be empty if register_globals is on
  173.     @session_start();
  174.  
  175. if ( $embedded && $embedded_inc != '' )
  176. {
  177.     require_once( $embedded_inc );
  178. }
  179. //CHECK FOR REQUIRED INFORMATION (sid)
  180. if (!$surveyid || !$surveyexists)
  181. {
  182.     if(isset($_GET['lang']))
  183.     {
  184.         $baselang = sanitize_languagecode($_GET['lang']);
  185.     }
  186.     elseif (!isset($baselang))
  187.     {
  188.         $baselang=$defaultlang;
  189.     }
  190.     $clang = new limesurvey_lang($baselang);
  191.     if(!isset($defaulttemplate))
  192.     {
  193.         $defaulttemplate="default";
  194.     }
  195.     $languagechanger = makelanguagechanger();
  196.     //Find out if there are any publicly available surveys
  197.     $query = "SELECT a.sid, b.surveyls_title, a.publicstatistics
  198.    FROM ".db_table_name('surveys')." AS a
  199.    INNER JOIN ".db_table_name('surveys_languagesettings')." AS b
  200.    ON ( surveyls_survey_id = a.sid AND surveyls_language = a.language )
  201.    WHERE surveyls_survey_id=a.sid
  202.    AND surveyls_language=a.language
  203.    AND a.active='Y'
  204.    AND a.listpublic='Y'
  205.    AND ((a.expires >= '".date("Y-m-d H:i")."') OR (a.expires is null))
  206.    AND ((a.startdate <= '".date("Y-m-d H:i")."') OR (a.startdate is null))
  207.    ORDER BY surveyls_title";
  208.     $result = db_execute_assoc($query,false,true) or die("Could not connect to database. If you try to install LimeSurvey please refer to the <a href='http://docs.limesurvey.org'>installation docs</a> and/or contact the system administrator of this webpage."); //Checked
  209.     $list=array();
  210.     if($result->RecordCount() > 0)
  211.     {
  212.         while($rows = $result->FetchRow())
  213.         {
  214.             $result2 = db_execute_assoc("Select surveyls_title from ".db_table_name('surveys_languagesettings')." where surveyls_survey_id={$rows['sid']} and surveyls_language='$baselang'");
  215.             if ($result2->RecordCount())
  216.             {
  217.                 $languagedetails=$result2->FetchRow();
  218.                 $rows['surveyls_title']=$languagedetails['surveyls_title'];
  219.             }
  220.             $link = "<li><a href='$rooturl/index.php?sid=".$rows['sid'];
  221.             if (isset($_GET['lang']))
  222.             {
  223.                 $link .= "&lang=".sanitize_languagecode($_GET['lang']);
  224.             }
  225.             if (isset($_GET['lang']))
  226.             {
  227.                 $link .= "&amp;lang=".sanitize_languagecode($_GET['lang']);
  228.             }
  229.             $link .= "'  class='surveytitle'>".$rows['surveyls_title']."</a>\n";
  230.             if ($rows['publicstatistics'] == 'Y') $link .= "<a href='{$relativeurl}/statistics_user.php?sid={$rows['sid']}'>(".$clang->gT('View statistics').")</a>";
  231.             $link .= "</li>\n";
  232.             $list[]=$link;
  233.         }
  234.     }
  235.     if(count($list) < 1)
  236.     {
  237.         $list[]="<li class='surveytitle'>".$clang->gT("No available surveys")."</li>";
  238.     }
  239.  
  240.     if(!$surveyid)
  241.     {
  242.         $thissurvey['name']=$sitename;
  243.         $nosid=$clang->gT("You have not provided a survey identification number");
  244.     }
  245.     else
  246.     {
  247.         $thissurvey['name']=$clang->gT("The survey identification number is invalid");
  248.         $nosid=$clang->gT("The survey identification number is invalid");
  249.     }
  250.     $surveylist=array(
  251.     "nosid"=>$clang->gT("You have not provided a survey identification number"),
  252.     "contact"=>sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$siteadminname,encodeEmail($siteadminemail)),
  253.     "listheading"=>$clang->gT("The following surveys are available:"),
  254.     "list"=>implode("\n",$list),
  255.     );
  256.  
  257.     $thissurvey['templatedir']=$defaulttemplate;
  258.  
  259.     //A nice exit
  260.     sendcacheheaders();
  261.     doHeader();
  262.     echo templatereplace(file_get_contents(sGetTemplatePath($defaulttemplate)."/startpage.pstpl"));
  263.  
  264.     echo templatereplace(file_get_contents(sGetTemplatePath($defaulttemplate)."/surveylist.pstpl"));
  265.  
  266.     echo templatereplace(file_get_contents(sGetTemplatePath($defaulttemplate)."/endpage.pstpl"));
  267.     doFooter();
  268.     exit;
  269. }
  270.  
  271. if ($clienttoken != '' && isset($_SESSION['token']) &&
  272. $clienttoken != $_SESSION['token'])
  273. {
  274.     require_once(dirname(__FILE__).'/classes/core/language.php');
  275.     $baselang = GetBaseLanguageFromSurveyID($surveyid);
  276.     $clang = new limesurvey_lang($baselang);
  277.     // Let's first regenerate a session id
  278.     killSession();
  279.     // Let's redirect the client to the same URL after having reseted the session
  280.     header("Location: $rooturl/index.php?" .$_SERVER['QUERY_STRING']);
  281.     sendcacheheaders();
  282.     doHeader();
  283.  
  284.     echo templatereplace(file_get_contents("$standardtemplaterootdir/default/startpage.pstpl"));
  285.     echo "\t<div id='wrapper'>\n"
  286.     ."\t<p id='tokenmessage'>\n"
  287.     ."\t<span class='error'>".$clang->gT("Token mismatch")."</span><br /><br />\n"
  288.     ."\t".$clang->gT("The token you provided doesn't match the one in your session.")."<br /><br />\n"
  289.     ."\t".$clang->gT("Please wait to begin with a new session.")."<br /><br />\n"
  290.     ."\t</p>\n"
  291.     ."\t</div>\n";
  292.  
  293.     echo templatereplace(file_get_contents("$standardtemplaterootdir/default/endpage.pstpl"));
  294.     doFooter();
  295.     exit;
  296. }
  297.  
  298. if (isset($_SESSION['finished']) && $_SESSION['finished'] === true)
  299. {
  300.     require_once(dirname(__FILE__).'/classes/core/language.php');
  301.     $baselang = GetBaseLanguageFromSurveyID($surveyid);
  302.     $clang = new limesurvey_lang($baselang);
  303.     // Let's first regenerate a session id
  304.     killSession();
  305.     // Let's redirect the client to the same URL after having reseted the session
  306.     header("Location: $rooturl/index.php?" .$_SERVER['QUERY_STRING']);
  307.     sendcacheheaders();
  308.     doHeader();
  309.  
  310.     echo templatereplace(file_get_contents("$standardtemplaterootdir/default/startpage.pstpl"));
  311.     echo "\t<div id='wrapper'>\n"
  312.     ."\t<p id='tokenmessage'>\n"
  313.     ."\t<span class='error'>".$clang->gT("Previous session is set to be finished.")."</span><br /><br />\n"
  314.     ."\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.")."<br /><br />\n"
  315.     ."\t".$clang->gT("Please wait to begin with a new session.")."<br /><br />\n"
  316.     ."\t</p>\n"
  317.     ."\t</div>\n";
  318.  
  319.     echo templatereplace(file_get_contents("$standardtemplaterootdir/default/endpage.pstpl"));
  320.     doFooter();
  321.     exit;
  322. }
  323. $previewgrp = false;
  324. if (isset($_REQUEST['action']) && ($_REQUEST['action'] == 'previewgroup')){
  325.     $rightquery="SELECT uid FROM {$dbprefix}survey_permissions WHERE sid=".db_quote($surveyid)." AND uid = ".db_quote($_SESSION['loginID'].' group by uid');
  326.     $rightresult = db_execute_assoc($rightquery);
  327.     if ($rightresult->RecordCount() > 0 || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1)
  328.     {
  329.         $previewgrp = true;
  330.     }
  331. }
  332.  
  333. if (($surveyid &&
  334. $issurveyactive===false && $surveyexists &&
  335. isset ($surveyPreview_require_Auth) &&
  336. $surveyPreview_require_Auth == true) &&  $previewgrp == false)
  337. {
  338.     // admin session and permission have not already been imported
  339.     // for this particular survey
  340.     if ( !isset($_SESSION['USER_RIGHT_PREVIEW']) ||
  341.     $_SESSION['USER_RIGHT_PREVIEW'] != $surveyid)
  342.     {
  343.         // Store initial session name
  344.         $initial_session_name=session_name();
  345.  
  346.         // One way (not implemented here) would be to start the
  347.         // user session from a duplicate of the admin session
  348.         // - destroy the new session
  349.         // - load admin session (with correct session name)
  350.         // - close admin session
  351.         // - change used session name to default
  352.         // - open new session (takes admin session id)
  353.         // - regenerate brand new session id for this session
  354.  
  355.         // The solution implemented here is to copy some
  356.         // fields from the admin session to the new session
  357.         // - first destroy the new (empty) user session
  358.         // - then open admin session
  359.         // - record interresting values from the admin session
  360.         // - duplicate admin session under another name and Id
  361.         // - destroy the duplicated admin session
  362.         // - start a brand new user session
  363.         // - copy interresting values in this user session
  364.  
  365.         @session_destroy(); // make it silent because for
  366.         // some strange reasons it fails sometimes
  367.         // which is not a problem
  368.         // but if it throws an error then future
  369.         // session functions won't work because
  370.         // headers are already sent.
  371.         if (isset($stg_SessionName) && $stg_SessionName)
  372.         {
  373.             @session_name($stg_SessionName);
  374.         }
  375.         else
  376.         {
  377.             session_name("LimeSurveyAdmin");
  378.         }
  379.         session_start(); // Loads Admin Session
  380.  
  381.         $previewright=false;
  382.         $savesessionvars=Array();
  383.         if (isset($_SESSION['loginID']))
  384.         {
  385.             $rightquery="SELECT uid FROM {$dbprefix}survey_permissions WHERE sid=".db_quote($surveyid)." AND uid = ".db_quote($_SESSION['loginID'].' group by uid');
  386.             $rightresult = db_execute_assoc($rightquery);      //Checked
  387.  
  388.             // Currently it is enough to be listed in the survey
  389.             // user operator list to get preview access
  390.             if ($rightresult->RecordCount() > 0 || $_SESSION['USER_RIGHT_SUPERADMIN'] == 1)
  391.             {
  392.                 $previewright=true;
  393.                 $savesessionvars["USER_RIGHT_PREVIEW"]=$surveyid;
  394.                 $savesessionvars["loginID"]=$_SESSION['loginID'];
  395.                 $savesessionvars["user"]=$_SESSION['user'];
  396.             }
  397.         }
  398.  
  399.         // change session name and id
  400.         // then delete this new session
  401.         // ==> the original admin session remains valid
  402.         // ==> it is possible to start a new session
  403.         session_name($initial_session_name);
  404.         if ($sessionhandler=='db')
  405.         {
  406.             adodb_session_regenerate_id();
  407.         }
  408.         elseif (session_regenerate_id() === false)
  409.         {
  410.             safe_die("Error Regenerating Session Id");
  411.         }
  412.         @session_destroy();
  413.  
  414.         // start new session
  415.         @session_start();
  416.         // regenerate id so that the header geenrated by previous
  417.         // regenerate_id is overwritten
  418.         // needed after clearall
  419.         if ($sessionhandler=='db')
  420.         {
  421.             adodb_session_regenerate_id();
  422.         }
  423.         elseif (session_regenerate_id() === false)
  424.         {
  425.             safe_die("Error Regenerating Session Id");
  426.         }
  427.  
  428.         if ( $previewright === true)
  429.         {
  430.             foreach ($savesessionvars as $sesskey => $sessval)
  431.             {
  432.                 $_SESSION[$sesskey]=$sessval;
  433.             }
  434.         }
  435.     }
  436.     else
  437.     { // already authorized
  438.         $previewright = true;
  439.     }
  440.  
  441.     if ($previewright === false)
  442.     {
  443.         // print an error message
  444.         if (isset($_REQUEST['rootdir']))
  445.         {
  446.             safe_die('You cannot start this script directly');
  447.         }
  448.         require_once(dirname(__FILE__).'/classes/core/language.php');
  449.         $baselang = GetBaseLanguageFromSurveyID($surveyid);
  450.         $clang = new limesurvey_lang($baselang);
  451.         //A nice exit
  452.         sendcacheheaders();
  453.         doHeader();
  454.  
  455.         echo templatereplace(file_get_contents("$standardtemplaterootdir/default/startpage.pstpl"));
  456.         echo "\t<div id='wrapper'>\n"
  457.         ."\t<p id='tokenmessage'>\n"
  458.         ."\t<span class='error'>".$clang->gT("ERROR")."</span><br /><br />\n"
  459.         ."\t".$clang->gT("We are sorry but you don't have permissions to do this.")."<br /><br />\n"
  460.         ."\t".sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$siteadminname,encodeEmail($siteadminemail))."<br /><br />\n"
  461.         ."\t</p>\n"
  462.         ."\t</div>\n";
  463.  
  464.         echo templatereplace(file_get_contents("$standardtemplaterootdir/default/endpage.pstpl"));
  465.         doFooter();
  466.         exit;
  467.     }
  468. }
  469. if (isset($_SESSION['srid']))
  470. {
  471.     $saved_id = $_SESSION['srid'];
  472. }
  473.  
  474. if (empty($_SESSION))
  475.         @session_start();
  476.  
  477. if (!isset($_SESSION['s_lang']) && (isset($move)) )
  478. // geez ... a session time out! RUN!
  479. {    if (isset($_REQUEST['rootdir']))
  480.     {
  481.         safe_die('You cannot start this script directly');
  482.     }
  483.     require_once(dirname(__FILE__).'/classes/core/language.php');
  484.     $baselang = GetBaseLanguageFromSurveyID($surveyid);
  485.     $clang = new limesurvey_lang($baselang);
  486.     //A nice exit
  487.     sendcacheheaders();
  488.     doHeader();
  489.  
  490.     echo templatereplace(file_get_contents("$standardtemplaterootdir/default/startpage.pstpl"));
  491.     echo "\t<div id='wrapper'>\n"
  492.     ."\t<p id='tokenmessage'>\n"
  493.     ."\t<span class='error'>".$clang->gT("ERROR")."</span><br /><br />\n"
  494.     ."\t".$clang->gT("We are sorry but your session has expired.")."<br /><br />\n"
  495.     ."\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.")."<br /><br />\n"
  496.     ."\t".sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$siteadminname,$siteadminemail)."<br /><br />\n"
  497.     ."\t</p>\n"
  498.     ."\t</div>\n";
  499.  
  500.     echo templatereplace(file_get_contents("$standardtemplaterootdir/default/endpage.pstpl"));
  501.     doFooter();
  502.     exit;
  503. };
  504.  
  505. if (isset($move) && (preg_match('/^changelang_/',$move)))
  506. {
  507.     // Then changing language from the language changer
  508.     $_POST['lang'] = substr($_POST['move'],11); // since sanitizing $move removes hyphen in languages like de-informal
  509. }
  510.  
  511. // Set the language of the survey, either from POST, GET parameter of session var
  512. if (isset($_POST['lang']) && $_POST['lang']!='')  // this one comes from the language question
  513. {
  514.     $templang = sanitize_languagecode($_POST['lang']);
  515.     $clang = SetSurveyLanguage( $surveyid, $templang);
  516.     UpdateSessionGroupList($templang);  // to refresh the language strings in the group list session variable
  517.  
  518.     UpdateFieldArray();        // to refresh question titles and question text
  519. }
  520. else
  521.     if (isset($_GET['lang']) && $surveyid)
  522.     {
  523.         $templang = sanitize_languagecode($_GET['lang']);
  524.         $clang = SetSurveyLanguage( $surveyid, $templang);
  525.         UpdateSessionGroupList($templang);  // to refresh the language strings in the group list session variable
  526.         UpdateFieldArray();        // to refresh question titles and question text
  527.     }
  528.     else
  529.         if (isset($_SESSION['s_lang']))
  530.         {
  531.             $clang = SetSurveyLanguage( $surveyid, $_SESSION['s_lang']);
  532.         }
  533.         elseif (isset($surveyid) && $surveyid)
  534.         {
  535.             $baselang = GetBaseLanguageFromSurveyID($surveyid);
  536.             $clang = SetSurveyLanguage( $surveyid, $baselang);
  537.         }
  538.  
  539.         if (isset($_REQUEST['embedded_inc']))
  540. {
  541.     safe_die('You cannot start this script directly');
  542. }
  543.  
  544.  
  545. // Get token
  546. if (!isset($token))
  547. {
  548.     $token=$clienttoken;
  549. }
  550.  
  551. //GET BASIC INFORMATION ABOUT THIS SURVEY
  552. $totalBoilerplatequestions =0;
  553. $thissurvey=getSurveyInfo($surveyid, $_SESSION['s_lang']);
  554.  
  555. if (isset($_GET['newtest']) && $_GET['newtest'] == "Y")
  556. {
  557.     //Removes any existing timer cookies so timers will start again
  558.     setcookie ("limesurvey_timers", "", time() - 3600);
  559. }
  560.  
  561. //SEE IF SURVEY USES TOKENS AND GROUP TOKENS
  562. $i = 0; //$tokensexist = 0;
  563. if ($surveyexists == 1 && tableExists('tokens_'.$thissurvey['sid']))
  564. {
  565.     $tokensexist = 1;
  566.  
  567. }
  568. else
  569. {
  570.     $tokensexist = 0;
  571.     unset ($_POST['token']);
  572.     unset ($_GET['token']);
  573.     unset($token);
  574.     unset($clienttoken);
  575. }
  576.  
  577.  
  578.  
  579.  
  580. //SET THE TEMPLATE DIRECTORY
  581. if (!$thissurvey['templatedir'])
  582. {
  583.     $thistpl=sGetTemplatePath($defaulttemplate);
  584. }
  585. else
  586. {
  587.     $thistpl=sGetTemplatePath($thissurvey['templatedir']);
  588. }
  589.  
  590.  
  591.  
  592. //MAKE SURE SURVEY HASN'T EXPIRED
  593. 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')
  594. {
  595.  
  596.     sendcacheheaders();
  597.     doHeader();
  598.  
  599.     echo templatereplace(file_get_contents("$thistpl/startpage.pstpl"));
  600.     echo "\t<div id='wrapper'>\n"
  601.     ."\t<p id='tokenmessage'>\n"
  602.     ."\t".$clang->gT("This survey is no longer available.")."<br /><br />\n"
  603.     ."\t".sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail']).".<br /><br />\n"
  604.     ."\t</p>\n"
  605.     ."\t</div>\n";
  606.  
  607.     echo templatereplace(file_get_contents("$thistpl/endpage.pstpl"));
  608.     doFooter();
  609.     exit;
  610. }
  611.  
  612. //MAKE SURE SURVEY IS ALREADY VALID
  613. 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')
  614. {
  615.     sendcacheheaders();
  616.     doHeader();
  617.  
  618.     echo templatereplace(file_get_contents("$thistpl/startpage.pstpl"));
  619.     echo "\t<div id='wrapper'>\n"
  620.     ."\t<p id='tokenmessage'>\n"
  621.     ."\t".$clang->gT("This survey is not yet started.")."<br /><br />\n"
  622.     ."\t".sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail']).".<br /><br />\n"
  623.     ."\t</p>\n"
  624.     ."\t</div>\n";
  625.  
  626.     echo templatereplace(file_get_contents("$thistpl/endpage.pstpl"));
  627.     doFooter();
  628.     exit;
  629. }
  630.  
  631. //CHECK FOR PREVIOUSLY COMPLETED COOKIE
  632. //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"
  633. $cookiename="PHPSID".returnglobal('sid')."STATUS";
  634. if (isset($_COOKIE[$cookiename]) && $_COOKIE[$cookiename] == "COMPLETE" && $thissurvey['usecookie'] == "Y" && $tokensexist != 1 && (!isset($_GET['newtest']) || $_GET['newtest'] != "Y"))
  635. {
  636.     sendcacheheaders();
  637.     doHeader();
  638.  
  639.     echo templatereplace(file_get_contents("$thistpl/startpage.pstpl"));
  640.     echo "\t<div id='wrapper'>\n"
  641.     ."\t<p id='tokenmessage'>\n"
  642.     ."\t<span class='error'>".$clang->gT("Error")."</span><br /><br />\n"
  643.     ."\t".$clang->gT("You have already completed this survey.")."<br /><br />\n"
  644.     ."\t".sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail'])."\n"
  645.     ."\t</p>\n"
  646.     ."\t</div>\n";
  647.  
  648.     echo templatereplace(file_get_contents("$thistpl/endpage.pstpl"));
  649.     doFooter();
  650.     exit;
  651. }
  652.  
  653.  
  654.  
  655.  
  656. //CHECK IF SURVEY ID DETAILS HAVE CHANGED
  657. if (isset($_SESSION['oldsid']))
  658. {
  659.     $oldsid=$_SESSION['oldsid'];
  660. }
  661.  
  662. if (!isset($oldsid))
  663. {
  664.     $_SESSION['oldsid'] = $surveyid;
  665. }
  666.  
  667. if (isset($oldsid) && $oldsid && $oldsid != $surveyid)
  668. {
  669.     $savesessionvars=Array();
  670.     if (isset($_SESSION['USER_RIGHT_PREVIEW']))
  671.     {
  672.         $savesessionvars["USER_RIGHT_PREVIEW"]=$surveyid;
  673.         $savesessionvars["loginID"]=$_SESSION['loginID'];
  674.         $savesessionvars["user"]=$_SESSION['user'];
  675.     }
  676.     session_unset();
  677.     $_SESSION['oldsid']=$surveyid;
  678.     foreach ($savesessionvars as $sesskey => $sessval)
  679.     {
  680.         $_SESSION[$sesskey]=$sessval;
  681.     }
  682. }
  683.  
  684.  
  685.  
  686. if (isset($_GET['loadall']) && $_GET['loadall'] == "reload")
  687. {
  688.     if (returnglobal('loadname') && returnglobal('loadpass'))
  689.     {
  690.         $_POST['loadall']="reload";
  691.     }
  692. }
  693.  
  694. //LOAD SAVED SURVEY
  695. if (isset($_POST['loadall']) && $_POST['loadall'] == "reload")
  696. {
  697.     $errormsg="";
  698.     // if (loadname is not set) or if ((loadname is set) and (loadname is NULL))
  699.     if (!isset($loadname) || (isset($loadname) && ($loadname == null)))
  700.     {
  701.         $errormsg .= $clang->gT("You did not provide a name")."<br />\n";
  702.     }
  703.     // if (loadpass is not set) or if ((loadpass is set) and (loadpass is NULL))
  704.     if (!isset($loadpass) || (isset($loadpass) && ($loadpass == null)))
  705.     {
  706.         $errormsg .= $clang->gT("You did not provide a password")."<br />\n";
  707.     }
  708.  
  709.     // if security question answer is incorrect
  710.     // Not called if scid is set in GET params (when using email save/reload reminder URL)
  711.     if (function_exists("ImageCreate") && captcha_enabled('saveandloadscreen',$thissurvey['usecaptcha']))
  712.     {
  713.         if ( (!isset($_POST['loadsecurity']) ||
  714.         !isset($_SESSION['secanswer']) ||
  715.         $_POST['loadsecurity'] != $_SESSION['secanswer']) &&
  716.         !isset($_GET['scid']))
  717.         {
  718.             $errormsg .= $clang->gT("The answer to the security question is incorrect.")."<br />\n";
  719.         }
  720.     }
  721.  
  722.     // Load session before loading the values from the saved data
  723.     if (isset($_GET['loadall']))
  724.     {
  725.         $totalquestions = buildsurveysession();
  726.     }
  727.  
  728.     $_SESSION['holdname']=$loadname; //Session variable used to load answers every page.
  729.     $_SESSION['holdpass']=$loadpass; //Session variable used to load answers every page.
  730.  
  731.     if ($errormsg == "") loadanswers();
  732.     $move = "movenext";
  733.     $_SESSION['LEMreload']=true;
  734.  
  735.     if ($errormsg)
  736.     {
  737.         $_POST['loadall'] = $clang->gT("Load Unfinished Survey");
  738.     }
  739. }
  740. //Allow loading of saved survey
  741. if (isset($_POST['loadall']) && $_POST['loadall'] == $clang->gT("Load Unfinished Survey"))
  742. {
  743.     require_once("load.php");
  744. }
  745.  
  746.  
  747. //Check if TOKEN is used for EVERY PAGE
  748. //This function fixes a bug where users able to submit two surveys/votes
  749. //by checking that the token has not been used at each page displayed.
  750. // bypass only this check at first page (Step=0) because
  751. // this check is done in buildsurveysession and error message
  752. // could be more interresting there (takes into accound captcha if used)
  753. if ($tokensexist == 1 && isset($token) && $token &&
  754. isset($_SESSION['step']) && $_SESSION['step']>0 && db_tables_exist($dbprefix.'tokens_'.$surveyid))
  755. {
  756.     //check if tokens actually haven't been already used
  757.     $areTokensUsed = usedTokens(db_quote(trim(strip_tags(returnglobal('token')))));
  758.     // check if token actually does exist
  759.     // check also if it is allowed to change survey after completion
  760.     if ($thissurvey['alloweditaftercompletion'] == 'Y' ) {
  761.         $tkquery = "SELECT * FROM ".db_table_name('tokens_'.$surveyid)." WHERE token='".db_quote($token)."' ";
  762.     } else {
  763.         $tkquery = "SELECT * FROM ".db_table_name('tokens_'.$surveyid)." WHERE token='".db_quote($token)."' AND (completed = 'N' or completed='')";
  764.     }
  765.     $tkresult = db_execute_num($tkquery); //Checked
  766.     $tokendata = $tkresult->FetchRow();
  767.     if ($tkresult->RecordCount()==0 || ($areTokensUsed && $thissurvey['alloweditaftercompletion'] != 'Y'))
  768.     {
  769.         sendcacheheaders();
  770.         doHeader();
  771.         //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
  772.  
  773.         echo templatereplace(file_get_contents("$thistpl/startpage.pstpl"));
  774.         echo templatereplace(file_get_contents("$thistpl/survey.pstpl"));
  775.         echo "\t<div id='wrapper'>\n"
  776.         ."\t<p id='tokenmessage'>\n"
  777.         ."\t".$clang->gT("This is a controlled survey. You need a valid token to participate.")."<br /><br />\n"
  778.         ."\t".$clang->gT("The token you have provided is either not valid, or has already been used.")."\n"
  779.         ."\t".sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']
  780.         ." (<a href='mailto:{$thissurvey['adminemail']}'>"
  781.         ."{$thissurvey['adminemail']}</a>)")."\n"
  782.         ."\t</p>\n"
  783.         ."\t</div>\n";
  784.  
  785.         echo templatereplace(file_get_contents("$thistpl/endpage.pstpl"));
  786.         killSession();
  787.         doFooter();
  788.         exit;
  789.     }
  790. }
  791. if ($tokensexist == 1 && isset($token) && $token && db_tables_exist($dbprefix.'tokens_'.$surveyid)) //check if token is in a valid time frame
  792. {
  793.  
  794.     // check also if it is allowed to change survey after completion
  795.     if ($thissurvey['alloweditaftercompletion'] == 'Y' ) {
  796.         $tkquery = "SELECT * FROM ".db_table_name('tokens_'.$surveyid)." WHERE token='".db_quote($token)."' ";
  797.     } else {
  798.         $tkquery = "SELECT * FROM ".db_table_name('tokens_'.$surveyid)." WHERE token='".db_quote($token)."' AND (completed = 'N' or completed='')";
  799.     }
  800.     $tkresult = db_execute_assoc($tkquery); //Checked
  801.     $tokendata = $tkresult->FetchRow();
  802.     if ((trim($tokendata['validfrom'])!='' && $tokendata['validfrom']>date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust)) ||
  803.     (trim($tokendata['validuntil'])!='' && $tokendata['validuntil']<date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust)))
  804.     {
  805.         sendcacheheaders();
  806.         doHeader();
  807.         //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
  808.  
  809.         echo templatereplace(file_get_contents("$thistpl/startpage.pstpl"));
  810.         echo templatereplace(file_get_contents("$thistpl/survey.pstpl"));
  811.         echo "\t<div id='wrapper'>\n"
  812.         ."\t<p id='tokenmessage'>\n"
  813.         ."\t".$clang->gT("We are sorry but you are not allowed to enter this survey.")."<br /><br />\n"
  814.         ."\t".$clang->gT("Your token seems to be valid but can be used only during a certain time period.")."<br />\n"
  815.         ."\t".sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']
  816.         ." (<a href='mailto:{$thissurvey['adminemail']}'>"
  817.         ."{$thissurvey['adminemail']}</a>)")."\n"
  818.         ."\t</p>\n"
  819.         ."\t</div>\n";
  820.  
  821.         echo templatereplace(file_get_contents("$thistpl/endpage.pstpl"));
  822.         doFooter();
  823.         killSession();
  824.         exit;
  825.     }
  826. }
  827.  
  828.  
  829.  
  830. //Clear session and remove the incomplete response if requested.
  831. if (isset($_GET['move']) && $_GET['move'] == "clearall")
  832. {
  833.     $s_lang = $_SESSION['s_lang'];
  834.     if (isset($_SESSION['srid']) && !isCompleted($surveyid,$_SESSION['srid']))
  835.     {
  836.         // delete the response but only if not already completed
  837.         $result = $connect->query('SELECT id FROM '.db_table_name('survey_'.$surveyid).' WHERE id='.$_SESSION['srid']." AND submitdate IS NULL");
  838.         if($result->RecordCount()>0)
  839.         {
  840.             $connect->query('DELETE FROM '.db_table_name('survey_'.$surveyid).' WHERE id='.$_SESSION['srid']." AND submitdate IS NULL");
  841.             // find out if there are any fuqt questions - checked
  842.             $fieldmap = createFieldMap($surveyid);
  843.             foreach ($fieldmap as $field)
  844.             {
  845.                 if ($field['type'] == "|" && !strpos($field['fieldname'], "_filecount"))
  846.                 {
  847.                     if (!isset($qid)) { $qid = array(); }
  848.                     $qid[] = $field['fieldname'];
  849.                 }
  850.             }
  851.             // if yes, extract the response json to those questions
  852.             if (isset($qid))
  853.             {
  854.                 $query = "SELECT * FROM ".db_table_name("survey_".$surveyid)." WHERE id=".$_SESSION['srid'];
  855.                 $result = db_execute_assoc($query);
  856.                 while ($row = $result->FetchRow())
  857.                 {
  858.                     foreach ($qid as $question)
  859.                     {
  860.                         $json = $row[$question];
  861.                         if ($json == "" || $json == NULL)
  862.                             continue;
  863.  
  864.                         // decode them
  865.                         $phparray = json_decode($json);
  866.  
  867.                         foreach ($phparray as $metadata)
  868.                         {
  869.                             $target = "{$uploaddir}/surveys/{$surveyid}/files/";
  870.                             // delete those files
  871.                             unlink($target.$metadata->filename);
  872.                         }
  873.                     }
  874.                 }
  875.             }
  876.             // done deleting uploaded files
  877.         }
  878.        
  879.         // also delete a record from saved_control when there is one, we can allway do it.
  880.         $connect->query('DELETE FROM '.db_table_name('saved_control'). ' WHERE srid='.$_SESSION['srid'].' AND sid='.$surveyid);
  881.     }
  882.     session_unset();
  883.     session_destroy();
  884.     setcookie(session_name(),"EXPIRED",time()-49999);
  885.     sendcacheheaders();
  886.     if (isset($_GET['redirect']))
  887.     {
  888.         session_write_close();
  889.         header("Location: {$_GET['redirect']}");
  890.     }
  891.     doHeader();
  892.     echo templatereplace(file_get_contents("$thistpl/startpage.pstpl"));
  893.     echo "\n\n<!-- JAVASCRIPT FOR CONDITIONAL QUESTIONS -->\n"
  894.     ."\t<script type='text/javascript'>\n"
  895.     ."\t<!--\n"
  896.     ."function checkconditions(value, name, type, evt_type)\n"
  897.     ."\t{\n"
  898.     ."\t}\n"
  899.     ."\t//-->\n"
  900.     ."\t</script>\n\n";
  901.  
  902.     //Present the clear all page using clearall.pstpl template
  903.     echo templatereplace(file_get_contents("$thistpl/clearall.pstpl"));
  904.  
  905.     echo templatereplace(file_get_contents("$thistpl/endpage.pstpl"));
  906.     doFooter();
  907.     exit;
  908. }
  909.  
  910. if (isset($_GET['newtest']) && $_GET['newtest'] == "Y")
  911. {
  912.     $savesessionvars=Array();
  913.     if (isset($_SESSION['USER_RIGHT_PREVIEW']))
  914.     {
  915.         $savesessionvars["USER_RIGHT_PREVIEW"]=$surveyid;
  916.         $savesessionvars["loginID"]=$_SESSION['loginID'];
  917.         $savesessionvars["user"]=$_SESSION['user'];
  918.     }
  919.     session_unset();
  920.     $_SESSION['oldsid']=$surveyid;
  921.     foreach ($savesessionvars as $sesskey => $sessval)
  922.     {
  923.         $_SESSION[$sesskey]=$sessval;
  924.     }
  925.     //DELETE COOKIE (allow to use multiple times)
  926.     setcookie($cookiename, "INCOMPLETE", time()-120);
  927.     //echo "Reset Cookie!";
  928. }
  929.  
  930. //Check to see if a refering URL has been captured.
  931. GetReferringUrl();
  932. // Let's do this only if
  933. //  - a saved answer record hasn't been loaded through the saved feature
  934. //  - the survey is not anonymous
  935. //  - the survey is active
  936. //  - a token information has been provided
  937. //  - the survey is setup to allow token-response-persistence
  938. if (!isset($_SESSION['srid']) && $thissurvey['anonymized'] == "N" && $thissurvey['active'] == "Y" && isset($token) && $token !='')
  939. {
  940.     // load previous answers if any (dataentry with nosubmit)
  941.     $srquery="SELECT id,submitdate,lastpage FROM {$thissurvey['tablename']}"
  942.     . " WHERE {$thissurvey['tablename']}.token='".db_quote($token)."' order by id desc";
  943.  
  944.     $result = db_select_limit_assoc($srquery,1);
  945.     if ($result->RecordCount()>0)
  946.     {
  947.         $row=$result->FetchRow();
  948.         if(($row['submitdate']==''  && $thissurvey['tokenanswerspersistence'] == 'Y' )|| ($row['submitdate']!='' && $thissurvey['alloweditaftercompletion'] == 'Y'))
  949.         {
  950.             $_SESSION['srid'] = $row['id'];
  951.             if (!is_null($row['lastpage']) && $row['submitdate']=='')
  952.             {
  953.                 $_SESSION['LEMtokenResume'] = true;
  954.                 $_SESSION['step'] = $row['lastpage'];
  955.             }
  956.         }
  957.         buildsurveysession();
  958.         loadanswers();
  959.     }
  960. }
  961.  
  962. if (isset($_REQUEST['action']) && ($_REQUEST['action'] == 'previewgroup')){
  963.     $thissurvey['format'] = 'G';
  964.     buildsurveysession(true);
  965. }
  966.  
  967. sendcacheheaders();
  968. //CALL APPROPRIATE SCRIPT
  969.  
  970. require_once("group.php");  // works for all survey styles - rename to navigation_controller.php?
  971.  
  972. if (isset($_POST['saveall']) || isset($flashmessage))
  973. {
  974.     echo "<script language='JavaScript'> $(document).ready( function() {alert('".$clang->gT("Your responses were successfully saved.","js")."');}) </script>";
  975. }
  976.  
  977. function loadanswers()
  978. {
  979.     global $dbprefix,$surveyid,$errormsg;
  980.     global $thissurvey, $thisstep, $clang;
  981.     global $databasetype, $clienttoken;
  982.     $scid=returnglobal('scid');
  983.     if (isset($_POST['loadall']) && $_POST['loadall'] == "reload")
  984.     {
  985.         $query = "SELECT * FROM ".db_table_name('saved_control')." INNER JOIN {$thissurvey['tablename']}
  986.        ON ".db_table_name('saved_control').".srid = {$thissurvey['tablename']}.id
  987.        WHERE ".db_table_name('saved_control').".sid=$surveyid\n";
  988.         if (isset($scid)) //Would only come from email
  989.  
  990.         {
  991.             $query .= "AND ".db_table_name('saved_control').".scid={$scid}\n";
  992.         }
  993.         $query .="AND ".db_table_name('saved_control').".identifier = '".auto_escape($_SESSION['holdname'])."' ";
  994.  
  995.         if ($databasetype=='odbc_mssql' || $databasetype=='odbtp' || $databasetype=='mssql_n' || $databasetype=='mssqlnative')
  996.         {
  997.             $query .="AND CAST(".db_table_name('saved_control').".access_code as varchar(32))= '".md5(auto_unescape($_SESSION['holdpass']))."'\n";
  998.         }
  999.         else
  1000.         {
  1001.             $query .="AND ".db_table_name('saved_control').".access_code = '".md5(auto_unescape($_SESSION['holdpass']))."'\n";
  1002.         }
  1003.     }
  1004.     elseif (isset($_SESSION['srid']))
  1005.     {
  1006.         $query = "SELECT * FROM {$thissurvey['tablename']}
  1007.        WHERE {$thissurvey['tablename']}.id=".$_SESSION['srid']."\n";
  1008.     }
  1009.     else
  1010.     {
  1011.         return;
  1012.     }
  1013.     $result = db_execute_assoc($query) or safe_die ("Error loading results<br />$query<br />".$connect->ErrorMsg());   //Checked
  1014.     if ($result->RecordCount() < 1)
  1015.     {
  1016.         $errormsg .= $clang->gT("There is no matching saved survey")."<br />\n";
  1017.     }
  1018.     else
  1019.     {
  1020.         //A match has been found. Let's load the values!
  1021.         //If this is from an email, build surveysession first
  1022.         $_SESSION['LEMtokenResume']=true;
  1023.  
  1024.         $row=$result->FetchRow();
  1025.         foreach ($row as $column => $value)
  1026.         {
  1027.             if ($column == "token")
  1028.             {
  1029.                 $clienttoken=$value;
  1030.                 $token=$value;
  1031.             }
  1032.             elseif ($column == "saved_thisstep" && $thissurvey['alloweditaftercompletion'] != 'Y' )
  1033.             {
  1034.                 $_SESSION['step']=$value;
  1035.                 $thisstep=$value-1;
  1036.             }
  1037.             elseif ($column =='lastpage' && isset($_GET['token']) && $thissurvey['alloweditaftercompletion'] != 'Y' )
  1038.             {
  1039.                 if ($value<1) $value=1;
  1040.                 $_SESSION['step']=$value;
  1041.                 $thisstep=$value-1;
  1042.             }
  1043.             /*
  1044.             Commented this part out because otherwise startlanguage would overwrite any other language during a running survey.
  1045.             We will need a new field named 'endlanguage' to save the current language (for example for returning participants)
  1046.             /the language the survey was completed in.
  1047.             elseif ($column =='startlanguage')
  1048.             {
  1049.             $clang = SetSurveyLanguage( $surveyid, $value);
  1050.             UpdateSessionGroupList($value);  // to refresh the language strings in the group list session variable
  1051.             UpdateFieldArray();        // to refresh question titles and question text
  1052.             }*/
  1053.             elseif ($column == "scid")
  1054.             {
  1055.                 $_SESSION['scid']=$value;
  1056.             }
  1057.             elseif ($column == "srid")
  1058.             {
  1059.                 $_SESSION['srid']=$value;
  1060.             }
  1061.             elseif ($column == "datestamp")
  1062.             {
  1063.                 $_SESSION['datestamp']=$value;
  1064.             }
  1065.             if ($column == "startdate")
  1066.             {
  1067.                 $_SESSION['startdate']=$value;
  1068.             }
  1069.             else
  1070.             {
  1071.                 //Only make session variables for those in insertarray[]
  1072.                 if (in_array($column, $_SESSION['insertarray']))
  1073.                 {
  1074.                     //                    if (($_SESSION['fieldmap'][$column]['type'] == 'N' ||
  1075.                     //                            $_SESSION['fieldmap'][$column]['type'] == 'K' ||
  1076.                     //                            $_SESSION['fieldmap'][$column]['type'] == 'D') && $value == null)
  1077.                     //                    {   // For type N,K,D NULL in DB is to be considered as NoAnswer in any case.
  1078.                     //                        // We need to set the _SESSION[field] value to '' in order to evaluate conditions.
  1079.                     //                        // This is especially important for the deletenonvalue feature,
  1080.                     //                        // otherwise we would erase any answer with condition such as EQUALS-NO-ANSWER on such
  1081.                     //                        // question types (NKD)
  1082.                     //                        $_SESSION[$column]='';
  1083.                     //                    }
  1084.                     //                    else
  1085.                     //                    {
  1086.                     $_SESSION[$column]=$value;
  1087.                     //                }
  1088.                 }  // if (in_array(
  1089.             }  // else
  1090.         } // foreach
  1091.     }
  1092.     return true;
  1093. }
  1094.  
  1095. function makegraph($currentstep, $total)
  1096. {
  1097.     global $thissurvey;
  1098.     global $publicurl, $clang;
  1099.  
  1100.     $size = intval(($currentstep-1)/$total*100);
  1101.  
  1102.     $graph = '<script type="text/javascript">
  1103.    $(function() {
  1104.    $("#progressbar").progressbar({
  1105.    value: '.$size.'
  1106.    });
  1107.    });';
  1108.     if (getLanguageRTL($clang->langcode))
  1109.     {
  1110.         $graph.='
  1111.        $(document).ready(function() {
  1112.        $("div.ui-progressbar-value").removeClass("ui-corner-left");
  1113.        $("div.ui-progressbar-value").addClass("ui-corner-right");
  1114.        });';
  1115.     }
  1116.     $graph.='
  1117.    </script>
  1118.  
  1119.    <div id="progress-wrapper">
  1120.    <span class="hide">'.sprintf($clang->gT('You have completed %s%% of this survey'),$size).'</span>
  1121.    <div id="progress-pre">';
  1122.     if (getLanguageRTL($clang->langcode))
  1123.     {
  1124.         $graph.='100%';
  1125.     }
  1126.     else
  1127.     {
  1128.         $graph.='0%';
  1129.     }
  1130.  
  1131.     $graph.='</div>
  1132.    <div id="progressbar"></div>
  1133.    <div id="progress-post">';
  1134.     if (getLanguageRTL($clang->langcode))
  1135.     {
  1136.         $graph.='0%';
  1137.     }
  1138.     else
  1139.     {
  1140.         $graph.='100%';
  1141.     }
  1142.     $graph.='</div>
  1143.    </div>';
  1144.  
  1145.     if ($size == 0) // Progress bar looks dumb if 0
  1146.  
  1147.     {
  1148.         $graph.='
  1149.        <script type="text/javascript">
  1150.        $(document).ready(function() {
  1151.        $("div.ui-progressbar-value").hide();
  1152.        });
  1153.        </script>';
  1154.     }
  1155.  
  1156.     return $graph;
  1157. }
  1158.  
  1159.  
  1160. function makelanguagechanger()
  1161. {
  1162.     global $relativeurl;
  1163.     if (!isset($surveyid))
  1164.     {
  1165.         $surveyid=returnglobal('sid');
  1166.     }
  1167.     if (isset($surveyid))
  1168.     {
  1169.         $slangs = GetAdditionalLanguagesFromSurveyID($surveyid);
  1170.         $sBaseLanguage = GetBaseLanguageFromSurveyID($surveyid);
  1171.  
  1172.     }
  1173.  
  1174.     // TODO - When is this needed?
  1175.     $token = sanitize_token(returnglobal('token'));
  1176.     if ($token != '')
  1177.     {
  1178.         $tokenparam = "&token=$token";
  1179.     }
  1180.     else
  1181.     {
  1182.         $tokenparam = "";
  1183.     }
  1184.     $previewgrp = false;
  1185.     if (isset($_REQUEST['action']))
  1186.         if ($_REQUEST['action']=='previewgroup')
  1187.             $previewgrp = true;
  1188.  
  1189.         if (!empty($slangs))
  1190.     {
  1191.         if (isset($_SESSION['s_lang']) && $_SESSION['s_lang'] != '')
  1192.         {
  1193.             $lang = sanitize_languagecode($_SESSION['s_lang']);
  1194.         }
  1195.         else if(isset($_POST['lang']) && $_POST['lang']!='')
  1196.             {
  1197.                 $lang = sanitize_languagecode($_POST['lang']);
  1198.             }
  1199.             else if (isset($_GET['lang']) && $_GET['lang'] != '')
  1200.                 {
  1201.                     $lang = sanitize_languagecode($_GET['lang']);
  1202.                 }
  1203.                 else
  1204.                 {
  1205.                     $lang = $sBaseLanguage;
  1206.         }
  1207.         $slangs[]=$sBaseLanguage;
  1208.         $aAllLanguages=getLanguageData();
  1209.         $slangs=array_keys(array_intersect_key($aAllLanguages,array_flip($slangs))); // Sort languages by their locale name
  1210.  
  1211.         // Changed how language changer works so that posts any currently set values.  This also ensures that token (and other) parmeters are also posted.
  1212.         //        $htmlcode ="<select name=\"select\" class='languagechanger' onchange=\"javascript:window.location=this.value\">\n";
  1213.         $htmlcode ="<select name=\"select\" class='languagechanger' "
  1214.         . " onchange=\"javascript:$('[name=move]').val('changelang_'+ this.value);$('#limesurvey').submit();\">\n";
  1215.  
  1216.         $sAddToURL = "";
  1217.         $sTargetURL = "$relativeurl/index.php";
  1218.         if ($previewgrp){
  1219.             $sAddToURL = "&amp;action=previewgroup&amp;gid={$_REQUEST['gid']}";
  1220.             $sTargetURL = "";
  1221.         }
  1222.         foreach ($slangs as $otherlang)
  1223.         {
  1224.             //            $htmlcode .= "\t<option value=\"$sTargetURL?sid=". $surveyid ."&amp;lang=". $otherlang ."$tokenparam$sAddToURL\" ";
  1225.             $htmlcode .= "\t<option value=\"". $otherlang ."\" ";
  1226.  
  1227.             if($otherlang == $lang)
  1228.             {
  1229.                 $htmlcode .= " selected=\"selected\" ";
  1230.             }
  1231.             $htmlcode .= ">".getLanguageNameFromCode($otherlang,false)."</option>\n";
  1232.         }
  1233.  
  1234.         $htmlcode .= "</select>\n";
  1235.         //    . "</form>";
  1236.  
  1237.         return $htmlcode;
  1238.     } elseif (!isset($surveyid))
  1239.     {
  1240.         global $defaultlang, $baselang;
  1241.         $htmlcode = "<select name=\"select\" class='languagechanger' onchange=\"javascript:window.location=this.value\">\n";
  1242.         $htmlcode .= "<option value=\"$relativeurl/index.php?lang=". $defaultlang ."$tokenparam\">".getLanguageNameFromCode($defaultlang,false)."</option>\n";
  1243.         foreach(getlanguagedata() as $key=>$val)
  1244.         {
  1245.             $htmlcode .= "\t<option value=\"$relativeurl/index.php?lang=".$key."$tokenparam\" ";
  1246.             $htmlcode .= ">".getLanguageNameFromCode($key,false)."</option>\n";
  1247.         }
  1248.         $htmlcode .= "</select>\n";
  1249.         return $htmlcode;
  1250.     }
  1251. }
  1252.  
  1253. function checkUploadedFileValidity($move, $backok=null)
  1254. {
  1255.     global $connect, $thisstep, $clang;
  1256.     if (!isset($backok) || $backok != "Y")
  1257.     {
  1258.         global $dbprefix;
  1259.         $fieldmap = createFieldMap(returnglobal('sid'));
  1260.  
  1261.         if (isset($_POST['fieldnames']) && $_POST['fieldnames']!="")
  1262.         {
  1263.             $fields = explode("|", $_POST['fieldnames']);
  1264.  
  1265.             foreach ($fields as $field)
  1266.             {
  1267.                 if ($fieldmap[$field]['type'] == "|" && !strrpos($fieldmap[$field]['fieldname'], "_filecount"))
  1268.                 {
  1269.                     $validation = array();
  1270.  
  1271.                     $query = "SELECT * FROM ".$dbprefix."question_attributes WHERE qid = ".$fieldmap[$field]['qid'];
  1272.                     $result = db_execute_assoc($query);
  1273.                     while ($row = $result->FetchRow())
  1274.                         $validation[$row['attribute']] = $row['value'];
  1275.  
  1276.                     $filecount = 0;
  1277.  
  1278.                     $json = $_POST[$field];
  1279.                     // if name is blank, its basic, hence check
  1280.                     // else, its ajax, don't check, bypass it.
  1281.  
  1282.                     if ($json != "" && $json != "[]")
  1283.                     {
  1284.                         $phparray = json_decode(stripslashes($json));
  1285.                         if ($phparray[0]->size != "")
  1286.                         { // ajax
  1287.                             $filecount = count($phparray);
  1288.                         }
  1289.                         else
  1290.                         { // basic
  1291.                             for ($i = 1; $i <= $validation['max_num_of_files']; $i++)
  1292.                             {
  1293.                                 if (!isset($_FILES[$field."_file_".$i]) || $_FILES[$field."_file_".$i]['name'] == '')
  1294.                                     continue;
  1295.  
  1296.                                 $filecount++;
  1297.  
  1298.                                 $file = $_FILES[$field."_file_".$i];
  1299.  
  1300.                                 // File size validation
  1301.                                 if ($file['size'] > $validation['max_filesize'] * 1000)
  1302.                                 {
  1303.                                     $filenotvalidated = array();
  1304.                                     $filenotvalidated[$field."_file_".$i] = sprintf($clang->gT("Sorry, the uploaded file (%s) is larger than the allowed filesize of %s KB."), $file['size'], $validation['max_filesize']);
  1305.                                     $append = true;
  1306.                                 }
  1307.  
  1308.                                 // File extension validation
  1309.                                 $pathinfo = pathinfo(basename($file['name']));
  1310.                                 $ext = $pathinfo['extension'];
  1311.  
  1312.                                 $validExtensions = explode(",", $validation['allowed_filetypes']);
  1313.                                 if (!(in_array($ext, $validExtensions)))
  1314.                                 {
  1315.                                     if (isset($append) && $append)
  1316.                                     {
  1317.                                         $filenotvalidated[$field."_file_".$i] .= sprintf($clang->gT("Sorry, only %s extensions are allowed!"),$validation['allowed_filetypes']);
  1318.                                         unset($append);
  1319.                                     }
  1320.                                     else
  1321.                                     {
  1322.                                         $filenotvalidated = array();
  1323.                                         $filenotvalidated[$field."_file_".$i] .= sprintf($clang->gT("Sorry, only %s extensions are allowed!"),$validation['allowed_filetypes']);
  1324.                                     }
  1325.                                 }
  1326.                             }
  1327.                         }
  1328.                     }
  1329.                     else
  1330.                         $filecount = 0;
  1331.  
  1332.                     if (isset($validation['min_num_of_files']) && $filecount < $validation['min_num_of_files'] && LimeExpressionManager::QuestionIsRelevant($fieldmap[$field]['qid']))
  1333.                     {
  1334.                         $filenotvalidated = array();
  1335.                         $filenotvalidated[$field] = $clang->gT("The minimum number of files has not been uploaded.");
  1336.                     }
  1337.                 }
  1338.             }
  1339.         }
  1340.         if (isset($filenotvalidated))
  1341.         {
  1342.             if (isset($move) && $move == "moveprev")
  1343.                 $_SESSION['step'] = $thisstep;
  1344.             if (isset($move) && $move == "movenext")
  1345.                 $_SESSION['step'] = $thisstep;
  1346.             return $filenotvalidated;
  1347.         }
  1348.     }
  1349.     if (!isset($filenotvalidated))
  1350.         return false;
  1351.     else
  1352.         return $filenotvalidated;
  1353. }
  1354.  
  1355. function addtoarray_single($array1, $array2)
  1356. {
  1357.     //Takes two single element arrays and adds second to end of first if value exists
  1358.     if (is_array($array2))
  1359.     {
  1360.         foreach ($array2 as $ar)
  1361.         {
  1362.             if ($ar && $ar !== null)
  1363.             {
  1364.                 $array1[]=$ar;
  1365.             }
  1366.         }
  1367.     }
  1368.     return $array1;
  1369. }
  1370.  
  1371. function remove_nulls_from_array($array)
  1372. {
  1373.     foreach ($array as $ar)
  1374.     {
  1375.         if ($ar !== null)
  1376.         {
  1377.             $return[]=$ar;
  1378.         }
  1379.     }
  1380.     if (isset($return))
  1381.     {
  1382.         return $return;
  1383.     }
  1384.     else
  1385.     {
  1386.         return false;
  1387.     }
  1388. }
  1389.  
  1390.  
  1391. /**
  1392. * Marks a tokens as completed and sends a confirmation email to the participiant.
  1393. * If $quotaexit is set to true then the user exited the survey due to a quota
  1394. * restriction and the according token is only marked as 'Q'
  1395. *
  1396. * @param mixed $quotaexit
  1397. */
  1398. function submittokens($quotaexit=false)
  1399. {
  1400.     global $thissurvey, $timeadjust, $emailcharset ;
  1401.     global $dbprefix, $surveyid, $connect;
  1402.     global $sitename, $thistpl, $clang, $clienttoken;
  1403.  
  1404.     // Shift the date due to global timeadjust setting
  1405.     $today = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i", $timeadjust);
  1406.  
  1407.     // check how many uses the token has left
  1408.     $usesquery = "SELECT usesleft FROM {$dbprefix}tokens_$surveyid WHERE token='".db_quote($clienttoken)."'";
  1409.     $usesresult = db_execute_assoc($usesquery);
  1410.     $usesrow = $usesresult->FetchRow();
  1411.     if (isset($usesrow)) { $usesleft = $usesrow['usesleft']; }
  1412.  
  1413.     $utquery = "UPDATE {$dbprefix}tokens_$surveyid\n";
  1414.     if ($quotaexit==true)
  1415.     {
  1416.         $utquery .= "SET completed='Q', usesleft=usesleft-1\n";
  1417.     }
  1418.     elseif (bIsTokenCompletedDatestamped($thissurvey))
  1419.     {
  1420.         if (isset($usesleft) && $usesleft<=1)
  1421.         {
  1422.             $utquery .= "SET usesleft=usesleft-1, completed='$today'\n";
  1423.         }
  1424.         else
  1425.         {
  1426.             $utquery .= "SET usesleft=usesleft-1\n";
  1427.         }
  1428.     }
  1429.     else
  1430.     {
  1431.         if (isset($usesleft) && $usesleft<=1)
  1432.         {
  1433.             $utquery .= "SET usesleft=usesleft-1, completed='Y'\n";
  1434.         }
  1435.         else
  1436.         {
  1437.             $utquery .= "SET usesleft=usesleft-1\n";
  1438.         }
  1439.     }
  1440.     $utquery .= "WHERE token='".db_quote($clienttoken)."'";
  1441.  
  1442.     $utresult = $connect->Execute($utquery) or safe_die ("Couldn't update tokens table!<br />\n$utquery<br />\n".$connect->ErrorMsg());     //Checked
  1443.  
  1444.     if ($quotaexit==false)
  1445.     {
  1446.         // TLR change to put date into sent and completed
  1447.         $cnfquery = "SELECT * FROM ".db_table_name("tokens_$surveyid")." WHERE token='".db_quote($clienttoken)."' AND completed!='N' AND completed!=''";
  1448.  
  1449.         $cnfresult = db_execute_assoc($cnfquery);       //Checked
  1450.         $cnfrow = $cnfresult->FetchRow();
  1451.         if (isset($cnfrow))
  1452.         {
  1453.             $from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>";
  1454.             $to = $cnfrow['email'];
  1455.             $subject=$thissurvey['email_confirm_subj'];
  1456.  
  1457.             $fieldsarray["{ADMINNAME}"]=$thissurvey['adminname'];
  1458.             $fieldsarray["{ADMINEMAIL}"]=$thissurvey['adminemail'];
  1459.             $fieldsarray["{SURVEYNAME}"]=$thissurvey['name'];
  1460.             $fieldsarray["{SURVEYDESCRIPTION}"]=$thissurvey['description'];
  1461.             $fieldsarray["{FIRSTNAME}"]=$cnfrow['firstname'];
  1462.             $fieldsarray["{LASTNAME}"]=$cnfrow['lastname'];
  1463.             $fieldsarray["{TOKEN}"]=$clienttoken;
  1464.             $attrfieldnames=GetAttributeFieldnames($surveyid);
  1465.             foreach ($attrfieldnames as $attr_name)
  1466.             {
  1467.                 $fieldsarray["{".strtoupper($attr_name)."}"]=$cnfrow[$attr_name];
  1468.             }
  1469.  
  1470.             $dateformatdatat=getDateFormatData($thissurvey['surveyls_dateformat']);
  1471.             $numberformatdatat = getRadixPointData($thissurvey['surveyls_numberformat']);
  1472.             $fieldsarray["{EXPIRY}"]=convertDateTimeFormat($thissurvey["expiry"],'Y-m-d H:i:s',$dateformatdatat['phpdate']);
  1473.  
  1474.             $subject=ReplaceFields($subject, $fieldsarray, true);
  1475.  
  1476.             $subject=html_entity_decode($subject,ENT_QUOTES,$emailcharset);
  1477.  
  1478.             if (getEmailFormat($surveyid) == 'html')
  1479.             {
  1480.                 $ishtml=true;
  1481.             }
  1482.             else
  1483.             {
  1484.                 $ishtml=false;
  1485.             }
  1486.  
  1487.             if (trim(strip_tags($thissurvey['email_confirm'])) != "")
  1488.             {
  1489.                 $message=$thissurvey['email_confirm'];
  1490.                 $message=ReplaceFields($message, $fieldsarray, true);
  1491.  
  1492.                 if (!$ishtml)
  1493.                 {
  1494.                     $message=strip_tags(br2nl(html_entity_decode($message,ENT_QUOTES,$emailcharset)));
  1495.                 }
  1496.                 else
  1497.                 {
  1498.                     $message=html_entity_decode($message,ENT_QUOTES, $emailcharset );
  1499.                 }
  1500.  
  1501.                 //Only send confirmation email if there is a valid email address
  1502.                 if (validate_email($cnfrow['email']))
  1503.                 {
  1504.                     SendEmailMessage(null,$message, $subject, $to, $from, $sitename,$ishtml);
  1505.                 }
  1506.             }
  1507.             else
  1508.             {
  1509.                 //There is nothing in the message, so don't send a confirmation email
  1510.                 //This section only here as placeholder to indicate new feature :-)
  1511.             }
  1512.         }
  1513.     }
  1514. }
  1515.  
  1516. /**
  1517. * Send a submit notification to the email address specified in the notifications tab in the survey settings
  1518. */
  1519. function SendSubmitNotifications()
  1520. {
  1521.     global $thissurvey, $debug;
  1522.     global $dbprefix, $clang, $emailcharset;
  1523.     global $sitename, $homeurl, $surveyid, $publicurl, $maildebug, $tokensexist;
  1524.  
  1525.     $bIsHTML = ($thissurvey['htmlemail'] == 'Y');
  1526.  
  1527.     $aReplacementVars=array();
  1528.  
  1529.  
  1530.     if ($thissurvey['allowsave'] == "Y" && isset($_SESSION['scid']))
  1531.     {
  1532.         $aReplacementVars['RELOADURL']="{$publicurl}/index.php?sid={$surveyid}&loadall=reload&scid=".$_SESSION['scid']."&loadname=".urlencode($_SESSION['holdname'])."&loadpass=".urlencode($_SESSION['holdpass']);
  1533.         if ($bIsHTML)
  1534.         {
  1535.             $aReplacementVars['RELOADURL']="<a href='{$aReplacementVars['RELOADURL']}'>{$aReplacementVars['RELOADURL']}</a>";
  1536.         }
  1537.     }
  1538.     else
  1539.     {
  1540.         $aReplacementVars['RELOADURL']='';
  1541.     }
  1542.  
  1543.     $aReplacementVars['ADMINNAME'] = $thissurvey['adminname'];
  1544.     $aReplacementVars['ADMINEMAIL'] = $thissurvey['adminemail'];
  1545.     $aReplacementVars['VIEWRESPONSEURL']="{$homeurl}/admin.php?action=browse&sid={$surveyid}&subaction=id&id={$_SESSION['srid']}";
  1546.     $aReplacementVars['EDITRESPONSEURL']="{$homeurl}/admin.php?action=dataentry&sid={$surveyid}&subaction=edit&surveytable=survey_{$surveyid}&id=".$_SESSION['srid'];
  1547.     $aReplacementVars['STATISTICSURL']="{$homeurl}/admin.php?action=statistics&sid={$surveyid}";
  1548.     if ($bIsHTML)
  1549.     {
  1550.         $aReplacementVars['VIEWRESPONSEURL']="<a href='{$aReplacementVars['VIEWRESPONSEURL']}'>{$aReplacementVars['VIEWRESPONSEURL']}</a>";
  1551.         $aReplacementVars['EDITRESPONSEURL']="<a href='{$aReplacementVars['EDITRESPONSEURL']}'>{$aReplacementVars['EDITRESPONSEURL']}</a>";
  1552.         $aReplacementVars['STATISTICSURL']="<a href='{$aReplacementVars['STATISTICSURL']}'>{$aReplacementVars['STATISTICSURL']}</a>";
  1553.     }
  1554.     $aReplacementVars['ANSWERTABLE']='';
  1555.     $aEmailResponseTo=array();
  1556.     $aEmailNotificationTo=array();
  1557.     $sResponseData="";
  1558.  
  1559.     if (!empty($thissurvey['emailnotificationto']))
  1560.     {
  1561.         $aRecipient=explode(";", $thissurvey['emailnotificationto']);
  1562.         {
  1563.             foreach($aRecipient as $sRecipient)
  1564.             {
  1565.                 $sRecipient=ReplaceFields($sRecipient, array('ADMINEMAIL' =>$thissurvey['adminemail'] ), true); // Only need INSERTANS, ADMINMAIL and TOKEN
  1566.                 if(validate_email($sRecipient))
  1567.                 {
  1568.                     $aEmailNotificationTo[]=$sRecipient;
  1569.                 }
  1570.             }
  1571.         }
  1572.     }
  1573.  
  1574.     if (!empty($thissurvey['emailresponseto']))
  1575.     {
  1576.         if (isset($_SESSION['token']) && $_SESSION['token'] != '' && db_tables_exist($dbprefix.'tokens_'.$surveyid))
  1577.         {
  1578.             //Gather token data for tokenised surveys
  1579.             $_SESSION['thistoken']=getTokenData($surveyid, $_SESSION['token']);
  1580.         }
  1581.         // there was no token used so lets remove the token field from insertarray
  1582.         elseif ($_SESSION['insertarray'][0]=='token')
  1583.         {
  1584.             unset($_SESSION['insertarray'][0]);
  1585.         }
  1586.         //Make an array of email addresses to send to
  1587.         $aRecipient=explode(";", $thissurvey['emailresponseto']);
  1588.         {
  1589.             foreach($aRecipient as $sRecipient)
  1590.             {
  1591.                 $sRecipient=ReplaceFields($sRecipient, array('ADMINEMAIL' =>$thissurvey['adminemail'] ), true); // Only need INSERTANS, ADMINMAIL and TOKEN
  1592.                 if(validate_email($sRecipient))
  1593.                 {
  1594.                     $aEmailResponseTo[]=$sRecipient;
  1595.                 }
  1596.             }
  1597.         }
  1598.  
  1599.         $aFullResponseTable=aGetFullResponseTable($surveyid,$_SESSION['srid'],$_SESSION['s_lang']);
  1600.         $ResultTableHTML = "<table class='printouttable' >\n";
  1601.         $ResultTableText ="\n\n";
  1602.         $oldgid = 0;
  1603.         $oldqid = 0;
  1604.         foreach ($aFullResponseTable as $sFieldname=>$fname)
  1605.         {
  1606.             if (substr($sFieldname,0,4)=='gid_')
  1607.             {
  1608.  
  1609.                 $ResultTableHTML .= "\t<tr class='printanswersgroup'><td colspan='2'>{$fname[0]}</td></tr>\n";
  1610.                 $ResultTableText .="\n{$fname[0]}\n\n";
  1611.             }
  1612.             elseif (substr($sFieldname,0,4)=='qid_')
  1613.             {
  1614.                 $ResultTableHTML .= "\t<tr class='printanswersquestionhead'><td  colspan='2'>{$fname[0]}</td></tr>\n";
  1615.                 $ResultTableText .="\n{$fname[0]}\n";
  1616.             }
  1617.             else
  1618.             {
  1619.                 $ResultTableHTML .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>";
  1620.                 $ResultTableText .="     {$fname[0]} {$fname[1]}: {$fname[2]}\n";
  1621.             }
  1622.         }
  1623.  
  1624.         $ResultTableHTML .= "</table>\n";
  1625.         $ResultTableText .= "\n\n";
  1626.         if ($bIsHTML)
  1627.         {
  1628.             $aReplacementVars['ANSWERTABLE']=$ResultTableHTML;
  1629.         }
  1630.         else
  1631.         {
  1632.             $aReplacementVars['ANSWERTABLE']=$ResultTableText;
  1633.         }
  1634.     }
  1635.  
  1636.     $sFrom = $thissurvey['adminname'].' <'.$thissurvey['adminemail'].'>';
  1637.     if (count($aEmailNotificationTo)>0)
  1638.     {
  1639.         $sMessage=templatereplace($thissurvey['email_admin_notification'],$aReplacementVars,($thissurvey['anonymized'] == "Y"));
  1640.         $sSubject=templatereplace($thissurvey['email_admin_notification_subj'],$aReplacementVars,($thissurvey['anonymized'] == "Y"));
  1641.         $oMail = new PHPMailer;
  1642.         foreach ($aEmailNotificationTo as $sRecipient)
  1643.         {
  1644.             if (!SendEmailMessage($oMail, $sMessage, $sSubject, $sRecipient, $sFrom, $sitename, true, getBounceEmail($surveyid)))
  1645.             {
  1646.                 if ($debug>0)
  1647.                 {
  1648.                     echo '<br />Email could not be sent. Reason: '.$maildebug.'<br/>';
  1649.                 }
  1650.             }
  1651.         }
  1652.         $oMail->SmtpClose();
  1653.     }
  1654.  
  1655.     if (count($aEmailResponseTo)>0)
  1656.     {
  1657.         $sMessage=templatereplace($thissurvey['email_admin_responses'],$aReplacementVars);
  1658.         $sSubject=templatereplace($thissurvey['email_admin_responses_subj'],$aReplacementVars);
  1659.         $mail = new PHPMailer;
  1660.         foreach ($aEmailResponseTo as $sRecipient)
  1661.         {
  1662.             if (!SendEmailMessage($mail,$sMessage, $sSubject, $sRecipient, $sFrom, $sitename, true, getBounceEmail($surveyid)))
  1663.             {
  1664.                 if ($debug>0)
  1665.                 {
  1666.                     echo '<br />Email could not be sent. Reason: '.$maildebug.'<br/>';
  1667.                 }
  1668.             }
  1669.         }
  1670.         $mail->SmtpClose();
  1671.     }
  1672.  
  1673.  
  1674. }
  1675.  
  1676. function submitfailed($errormsg='')
  1677. {
  1678.     global $debug;
  1679.     global $thissurvey, $clang;
  1680.     global $thistpl, $subquery, $surveyid, $connect;
  1681.  
  1682.     $completed = "<br /><strong><font size='2' color='red'>"
  1683.     . $clang->gT("Did Not Save")."</strong></font><br /><br />\n\n"
  1684.     . $clang->gT("An unexpected error has occurred and your responses cannot be saved.")."<br /><br />\n";
  1685.     if ($thissurvey['adminemail'])
  1686.     {
  1687.         $completed .= $clang->gT("Your responses have not been lost and have been emailed to the survey administrator and will be entered into our database at a later point.")."<br /><br />\n";
  1688.         if ($debug>0)
  1689.         {
  1690.             $completed.='Error message: '.htmlspecialchars($errormsg).'<br />';
  1691.         }
  1692.         $email=$clang->gT("An error occurred saving a response to survey id","unescaped")." ".$thissurvey['name']." - $surveyid\n\n";
  1693.         $email .= $clang->gT("DATA TO BE ENTERED","unescaped").":\n";
  1694.         foreach ($_SESSION['insertarray'] as $value)
  1695.         {
  1696.             $email .= "$value: {$_SESSION[$value]}\n";
  1697.         }
  1698.         $email .= "\n".$clang->gT("SQL CODE THAT FAILED","unescaped").":\n"
  1699.         . "$subquery\n\n"
  1700.         . $clang->gT("ERROR MESSAGE","unescaped").":\n"
  1701.         . $errormsg."\n\n";
  1702.         SendEmailMessage(null,$email, $clang->gT("Error saving results","unescaped"), $thissurvey['adminemail'], $thissurvey['adminemail'], "LimeSurvey", false, getBounceEmail($surveyid));
  1703.         //echo "<!-- EMAIL CONTENTS:\n$email -->\n";
  1704.         //An email has been sent, so we can kill off this session.
  1705.         session_unset();
  1706.         session_destroy();
  1707.     }
  1708.     else
  1709.     {
  1710.         $completed .= "<a href='javascript:location.reload()'>".$clang->gT("Try to submit again")."</a><br /><br />\n";
  1711.         $completed .= $subquery;
  1712.     }
  1713.     return $completed;
  1714. }
  1715.  
  1716. /**
  1717. * This function builds all the required session variables when a survey is first started and
  1718. * it loads any answer defaults from command line or from the table defaultvalues
  1719. * It is called from the related format script (group.php, question.php, survey.php)
  1720. * if the survey has just started.
  1721. *
  1722. * @returns  $totalquestions Total number of questions in the survey
  1723. *
  1724. */
  1725. function buildsurveysession($previewGroup=false)
  1726. {
  1727.     global $thissurvey, $secerror, $clienttoken, $databasetype;
  1728.     global $tokensexist, $thistpl;
  1729.     global $surveyid, $dbprefix, $connect;
  1730.     global $register_errormsg, $clang;
  1731.     global $totalBoilerplatequestions;
  1732.     global $templang, $move, $rooturl, $publicurl;
  1733.  
  1734.     if (!isset($templang) || $templang=='')
  1735.     {
  1736.         $templang=$thissurvey['language'];
  1737.     }
  1738.  
  1739.     $totalBoilerplatequestions = 0;
  1740.     $loadsecurity = returnglobal('loadsecurity');
  1741.     // NO TOKEN REQUIRED BUT CAPTCHA ENABLED FOR SURVEY ACCESS
  1742.     if ($tokensexist == 0 &&
  1743.     captcha_enabled('surveyaccessscreen',$thissurvey['usecaptcha']))
  1744.     {
  1745.  
  1746.         // IF CAPTCHA ANSWER IS NOT CORRECT OR NOT SET
  1747.         if (!isset($loadsecurity) ||
  1748.         !isset($_SESSION['secanswer']) ||
  1749.         $loadsecurity != $_SESSION['secanswer'])
  1750.         {
  1751.             sendcacheheaders();
  1752.             doHeader();
  1753.             // No or bad answer to required security question
  1754.  
  1755.             echo templatereplace(file_get_contents("$thistpl/startpage.pstpl"));
  1756.             //echo makedropdownlist();
  1757.             echo templatereplace(file_get_contents("$thistpl/survey.pstpl"));
  1758.  
  1759.             if (isset($loadsecurity))
  1760.             { // was a bad answer
  1761.                 echo "<font color='#FF0000'>".$clang->gT("The answer to the security question is incorrect.")."</font><br />";
  1762.             }
  1763.  
  1764.             echo "<p class='captcha'>".$clang->gT("Please confirm access to survey by answering the security question below and click continue.")."</p>
  1765.            <form class='captcha' method='get' action='{$publicurl}/index.php'>
  1766.            <table align='center'>
  1767.            <tr>
  1768.            <td align='right' valign='middle'>
  1769.            <input type='hidden' name='sid' value='".$surveyid."' id='sid' />
  1770.            <input type='hidden' name='lang' value='".$templang."' id='lang' />";
  1771.             // In case we this is a direct Reload previous answers URL, then add hidden fields
  1772.             if (isset($_GET['loadall']) && isset($_GET['scid'])
  1773.             && isset($_GET['loadname']) && isset($_GET['loadpass']))
  1774.             {
  1775.                 echo "
  1776.                <input type='hidden' name='loadall' value='".htmlspecialchars($_GET['loadall'])."' id='loadall' />
  1777.                <input type='hidden' name='scid' value='".returnglobal('scid')."' id='scid' />
  1778.                <input type='hidden' name='loadname' value='".htmlspecialchars($_GET['loadname'])."' id='loadname' />
  1779.                <input type='hidden' name='loadpass' value='".htmlspecialchars($_GET['loadpass'])."' id='loadpass' />";
  1780.             }
  1781.  
  1782.             echo "
  1783.            </td>
  1784.            </tr>";
  1785.             if (function_exists("ImageCreate") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha']))
  1786.             {
  1787.                 echo "<tr>
  1788.                <td align='center' valign='middle'><label for='captcha'>".$clang->gT("Security question:")."</label></td><td align='left' valign='middle'><table><tr><td valign='middle'><img src='$rooturl/verification.php?sid=$surveyid' alt='captcha' /></td>
  1789.                <td valign='middle'><input id='captcha' type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table>
  1790.                </td>
  1791.                </tr>";
  1792.             }
  1793.             echo "<tr><td colspan='2' align='center'><input class='submit' type='submit' value='".$clang->gT("Continue")."' /></td></tr>
  1794.            </table>
  1795.            </form>";
  1796.  
  1797.             echo templatereplace(file_get_contents("$thistpl/endpage.pstpl"));
  1798.             doFooter();
  1799.             exit;
  1800.         }
  1801.     }
  1802.  
  1803.     //BEFORE BUILDING A NEW SESSION FOR THIS SURVEY, LET'S CHECK TO MAKE SURE THE SURVEY SHOULD PROCEED!
  1804.  
  1805.     // TOKEN REQUIRED BUT NO TOKEN PROVIDED
  1806.     if ($tokensexist == 1 && !returnglobal('token') && !$previewGroup)
  1807.     {
  1808.         if ($thissurvey['nokeyboard']=='Y')
  1809.         {
  1810.             vIncludeKeypad();
  1811.             $kpclass = "text-keypad";
  1812.         }
  1813.         else
  1814.         {
  1815.             $kpclass = "";
  1816.         }
  1817.  
  1818.         // DISPLAY REGISTER-PAGE if needed
  1819.         // DISPLAY CAPTCHA if needed
  1820.         sendcacheheaders();
  1821.         doHeader();
  1822.  
  1823.         echo templatereplace(file_get_contents("$thistpl/startpage.pstpl"));
  1824.         //echo makedropdownlist();
  1825.         echo templatereplace(file_get_contents("$thistpl/survey.pstpl"));
  1826.         if (isset($thissurvey) && $thissurvey['allowregister'] == "Y")
  1827.         {
  1828.             echo templatereplace(file_get_contents("$thistpl/register.pstpl"));
  1829.         }
  1830.         else
  1831.         {
  1832.             if (isset($secerror)) echo "<span class='error'>".$secerror."</span><br />";
  1833.             echo '<div id="wrapper"><p id="tokenmessage">'.$clang->gT("This is a controlled survey. You need a valid token to participate.")."<br />";
  1834.             echo $clang->gT("If you have been issued a token, please enter it in the box below and click continue.")."</p>
  1835.            <script type='text/javascript'>var focus_element='#token';</script>
  1836.            <form id='tokenform' method='get' action='{$publicurl}/index.php'>
  1837.            <ul>
  1838.            <li>
  1839.            <label for='token'>".$clang->gT("Token")."</label><input class='text $kpclass' id='token' type='text' name='token' />";
  1840.  
  1841.             echo "<input type='hidden' name='sid' value='".$surveyid."' id='sid' />
  1842.            <input type='hidden' name='lang' value='".$templang."' id='lang' />";
  1843.             if (isset($_GET['newtest']) && $_GET['newtest'] == "Y")
  1844.             {
  1845.                 echo "  <input type='hidden' name='newtest' value='Y' id='newtest' />";
  1846.  
  1847.             }
  1848.  
  1849.             // If this is a direct Reload previous answers URL, then add hidden fields
  1850.             if (isset($_GET['loadall']) && isset($_GET['scid'])
  1851.             && isset($_GET['loadname']) && isset($_GET['loadpass']))
  1852.             {
  1853.                 echo "
  1854.                <input type='hidden' name='loadall' value='".htmlspecialchars($_GET['loadall'])."' id='loadall' />
  1855.                <input type='hidden' name='scid' value='".returnglobal('scid')."' id='scid' />
  1856.                <input type='hidden' name='loadname' value='".htmlspecialchars($_GET['loadname'])."' id='loadname' />
  1857.                <input type='hidden' name='loadpass' value='".htmlspecialchars($_GET['loadpass'])."' id='loadpass' />";
  1858.             }
  1859.             echo "</li>";
  1860.  
  1861.             if (function_exists("ImageCreate") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha']))
  1862.             {
  1863.                 echo "<li>
  1864.                <label for='captchaimage'>".$clang->gT("Security Question")."</label><img id='captchaimage' src='$rooturl/verification.php?sid=$surveyid' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />
  1865.                </li>";
  1866.             }
  1867.             echo "<li>
  1868.            <input class='submit' type='submit' value='".$clang->gT("Continue")."' />
  1869.            </li>
  1870.            </ul>
  1871.            </form></div>";
  1872.         }
  1873.  
  1874.         echo templatereplace(file_get_contents("$thistpl/endpage.pstpl"));
  1875.         doFooter();
  1876.         exit;
  1877.     }
  1878.     // TOKENS REQUIRED, A TOKEN PROVIDED
  1879.     // SURVEY WITH NO NEED TO USE CAPTCHA
  1880.     elseif ($tokensexist == 1 && returnglobal('token') &&
  1881.     !captcha_enabled('surveyaccessscreen',$thissurvey['usecaptcha']))
  1882.     {
  1883.         //check if tokens actually haven't been already used
  1884.         $areTokensUsed = usedTokens(db_quote(trim(strip_tags(returnglobal('token')))));
  1885.         //check if token actually does exist
  1886.         // check also if it is allowed to change survey after completion
  1887.         if ($thissurvey['alloweditaftercompletion'] == 'Y' ) {
  1888.             $tkquery = "SELECT COUNT(*) FROM ".db_table_name('tokens_'.$surveyid)." WHERE token='".db_quote(trim(strip_tags(returnglobal('token'))))."' ";
  1889.         } else {
  1890.             $tkquery = "SELECT COUNT(*) FROM ".db_table_name('tokens_'.$surveyid)." WHERE token='".db_quote(trim(strip_tags(returnglobal('token'))))."' AND (completed = 'N' or completed='')";
  1891.         }
  1892.  
  1893.         $tkresult = db_execute_num($tkquery);    //Checked
  1894.         list($tkexist) = $tkresult->FetchRow();
  1895.         if (!$tkexist || ($areTokensUsed && $thissurvey['alloweditaftercompletion'] != 'Y'))
  1896.         {
  1897.             //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
  1898.  
  1899.             killSession();
  1900.             sendcacheheaders();
  1901.             doHeader();
  1902.  
  1903.             echo templatereplace(file_get_contents("$thistpl/startpage.pstpl"));
  1904.             echo templatereplace(file_get_contents("$thistpl/survey.pstpl"));
  1905.             echo '<div id="wrapper"><p id="tokenmessage">'.$clang->gT("This is a controlled survey. You need a valid token to participate.")."<br /><br />\n"
  1906.             ."\t".$clang->gT("The token you have provided is either not valid, or has already been used.")."<br />\n"
  1907.             ."\t".sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname'])
  1908.             ." (<a href='mailto:{$thissurvey['adminemail']}'>"
  1909.             ."{$thissurvey['adminemail']}</a>)</p></div>\n";
  1910.  
  1911.             echo templatereplace(file_get_contents("$thistpl/endpage.pstpl"));
  1912.             doFooter();
  1913.             exit;
  1914.         }
  1915.     }
  1916.     // TOKENS REQUIRED, A TOKEN PROVIDED
  1917.     // SURVEY CAPTCHA REQUIRED
  1918.     elseif ($tokensexist == 1 && returnglobal('token') && captcha_enabled('surveyaccessscreen',$thissurvey['usecaptcha']))
  1919.     {
  1920.  
  1921.         // IF CAPTCHA ANSWER IS CORRECT
  1922.         if (isset($loadsecurity) &&
  1923.         isset($_SESSION['secanswer']) &&
  1924.         $loadsecurity == $_SESSION['secanswer'])
  1925.         {
  1926.             //check if tokens actually haven't been already used
  1927.             $areTokensUsed = usedTokens(db_quote(trim(strip_tags(returnglobal('token')))));
  1928.             //check if token actually does exist
  1929.             if ($thissurvey['alloweditaftercompletion'] == 'Y' )
  1930.             {
  1931.                 $tkquery = "SELECT COUNT(*) FROM ".db_table_name('tokens_'.$surveyid)." WHERE token='".db_quote(trim(sanitize_xss_string(strip_tags(returnglobal('token')))))."'";
  1932.             }
  1933.             else
  1934.             {
  1935.                 $tkquery = "SELECT COUNT(*) FROM ".db_table_name('tokens_'.$surveyid)." WHERE token='".db_quote(trim(sanitize_xss_string(strip_tags(returnglobal('token')))))."' AND (completed = 'N' or completed='')";
  1936.             }
  1937.             $tkresult = db_execute_num($tkquery);     //Checked
  1938.             list($tkexist) = $tkresult->FetchRow();
  1939.             if (!$tkexist || ($areTokensUsed && $thissurvey['alloweditaftercompletion'] != 'Y') )
  1940.             {
  1941.                 sendcacheheaders();
  1942.                 doHeader();
  1943.                 //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
  1944.  
  1945.                 echo templatereplace(file_get_contents("$thistpl/startpage.pstpl"));
  1946.                 echo templatereplace(file_get_contents("$thistpl/survey.pstpl"));
  1947.                 echo "\t<div id='wrapper'>\n"
  1948.                 ."\t<p id='tokenmessage'>\n"
  1949.                 ."\t".$clang->gT("This is a controlled survey. You need a valid token to participate.")."<br /><br />\n"
  1950.                 ."\t".$clang->gT("The token you have provided is either not valid, or has already been used.")."<br/>\n"
  1951.                 ."\t".sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname'])
  1952.                 ." (<a href='mailto:{$thissurvey['adminemail']}'>"
  1953.                 ."{$thissurvey['adminemail']}</a>)\n"
  1954.                 ."\t</p>\n"
  1955.                 ."\t</div>\n";
  1956.  
  1957.                 echo templatereplace(file_get_contents("$thistpl/endpage.pstpl"));
  1958.                 doFooter();
  1959.                 exit;
  1960.             }
  1961.         }
  1962.         // IF CAPTCHA ANSWER IS NOT CORRECT
  1963.         else if (!isset($move) || is_null($move))
  1964.             {
  1965.                 $gettoken = $clienttoken;
  1966.                 sendcacheheaders();
  1967.                 doHeader();
  1968.                 // No or bad answer to required security question
  1969.                 echo templatereplace(file_get_contents("$thistpl/startpage.pstpl"));
  1970.                 echo templatereplace(file_get_contents("$thistpl/survey.pstpl"));
  1971.                 // If token wasn't provided and public registration
  1972.                 // is enabled then show registration form
  1973.                 if ( !isset($gettoken) && isset($thissurvey) && $thissurvey['allowregister'] == "Y")
  1974.                 {
  1975.                     echo templatereplace(file_get_contents("$thistpl/register.pstpl"));
  1976.                 }
  1977.                 else
  1978.                 { // only show CAPTCHA
  1979.  
  1980.                     echo '<div id="wrapper"><p id="tokenmessage">';
  1981.                     if (isset($loadsecurity))
  1982.                     { // was a bad answer
  1983.                         echo "<span class='error'>".$clang->gT("The answer to the security question is incorrect.")."</span><br />";
  1984.                     }
  1985.  
  1986.                     echo $clang->gT("This is a controlled survey. You need a valid token to participate.")."<br /><br />";
  1987.                     // IF TOKEN HAS BEEN GIVEN THEN AUTOFILL IT
  1988.                     // AND HIDE ENTRY FIELD
  1989.                     if (!isset($gettoken))
  1990.                     {
  1991.                         echo $clang->gT("If you have been issued a token, please enter it in the box below and click continue.")."</p>
  1992.                        <form id='tokenform' method='get' action='{$publicurl}/index.php'>
  1993.                        <ul>
  1994.                        <li>
  1995.                        <input type='hidden' name='sid' value='".$surveyid."' id='sid' />
  1996.                        <input type='hidden' name='lang' value='".$templang."' id='lang' />";
  1997.                         if (isset($_GET['loadall']) && isset($_GET['scid'])
  1998.                         && isset($_GET['loadname']) && isset($_GET['loadpass']))
  1999.                         {
  2000.                             echo "<input type='hidden' name='loadall' value='".htmlspecialchars($_GET['loadall'])."' id='loadall' />
  2001.                            <input type='hidden' name='scid' value='".returnglobal('scid')."' id='scid' />
  2002.                            <input type='hidden' name='loadname' value='".htmlspecialchars($_GET['loadname'])."' id='loadname' />
  2003.                            <input type='hidden' name='loadpass' value='".htmlspecialchars($_GET['loadpass'])."' id='loadpass' />";
  2004.                         }
  2005.  
  2006.                         echo '<label for="token">'.$clang->gT("Token")."</label><input class='text' type='text' id='token' name='token'></li>";
  2007.                 }
  2008.                 else
  2009.                 {
  2010.                     echo $clang->gT("Please confirm the token by answering the security question below and click continue.")."</p>
  2011.                    <form id='tokenform' method='get' action='{$publicurl}/index.php'>
  2012.                    <ul>
  2013.                    <li>
  2014.                    <input type='hidden' name='sid' value='".$surveyid."' id='sid' />
  2015.                    <input type='hidden' name='lang' value='".$templang."' id='lang' />";
  2016.                     if (isset($_GET['loadall']) && isset($_GET['scid'])
  2017.                     && isset($_GET['loadname']) && isset($_GET['loadpass']))
  2018.                     {
  2019.                         echo "<input type='hidden' name='loadall' value='".htmlspecialchars($_GET['loadall'])."' id='loadall' />
  2020.                        <input type='hidden' name='scid' value='".returnglobal('scid')."' id='scid' />
  2021.                        <input type='hidden' name='loadname' value='".htmlspecialchars($_GET['loadname'])."' id='loadname' />
  2022.                        <input type='hidden' name='loadpass' value='".htmlspecialchars($_GET['loadpass'])."' id='loadpass' />";
  2023.                     }
  2024.                     echo '<label for="token">'.$clang->gT("Token:")."</label><span id='token'>$gettoken</span>"
  2025.                     ."<input type='hidden' name='token' value='$gettoken'></li>";
  2026.                 }
  2027.  
  2028.  
  2029.                 if (function_exists("ImageCreate") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha']))
  2030.                 {
  2031.                     echo "<li>
  2032.                    <label for='captchaimage'>".$clang->gT("Security Question")."</label><img id='captchaimage' src='$rooturl/verification.php?sid=$surveyid' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />
  2033.                    </li>";
  2034.                 }
  2035.                 echo "<li><input class='submit' type='submit' value='".$clang->gT("Continue")."' /></li>
  2036.                </ul>
  2037.                </form>
  2038.                </id>";
  2039.             }
  2040.  
  2041.             echo '</div>'.templatereplace(file_get_contents("$thistpl/endpage.pstpl"));
  2042.             doFooter();
  2043.             unset($_SESSION['srid']);
  2044.  
  2045.             exit;
  2046.         }
  2047.     }
  2048.  
  2049.     //RESET ALL THE SESSION VARIABLES AND START AGAIN
  2050.     unset($_SESSION['grouplist']);
  2051.     unset($_SESSION['fieldarray']);
  2052.     unset($_SESSION['insertarray']);
  2053.     unset($_SESSION['thistoken']);
  2054.     unset($_SESSION['fieldnamesInfo']);
  2055.     $_SESSION['fieldnamesInfo'] = Array();
  2056.  
  2057.  
  2058.     //RL: multilingual support
  2059.  
  2060.     if (isset($_GET['token']) && db_tables_exist($dbprefix.'tokens_'.$surveyid))
  2061.     {
  2062.         //get language from token (if one exists)
  2063.         $tkquery2 = "SELECT * FROM ".db_table_name('tokens_'.$surveyid)." WHERE token='".db_quote($clienttoken)."' AND (completed = 'N' or completed='')";
  2064.         //echo $tkquery2;
  2065.         $result = db_execute_assoc($tkquery2) or safe_die ("Couldn't get tokens<br />$tkquery<br />".$connect->ErrorMsg());    //Checked
  2066.         while ($rw = $result->FetchRow())
  2067.         {
  2068.             $tklanguage=$rw['language'];
  2069.         }
  2070.     }
  2071.     if (returnglobal('lang'))
  2072.     {
  2073.         $language_to_set=returnglobal('lang');
  2074.     } elseif (isset($tklanguage))
  2075.     {
  2076.         $language_to_set=$tklanguage;
  2077.     }
  2078.     else
  2079.     {
  2080.         $language_to_set = $thissurvey['language'];
  2081.     }
  2082.  
  2083.     if (!isset($_SESSION['s_lang']))
  2084.     {
  2085.         SetSurveyLanguage($surveyid, $language_to_set);
  2086.     }
  2087.  
  2088.  
  2089.     UpdateSessionGroupList($_SESSION['s_lang']);
  2090.  
  2091.  
  2092.  
  2093.     // Optimized Query
  2094.     // Change query to use sub-select to see if conditions exist.
  2095.     $query = "SELECT ".db_table_name('questions').".*, ".db_table_name('groups').".*\n"
  2096.     //    ." (SELECT count(1) FROM ".db_table_name('conditions')."\n"
  2097.     //    ." WHERE ".db_table_name('questions').".qid = ".db_table_name('conditions').".qid) AS hasconditions,\n"
  2098.     //    ." (SELECT count(1) FROM ".db_table_name('conditions')."\n"
  2099.     //    ." WHERE ".db_table_name('questions').".qid = ".db_table_name('conditions').".cqid) AS usedinconditions\n"
  2100.     ." FROM ".db_table_name('groups')." INNER JOIN ".db_table_name('questions')." ON ".db_table_name('groups').".gid = ".db_table_name('questions').".gid\n"
  2101.     ." WHERE ".db_table_name('questions').".sid=".$surveyid."\n"
  2102.     ." AND ".db_table_name('groups').".language='".$_SESSION['s_lang']."'\n"
  2103.     ." AND ".db_table_name('questions').".language='".$_SESSION['s_lang']."'\n"
  2104.     ." AND ".db_table_name('questions').".parent_qid=0\n"
  2105.     ." ORDER BY ".db_table_name('groups').".group_order,".db_table_name('questions').".question_order";
  2106.  
  2107.     //var_dump($_SESSION);
  2108.     $result = db_execute_assoc($query);    //Checked
  2109.  
  2110.     //    $arows = $result->GetRows();  // Not used?
  2111.  
  2112.     $totalquestions = $result->RecordCount();
  2113.  
  2114.     //2. SESSION VARIABLE: totalsteps
  2115.     //The number of "pages" that will be presented in this survey
  2116.     //The number of pages to be presented will differ depending on the survey format
  2117.     switch($thissurvey['format'])
  2118.     {
  2119.         case "A":
  2120.             $_SESSION['totalsteps']=1;
  2121.             break;
  2122.         case "G":
  2123.             if (isset($_SESSION['grouplist']))
  2124.             {
  2125.                 $_SESSION['totalsteps']=count($_SESSION['grouplist']);
  2126.             }
  2127.             break;
  2128.         case "S":
  2129.             $_SESSION['totalsteps']=$totalquestions;
  2130.     }
  2131.  
  2132.     if ($totalquestions == "0") //break out and crash if there are no questions!
  2133.     {
  2134.         sendcacheheaders();
  2135.         doHeader();
  2136.  
  2137.         echo templatereplace(file_get_contents("$thistpl/startpage.pstpl"));
  2138.         echo templatereplace(file_get_contents("$thistpl/survey.pstpl"));
  2139.         echo "\t<div id='wrapper'>\n"
  2140.         ."\t<p id='tokenmessage'>\n"
  2141.         ."\t".$clang->gT("This survey does not yet have any questions and cannot be tested or completed.")."<br /><br />\n"
  2142.         ."\t".sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname'])
  2143.         ." (<a href='mailto:{$thissurvey['adminemail']}'>"
  2144.         ."{$thissurvey['adminemail']}</a>)<br /><br />\n"
  2145.         ."\t</p>\n"
  2146.         ."\t</div>\n";
  2147.  
  2148.         echo templatereplace(file_get_contents("$thistpl/endpage.pstpl"));
  2149.         doFooter();
  2150.         exit;
  2151.     }
  2152.  
  2153.     //Perform a case insensitive natural sort on group name then question title of a multidimensional array
  2154.     //  usort($arows, 'GroupOrderThenQuestionOrder');
  2155.  
  2156.     //3. SESSION VARIABLE - insertarray
  2157.     //An array containing information about used to insert the data into the db at the submit stage
  2158.     //4. SESSION VARIABLE - fieldarray
  2159.     //See rem at end..
  2160.     $_SESSION['token'] = $clienttoken;
  2161.  
  2162.     if ($thissurvey['anonymized'] == "N")
  2163.     {
  2164.         $_SESSION['insertarray'][]= "token";
  2165.     }
  2166.  
  2167.     if ($tokensexist == 1 && $thissurvey['anonymized'] == "N"  && db_tables_exist($dbprefix.'tokens_'.$surveyid))
  2168.     {
  2169.         //Gather survey data for "non anonymous" surveys, for use in presenting questions
  2170.         $_SESSION['thistoken']=getTokenData($surveyid, $clienttoken);
  2171.     }
  2172.     $qtypes=getqtypelist('','array');
  2173.     $fieldmap=createFieldMap($surveyid,'full',false,false,$_SESSION['s_lang']);
  2174.  
  2175.     // Randomization Groups
  2176.  
  2177.     // Find all defined randomization groups through question attribute values
  2178.     $randomGroups=array();
  2179.     if ($databasetype=='odbc_mssql' || $databasetype=='odbtp' || $databasetype=='mssql_n' || $databasetype=='mssqlnative')
  2180.     {
  2181.         $rgquery = "SELECT attr.qid, CAST(value as varchar(255)) FROM ".db_table_name('question_attributes')." as attr right join ".db_table_name('questions')." as quests on attr.qid=quests.qid WHERE attribute='random_group' and CAST(value as varchar(255)) <> '' and sid=$surveyid GROUP BY attr.qid, CAST(value as varchar(255))";
  2182.     }
  2183.     else
  2184.     {
  2185.         $rgquery = "SELECT attr.qid, value FROM ".db_table_name('question_attributes')." as attr right join ".db_table_name('questions')." as quests on attr.qid=quests.qid WHERE attribute='random_group' and value <> '' and sid=$surveyid GROUP BY attr.qid, value";
  2186.     }
  2187.     $rgresult = db_execute_assoc($rgquery);
  2188.     while($rgrow = $rgresult->FetchRow())
  2189.     {
  2190.         // Get the question IDs for each randomization group
  2191.         $randomGroups[$rgrow['value']][] = $rgrow['qid'];
  2192.     }
  2193.  
  2194.     // If we have randomization groups set, then lets cycle through each group and
  2195.     // replace questions in the group with a randomly chosen one from the same group
  2196.     if (count($randomGroups) > 0)
  2197.     {
  2198.         $copyFieldMap = array();
  2199.         $oldQuestOrder = array();
  2200.         $newQuestOrder = array();
  2201.         $randGroupNames = array();
  2202.         foreach ($randomGroups as $key=>$value)
  2203.         {
  2204.             $oldQuestOrder[$key] = $randomGroups[$key];
  2205.             $newQuestOrder[$key] = $oldQuestOrder[$key];
  2206.             // We shuffle the question list to get a random key->qid which will be used to swap from the old key
  2207.             shuffle($newQuestOrder[$key]);
  2208.             $randGroupNames[] = $key;
  2209.         }
  2210.  
  2211.         // Loop through the fieldmap and swap each question as they come up
  2212.         while (list($fieldkey,$fieldval) = each($fieldmap))
  2213.         {
  2214.             $found = 0;
  2215.             foreach ($randomGroups as $gkey=>$gval)
  2216.             {
  2217.                 // We found a qid that is in the randomization group
  2218.                 if (isset($fieldval['qid']) && in_array($fieldval['qid'],$oldQuestOrder[$gkey]))
  2219.                 {
  2220.                     // Get the swapped question
  2221.                     $oldQuestFlip = array_flip($oldQuestOrder[$gkey]);
  2222.                     $qfieldmap = createFieldMap($surveyid,'full',true,$newQuestOrder[$gkey][$oldQuestFlip[$fieldval['qid']]],$_SESSION['s_lang']);
  2223.                     unset($qfieldmap['id']);
  2224.                     unset($qfieldmap['submitdate']);
  2225.                     unset($qfieldmap['lastpage']);
  2226.                     unset($qfieldmap['lastpage']);
  2227.                     unset($qfieldmap['token']);
  2228.                     unset($qfieldmap['startlanguage']);
  2229.                     foreach ($qfieldmap as $tkey=>$tval)
  2230.                     {
  2231.                         // Assign the swapped question (Might be more than one field)
  2232.                         $tval['random_gid'] = $fieldval['gid'];
  2233.                         //$tval['gid'] = $fieldval['gid'];
  2234.                         $copyFieldMap[$tkey]=$tval;
  2235.                     }
  2236.                     $found = 1;
  2237.                     break;
  2238.                 } else
  2239.                 {
  2240.                     $found = 2;
  2241.                 }
  2242.             }
  2243.             if ($found == 2)
  2244.             {
  2245.                 $copyFieldMap[$fieldkey]=$fieldval;
  2246.             }
  2247.             reset($randomGroups);
  2248.         }
  2249.         // reset the sequencing counts
  2250.         $gseq=-1;
  2251.         $_gid=-1;
  2252.         $qseq=-1;
  2253.         $_qid=-1;
  2254.         $copyFieldMap2 = array();
  2255.         foreach ($copyFieldMap as $key=>$val)
  2256.         {
  2257.             if (isset($val['random_gid']))
  2258.             {
  2259.                 if ($val['gid'] != '' && $val['random_gid'] != '' && $val['random_gid'] != $_gid)
  2260.                 {
  2261.                     $_gid = $val['random_gid'];
  2262.                     ++$gseq;
  2263.                 }
  2264.             }
  2265.             else
  2266.             {
  2267.                 if ($val['gid'] != '' && $val['gid'] != $_gid)
  2268.                 {
  2269.                     $_gid = $val['gid'];
  2270.                     ++$gseq;
  2271.                 }
  2272.             }
  2273.  
  2274.             if ($val['qid'] != '' && $val['qid'] != $_qid)
  2275.             {
  2276.                 $_qid = $val['qid'];
  2277.                 ++$qseq;
  2278.             }
  2279.             if ($val['gid'] != '' && $val['qid'] != '')
  2280.             {
  2281.                 $val['groupSeq'] = $gseq;
  2282.                 $val['questionSeq'] = $qseq;
  2283.             }
  2284.             $copyFieldMap2[$key] = $val;
  2285.         }
  2286.         unset($copyFieldMap);
  2287.         $fieldmap=$copyFieldMap2;
  2288.  
  2289.         $_SESSION['fieldmap-' . $surveyid . $_SESSION['s_lang']] = $fieldmap;
  2290.         $_SESSION['fieldmap-' . $surveyid . '-randMaster'] = 'fieldmap-' . $surveyid . $_SESSION['s_lang'];
  2291.     }
  2292.     //die(print_r($fieldmap));
  2293.  
  2294.     foreach ($fieldmap as $field)
  2295.     {
  2296.         if (isset($field['qid']) && $field['qid']!='')
  2297.         {
  2298.             $_SESSION['fieldnamesInfo'][$field['fieldname']]=$field['sid'].'X'.$field['gid'].'X'.$field['qid'];
  2299.             $_SESSION['insertarray'][]=$field['fieldname'];
  2300.             //fieldarray ARRAY CONTENTS -
  2301.             //            [0]=questions.qid,
  2302.             //          [1]=fieldname,
  2303.             //          [2]=questions.title,
  2304.             //          [3]=questions.question
  2305.             //                  [4]=questions.type,
  2306.             //          [5]=questions.gid,
  2307.             //          [6]=questions.mandatory,
  2308.             //          [7]=conditionsexist,
  2309.             //          [8]=usedinconditions
  2310.             //          [8]=usedinconditions
  2311.             //          [9]=used in group.php for question count
  2312.             //          [10]=new group id for question in randomization group (GroupbyGroup Mode)
  2313.             if (!isset($_SESSION['fieldarray'][$field['sid'].'X'.$field['gid'].'X'.$field['qid']]))
  2314.             {
  2315.                 $_SESSION['fieldarray'][$field['sid'].'X'.$field['gid'].'X'.$field['qid']]=array($field['qid'],
  2316.                 $field['sid'].'X'.$field['gid'].'X'.$field['qid'],
  2317.                 $field['title'],
  2318.                 $field['question'],
  2319.                 $field['type'],
  2320.                 $field['gid'],
  2321.                 $field['mandatory'],
  2322.                 $field['hasconditions'],
  2323.                 $field['usedinconditions']);
  2324.             }
  2325.             if (isset($field['random_gid']))
  2326.             {
  2327.                 $_SESSION['fieldarray'][$field['sid'].'X'.$field['gid'].'X'.$field['qid']][10] = $field['random_gid'];
  2328.             }
  2329.         }
  2330.  
  2331.     }
  2332.  
  2333.     // Defaults need to be set within Expression Manager so that it can process defaults comprised of equations
  2334.     //    // Prefill question/answer from defaultvalues
  2335.     //    foreach ($fieldmap as $field)
  2336.     //    {
  2337.     //        if (isset($field['defaultvalue']))
  2338.     //        {
  2339.     //            $_SESSION[$field['fieldname']]=$field['defaultvalue'];
  2340.     //        }
  2341.     //    }
  2342.     // Prefill questions/answers from command line params
  2343.     $startingValues=array();
  2344.     if (isset($_GET))
  2345.     {
  2346.         foreach ($_GET as $k=>$v)
  2347.         {
  2348.             if (preg_match('/^(token|sid|lang|newtest)$/',$k))
  2349.             {
  2350.                 continue;
  2351.             }
  2352.             $startingValues[$k] = $v;
  2353.         }
  2354.     }
  2355.     $_SESSION['startingValues']=$startingValues;
  2356.  
  2357.     if (isset($_SESSION['fieldarray'])) $_SESSION['fieldarray']=array_values($_SESSION['fieldarray']);
  2358.  
  2359.     // Check if the current survey language is set - if not set it
  2360.     // this way it can be changed later (for example by a special question type)
  2361.     //Check if a passthru label and value have been included in the query url
  2362.     if(isset($_GET['passthru']) && $_GET['passthru'] != "")
  2363.     {
  2364.         if(isset($_GET[$_GET['passthru']]) && $_GET[$_GET['passthru']] != "")
  2365.         {
  2366.             $_SESSION['passthrulabel']=$_GET['passthru'];
  2367.             $_SESSION['passthruvalue']=$_GET[$_GET['passthru']];
  2368.         }
  2369.  
  2370.     }
  2371.     // New: If no passthru variable is explicitely set, save the whole query_string - above method is obsolete and the new way should only be used
  2372.     elseif (isset($_SERVER['QUERY_STRING']))
  2373.     {
  2374.         $_SESSION['ls_initialquerystr']=$_SERVER['QUERY_STRING'];
  2375.     }
  2376.     // END NEW
  2377.  
  2378.     // Fix totalquestions by substracting Test Display questions
  2379.     $sNoOfTextDisplayQuestions=(int) $connect->GetOne("SELECT count(*)\n"
  2380.     ." FROM ".db_table_name('questions')
  2381.     ." WHERE type in ('X','*')\n"
  2382.     ." AND sid={$surveyid}"
  2383.     ." AND language='".$_SESSION['s_lang']."'"
  2384.     ." AND parent_qid=0");
  2385.  
  2386.     $_SESSION['therearexquestions'] = $totalquestions - $sNoOfTextDisplayQuestions; // must be global for THEREAREXQUESTIONS replacement field to work
  2387.  
  2388.     return $totalquestions-$sNoOfTextDisplayQuestions;
  2389. }
  2390.  
  2391. function surveymover()
  2392. {
  2393.     //This function creates the form elements in the survey navigation bar
  2394.     //with "<<PREV" or ">>NEXT" in them. The "submit" value determines how the script moves from
  2395.     //one survey page to another. It is a hidden element, updated by clicking
  2396.     //on the  relevant button - allowing "NEXT" to be the default setting when
  2397.     //a user presses enter.
  2398.     //
  2399.     //Attribute accesskey added for keyboard navigation.
  2400.     global $thissurvey, $clang;
  2401.     global $surveyid, $presentinggroupdescription;
  2402.     $surveymover = "";
  2403.  
  2404.     if ($thissurvey['navigationdelay'] > 0 && (
  2405.     isset($_SESSION['maxstep']) && $_SESSION['maxstep'] > 0 && $_SESSION['maxstep'] == $_SESSION['step']))
  2406.     {
  2407.         $disabled = "disabled=\"disabled\"";
  2408.         $surveymover .= "<script type=\"text/javascript\">\n"
  2409.         . "  navigator_countdown(" . $thissurvey['navigationdelay'] . ");\n"
  2410.         . "</script>\n";
  2411.     }
  2412.     else
  2413.     {
  2414.         $disabled = "";
  2415.     }
  2416.  
  2417.     if (isset($_SESSION['step']) && $_SESSION['step'] && ($_SESSION['step'] == $_SESSION['totalsteps']) && !$presentinggroupdescription && $thissurvey['format'] != "A")
  2418.     {
  2419.         $surveymover .= "<input type=\"hidden\" name=\"move\" value=\"movesubmit\" id=\"movesubmit\" />";
  2420.     }
  2421.     else
  2422.     {
  2423.         $surveymover .= "<input type=\"hidden\" name=\"move\" value=\"movenext\" id=\"movenext\" />";
  2424.     }
  2425.  
  2426.     if (isset($_SESSION['step']) && $thissurvey['format'] != "A" && ($thissurvey['allowprev'] != "N" || $thissurvey['allowjumps'] == "Y") &&
  2427.     ($_SESSION['step'] > 0 || (!$_SESSION['step'] && $presentinggroupdescription && $thissurvey['showwelcome'] == 'Y')))
  2428.     {
  2429.         //To prevent too much complication in the if statement above I put it here...
  2430.         if ($thissurvey['showwelcome'] == 'N' && $_SESSION['step'] == 1) {
  2431.             //first step and we do not want to go back to the welcome screen since we don't show that...
  2432.             //so skip the prev button
  2433.         } else {
  2434.             $surveymover .= "<input class='submit' accesskey='p' type='button' onclick=\"javascript:document.limesurvey.move.value = 'moveprev'; $('#limesurvey').submit();\" value=' &lt;&lt; "
  2435.             . $clang->gT("Previous")." ' name='move2' id='moveprevbtn' $disabled />\n";
  2436.         }
  2437.     }
  2438.     if (isset($_SESSION['step']) && $_SESSION['step'] && (!$_SESSION['totalsteps'] || ($_SESSION['step'] < $_SESSION['totalsteps'])))
  2439.     {
  2440.         $surveymover .=  "\t<input class='submit' type='submit' accesskey='n' onclick=\"javascript:document.limesurvey.move.value = 'movenext';\" value=' "
  2441.         . $clang->gT("Next")." &gt;&gt; ' name='move2' id='movenextbtn' $disabled />\n";
  2442.     }
  2443.     // here, in some lace, is where I must modify to turn the next button conditionable
  2444.     if (!isset($_SESSION['step']) || !$_SESSION['step'])
  2445.     {
  2446.         $surveymover .=  "\t<input class='submit' type='submit' accesskey='n' onclick=\"javascript:document.limesurvey.move.value = 'movenext';\" value=' "
  2447.         . $clang->gT("Next")." &gt;&gt; ' name='move2' id='movenextbtn' $disabled />\n";
  2448.     }
  2449.     if (isset($_SESSION['step']) && $_SESSION['step'] && ($_SESSION['step'] == $_SESSION['totalsteps']) && $presentinggroupdescription == "yes")
  2450.     {
  2451.         $surveymover .=  "\t<input class='submit' type='submit' onclick=\"javascript:document.limesurvey.move.value = 'movenext';\" value=' "
  2452.         . $clang->gT("Next")." &gt;&gt; ' name='move2' id=\"movenextbtn\" $disabled />\n";
  2453.     }
  2454.     if (($_SESSION['step'] && ($_SESSION['step'] == $_SESSION['totalsteps']) && !$presentinggroupdescription) || $thissurvey['format'] == 'A')
  2455.     {
  2456.         $surveymover .= "\t<input class=\"submit\" type=\"submit\" accesskey=\"l\" onclick=\"javascript:document.limesurvey.move.value = 'movesubmit';\" value=\""
  2457.         . $clang->gT("Submit")."\" name=\"move2\" id=\"movesubmitbtn\" $disabled />\n";
  2458.     }
  2459.  
  2460.     //  $surveymover .= "<input type='hidden' name='PHPSESSID' value='".session_id()."' id='PHPSESSID' />\n";
  2461.     return $surveymover;
  2462. }
  2463.  
  2464.  
  2465. /**
  2466. * Caculate assessement scores
  2467. *
  2468. * @param mixed $surveyid
  2469. * @param mixed $returndataonly - only returns an array with data
  2470. */
  2471. function doAssessment($surveyid, $returndataonly=false)
  2472. {
  2473.     global $dbprefix, $thistpl, $connect;
  2474.     $baselang=GetBaseLanguageFromSurveyID($surveyid);
  2475.     $total=0;
  2476.     if (!isset($_SESSION['s_lang']))
  2477.     {
  2478.         $_SESSION['s_lang']=$baselang;
  2479.     }
  2480.     $query = "SELECT * FROM ".db_table_name('assessments')."
  2481.    WHERE sid=$surveyid and language='{$_SESSION['s_lang']}'
  2482.    ORDER BY scope,id";
  2483.     if ($result = db_execute_assoc($query))   //Checked
  2484.     {
  2485.         if ($result->RecordCount() > 0)
  2486.         {
  2487.             while ($row=$result->FetchRow())
  2488.             {
  2489.                 if ($row['scope'] == "G")
  2490.                 {
  2491.                     $assessment['group'][$row['gid']][]=array("name"=>$row['name'],
  2492.                     "min"=>$row['minimum'],
  2493.                     "max"=>$row['maximum'],
  2494.                     "message"=>$row['message']);
  2495.                 }
  2496.                 else
  2497.                 {
  2498.                     $assessment['total'][]=array( "name"=>$row['name'],
  2499.                     "min"=>$row['minimum'],
  2500.                     "max"=>$row['maximum'],
  2501.                     "message"=>$row['message']);
  2502.                 }
  2503.             }
  2504.             $fieldmap=createFieldMap($surveyid, "full");
  2505.             $i=0;
  2506.             $total=0;
  2507.             $groups=array();
  2508.             foreach($fieldmap as $field)
  2509.             {
  2510.                 if (in_array($field['type'],array('1','F','H','W','Z','L','!','M','O','P')))
  2511.                 {
  2512.                     $fieldmap[$field['fieldname']]['assessment_value']=0;
  2513.                     if (isset($_SESSION[$field['fieldname']]))
  2514.                     {
  2515.                         if (($field['type'] == "M") || ($field['type'] == "P")) //Multiflexi choice  - result is the assessment attribute value
  2516.                         {
  2517.                             if ($_SESSION[$field['fieldname']] == "Y")
  2518.                             {
  2519.                                 $aAttributes=getQuestionAttributes($field['qid'],$field['type']);
  2520.                                 $fieldmap[$field['fieldname']]['assessment_value']=(int)$aAttributes['assessment_value'];
  2521.                                 $total=$total+(int)$aAttributes['assessment_value'];
  2522.                             }
  2523.                         }
  2524.                         else
  2525.                         {
  2526.                             $usquery = "SELECT assessment_value FROM ".db_table_name("answers")." where qid=".$field['qid']." and language='$baselang' and code=".db_quoteall($_SESSION[$field['fieldname']]);
  2527.                             $usresult = db_execute_assoc($usquery);          //Checked
  2528.                             if ($usresult)
  2529.                             {
  2530.                                 $usrow = $usresult->FetchRow();
  2531.                                 $fieldmap[$field['fieldname']]['assessment_value']=$usrow['assessment_value'];
  2532.                                 $total=$total+$usrow['assessment_value'];
  2533.                             }
  2534.                         }
  2535.                     }
  2536.                     $groups[]=$field['gid'];
  2537.                 }
  2538.                 $i++;
  2539.             }
  2540.  
  2541.             $groups=array_unique($groups);
  2542.  
  2543.             foreach($groups as $group)
  2544.             {
  2545.                 $grouptotal=0;
  2546.                 foreach ($fieldmap as $field)
  2547.                 {
  2548.                     if ($field['gid'] == $group && isset($field['assessment_value']))
  2549.                     {
  2550.                         //$grouptotal=$grouptotal+$field['answer'];
  2551.                         if (isset ($_SESSION[$field['fieldname']]))
  2552.                         {
  2553.                             $grouptotal=$grouptotal+$field['assessment_value'];
  2554.                         }
  2555.                     }
  2556.                 }
  2557.                 $subtotal[$group]=$grouptotal;
  2558.             }
  2559.         }
  2560.         $assessments = "";
  2561.         if (isset($subtotal) && is_array($subtotal))
  2562.         {
  2563.             foreach($subtotal as $key=>$val)
  2564.             {
  2565.                 if (isset($assessment['group'][$key]))
  2566.                 {
  2567.                     foreach($assessment['group'][$key] as $assessed)
  2568.                     {
  2569.                         if ($val >= $assessed['min'] && $val <= $assessed['max'] && $returndataonly===false)
  2570.                         {
  2571.                             $assessments .= "\t<!-- GROUP ASSESSMENT: Score: $val Min: ".$assessed['min']." Max: ".$assessed['max']."-->
  2572.                            <table class='assessments' align='center'>
  2573.                            <tr>
  2574.                            <th>".str_replace(array("{PERC}", "{TOTAL}"), array($val, $total), $assessed['name'])."
  2575.                            </th>
  2576.                            </tr>
  2577.                            <tr>
  2578.                            <td align='center'>".str_replace(array("{PERC}", "{TOTAL}"), array($val, $total), $assessed['message'])."
  2579.                            </td>
  2580.                            </tr>
  2581.                            </table><br />\n";
  2582.                         }
  2583.                     }
  2584.                 }
  2585.             }
  2586.         }
  2587.  
  2588.         if (isset($assessment['total']))
  2589.         {
  2590.             foreach($assessment['total'] as $assessed)
  2591.             {
  2592.                 if ($total >= $assessed['min'] && $total <= $assessed['max'] && $returndataonly===false)
  2593.                 {
  2594.                     $assessments .= "\t\t\t<!-- TOTAL ASSESSMENT: Score: $total Min: ".$assessed['min']." Max: ".$assessed['max']."-->
  2595.                    <table class='assessments' align='center'><tr><th>".str_replace(array("{PERC}", "{TOTAL}"), array($val, $total), stripslashes($assessed['name']))."
  2596.                    </th></tr>
  2597.                    <tr>
  2598.                    <td align='center'>".str_replace(array("{PERC}", "{TOTAL}"), array($val, $total), stripslashes($assessed['message']))."
  2599.                    </td>
  2600.                    </tr>
  2601.                    </table>\n";
  2602.                 }
  2603.             }
  2604.         }
  2605.         if ($returndataonly==true)
  2606.         {
  2607.             return array('total'=>$total);
  2608.         }
  2609.         else
  2610.         {
  2611.             return $assessments;
  2612.         }
  2613.     }
  2614. }
  2615.  
  2616. function UpdateSessionGroupList($language)
  2617. //1. SESSION VARIABLE: grouplist
  2618. //A list of groups in this survey, ordered by group name.
  2619.  
  2620. {
  2621.     global $surveyid;
  2622.     unset ($_SESSION['grouplist']);
  2623.     $query = "SELECT * FROM ".db_table_name('groups')." WHERE sid=$surveyid AND language='".$language."' ORDER BY group_order";
  2624.     $result = db_execute_assoc($query) or safe_die ("Couldn't get group list<br />$query<br />".$connect->ErrorMsg());  //Checked
  2625.     while ($row = $result->FetchRow())
  2626.     {
  2627.         $_SESSION['grouplist'][]=array($row['gid'], $row['group_name'], $row['description']);
  2628.     }
  2629. }
  2630.  
  2631. function UpdateFieldArray()
  2632. //The FieldArray contains all necessary information regarding the questions
  2633. //This function is needed to update it in case the survey is switched to another language
  2634.  
  2635. {
  2636.     global $surveyid;
  2637.  
  2638.     if (isset($_SESSION['fieldarray']))
  2639.     {
  2640.         reset($_SESSION['fieldarray']);
  2641.         while ( list($key) = each($_SESSION['fieldarray']) )
  2642.         {
  2643.             $questionarray =& $_SESSION['fieldarray'][$key];
  2644.  
  2645.             $query = "SELECT * FROM ".db_table_name('questions')." WHERE qid=".$questionarray[0]." AND language='".$_SESSION['s_lang']."'";
  2646.             $result = db_execute_assoc($query) or safe_die ("Couldn't get question <br />$query<br />".$connect->ErrorMsg());      //Checked
  2647.             $row = $result->FetchRow();
  2648.             $questionarray[2]=$row['title'];
  2649.             $questionarray[3]=$row['question'];
  2650.             unset($questionarray);
  2651.         }
  2652.     }
  2653.  
  2654. }
  2655.  
  2656.  
  2657. /**
  2658. * check_quota() returns quota information for the current survey
  2659. * @param string $checkaction - action the function must take after completing:
  2660. *                               enforce: Enforce the Quota action
  2661. *                               return: Return the updated quota array from getQuotaAnswers()
  2662. * @param string $surveyid - Survey identification number
  2663. * @return array - nested array, Quotas->Members->Fields, includes quota status and which members matched in session.
  2664. */
  2665. function check_quota($checkaction,$surveyid)
  2666. {
  2667.     if (!isset($_SESSION['s_lang'])){
  2668.         return;
  2669.     }
  2670.     global $thistpl, $clang, $clienttoken, $publicurl;
  2671.     $global_matched = false;
  2672.     $quota_info = getQuotaInformation($surveyid, $_SESSION['s_lang']);
  2673.     $x=0;
  2674.  
  2675.     if(count($quota_info) > 0) // Quota's have to exist
  2676.     {
  2677.         // Check each quota on saved data to see if it is full
  2678.         $querycond = array();
  2679.         foreach ($quota_info as $quota)
  2680.         {
  2681.             if (count($quota['members']) > 0) // Quota can't be empty
  2682.             {
  2683.                 $fields_list = array(); // Keep a list of fields for easy reference
  2684.                 $y=0;
  2685.                 // We need to make the conditions for the select statement here
  2686.                 unset($querycond);
  2687.                 // fill the array of value and query for each fieldnames
  2688.                 $fields_value_array = array();
  2689.                 $fields_query_array = array();
  2690.                 foreach($quota['members'] as $member)
  2691.                 {
  2692.                     foreach($member['fieldnames'] as $fieldname)
  2693.                     {
  2694.  
  2695.                         if (!in_array($fieldname,$fields_list))
  2696.                         {
  2697.                             $fields_list[] = $fieldname;
  2698.                             $fields_value_array[$fieldname] = array();
  2699.                             $fields_query_array[$fieldname] = array();
  2700.                         }
  2701.                         $fields_value_array[$fieldname][]=$member['value'];
  2702.                         $fields_query_array[$fieldname][]= db_quote_id($fieldname)." = '{$member['value']}'";
  2703.                     }
  2704.  
  2705.                 }
  2706.                 // fill the $querycond array with each fields_query grouped by fieldname
  2707.                 foreach($fields_list as $fieldname)
  2708.                 {
  2709.                     $select_query = " ( ".implode(' OR ',$fields_query_array[$fieldname]).' )';
  2710.                     $querycond[] = $select_query;
  2711.                 }
  2712.                 // Test if the fieldname is in the array of value in the session
  2713.                 foreach($quota['members'] as $member)
  2714.                 {
  2715.                     foreach($member['fieldnames'] as $fieldname)
  2716.                     {
  2717.                         if (isset($_SESSION[$fieldname]))
  2718.                         {
  2719.                             if (in_array($_SESSION[$fieldname],$fields_value_array[$fieldname])){
  2720.                                 $quota_info[$x]['members'][$y]['insession'] = "true";
  2721.                             }
  2722.                         }
  2723.                     }
  2724.                     $y++;
  2725.                 }
  2726.                 unset($fields_query_array);unset($fields_value_array);
  2727.  
  2728.                 // Lets only continue if any of the quota fields is in the posted page
  2729.                 $matched_fields = false;
  2730.                 if (isset($_POST['fieldnames']))
  2731.                 {
  2732.                     $posted_fields = explode("|",$_POST['fieldnames']);
  2733.                     foreach ($fields_list as $checkfield)
  2734.                     {
  2735.                         if (in_array($checkfield,$posted_fields))
  2736.                         {
  2737.                             $matched_fields = true;
  2738.                             $global_matched = true;
  2739.                         }
  2740.                     }
  2741.                 }
  2742.  
  2743.                 // A field was submitted that is part of the quota
  2744.  
  2745.                 if ($matched_fields == true)
  2746.                 {
  2747.  
  2748.                     // Check the status of the quota, is it full or not
  2749.                     $querysel = "SELECT id FROM ".db_table_name('survey_'.$surveyid)."
  2750.                    WHERE ".implode(' AND ',$querycond)." "."
  2751.                    AND submitdate IS NOT NULL";
  2752.  
  2753.                     $result = db_execute_assoc($querysel) or safe_die($connect->ErrorMsg());    //Checked
  2754.                     $quota_check = $result->FetchRow();
  2755.  
  2756.                     if ($result->RecordCount() >= $quota['Limit']) // Quota is full!!
  2757.  
  2758.                     {
  2759.                         // Now we have to check if the quota matches in the current session
  2760.                         // This will let us know if this person is going to exceed the quota
  2761.  
  2762.                         $counted_matches = 0;
  2763.                         foreach($quota_info[$x]['members'] as $member)
  2764.                         {
  2765.                             if (isset($member['insession']) && $member['insession'] == "true") $counted_matches++;
  2766.                         }
  2767.                         if($counted_matches == count($quota['members']))
  2768.                         {
  2769.                             // They are going to exceed the quota if data is submitted
  2770.                             $quota_info[$x]['status']="matched";
  2771.  
  2772.                         } else
  2773.                         {
  2774.                             $quota_info[$x]['status']="notmatched";
  2775.                         }
  2776.  
  2777.                     } else
  2778.                     {
  2779.                         // Quota is no in danger of being exceeded.
  2780.                         $quota_info[$x]['status']="notmatched";
  2781.                     }
  2782.                 }
  2783.  
  2784.             }
  2785.             $x++;
  2786.         }
  2787.  
  2788.     } else
  2789.     {
  2790.         return false;
  2791.     }
  2792.  
  2793.     // Now we have all the information we need about the quotas and their status.
  2794.     // Lets see what we should do now
  2795.     if ($checkaction == 'return')
  2796.     {
  2797.         return $quota_info;
  2798.     } else if ($global_matched == true && $checkaction == 'enforce')
  2799.         {
  2800.             // Need to add Quota action enforcement here.
  2801.             reset($quota_info);
  2802.  
  2803.             $tempmsg ="";
  2804.             $found = false;
  2805.             foreach($quota_info as $quota)
  2806.             {
  2807.                 if ((isset($quota['status']) && $quota['status'] == "matched") && (isset($quota['Action']) && $quota['Action'] == "1"))
  2808.                 {
  2809.                     // If a token is used then mark the token as completed
  2810.                     if (isset($clienttoken) && $clienttoken)
  2811.                     {
  2812.                         submittokens(true);
  2813.                     }
  2814.                     session_destroy();
  2815.                 sendcacheheaders();
  2816.                 if($quota['AutoloadUrl'] == 1 && $quota['Url'] != "")
  2817.                 {
  2818.                     header("Location: ".$quota['Url']);
  2819.                 }
  2820.                 doHeader();
  2821.                 echo templatereplace(file_get_contents("$thistpl/startpage.pstpl"));
  2822.                 echo "\t<div class='quotamessage'>\n";
  2823.                 echo "\t".$quota['Message']."<br /><br />\n";
  2824.                 echo "\t<a href='".$quota['Url']."'>".$quota['UrlDescrip']."</a><br />\n";
  2825.                 echo "\t</div>\n";
  2826.                 echo templatereplace(file_get_contents("$thistpl/endpage.pstpl"));
  2827.                 doFooter();
  2828.                 exit;
  2829.             }
  2830.  
  2831.             if ((isset($quota['status']) && $quota['status'] == "matched") && (isset($quota['Action']) && $quota['Action'] == "2"))
  2832.             {
  2833.  
  2834.                 sendcacheheaders();
  2835.                 doHeader();
  2836.                 echo templatereplace(file_get_contents("$thistpl/startpage.pstpl"));
  2837.                 echo "\t<div class='quotamessage'>\n";
  2838.                 echo "\t".$quota['Message']."<br /><br />\n";
  2839.                 echo "\t<a href='".$quota['Url']."'>".$quota['UrlDescrip']."</a><br />\n";
  2840.                 echo "<form method='post' action='{$publicurl}/index.php' id='limesurvey' name='limesurvey'><input type=\"hidden\" name=\"move\" value=\"movenext\" id=\"movenext\" /><input class='submit' accesskey='p' type='button' onclick=\"javascript:document.limesurvey.move.value = 'moveprev'; document.limesurvey.submit();\" value=' &lt;&lt; ". $clang->gT("Previous")." ' name='move2' />
  2841.                <input type='hidden' name='thisstep' value='".($_SESSION['step'])."' id='thisstep' />
  2842.                <input type='hidden' name='sid' value='".returnglobal('sid')."' id='sid' />
  2843.                <input type='hidden' name='token' value='".$clienttoken."' id='token' />
  2844.                </form>\n";
  2845.                 echo "\t</div>\n";
  2846.                 echo templatereplace(file_get_contents("$thistpl/endpage.pstpl"));
  2847.                 doFooter();
  2848.                 exit;
  2849.             }
  2850.         }
  2851.  
  2852.  
  2853.     } else
  2854.     {
  2855.         // Unknown value
  2856.         return false;
  2857.     }
  2858.  
  2859. }
  2860.  
  2861. /**
  2862. * put your comment there...
  2863. *
  2864. * @param mixed $mail
  2865. * @param mixed $text
  2866. * @param mixed $class
  2867. * @param mixed $params
  2868. */
  2869. function encodeEmail($mail, $text="", $class="", $params=array())
  2870. {
  2871.     $encmail ="";
  2872.     for($i=0; $i<strlen($mail); $i++)
  2873.     {
  2874.         $encMod = rand(0,2);
  2875.         switch ($encMod)
  2876.         {
  2877.             case 0: // None
  2878.                 $encmail .= substr($mail,$i,1);
  2879.                 break;
  2880.             case 1: // Decimal
  2881.                 $encmail .= "&#".ord(substr($mail,$i,1)).';';
  2882.                 break;
  2883.             case 2: // Hexadecimal
  2884.                 $encmail .= "&#x".dechex(ord(substr($mail,$i,1))).';';
  2885.                 break;
  2886.         }
  2887.     }
  2888.  
  2889.     if(!$text)
  2890.     {
  2891.         $text = $encmail;
  2892.     }
  2893.     return $text;
  2894. }
  2895.  
  2896.  
  2897.  
  2898. /**
  2899. * GetReferringUrl() returns the reffering URL
  2900. */
  2901. function GetReferringUrl()
  2902. {
  2903.     global $clang,$stripQueryFromRefurl;
  2904.     if (isset($_SESSION['refurl']))
  2905.     {
  2906.         return; // do not overwrite refurl
  2907.     }
  2908.  
  2909.     // refurl is not set in session, read it from server variable
  2910.     if(isset($_SERVER["HTTP_REFERER"]))
  2911.     {
  2912.         if(!preg_match('/'.$_SERVER["SERVER_NAME"].'/', $_SERVER["HTTP_REFERER"]))
  2913.         {
  2914.             if (!isset($stripQueryFromRefurl) || !$stripQueryFromRefurl)
  2915.             {
  2916.                 $_SESSION['refurl'] = $_SERVER["HTTP_REFERER"];
  2917.             }
  2918.             else
  2919.             {
  2920.                 $aRefurl = explode("?",$_SERVER["HTTP_REFERER"]);
  2921.                 $_SESSION['refurl'] = $aRefurl[0];
  2922.             }
  2923.         }
  2924.         else
  2925.         {
  2926.             $_SESSION['refurl'] = '-';
  2927.         }
  2928.     }
  2929.     else
  2930.     {
  2931.         $_SESSION['refurl'] = null;
  2932.     }
  2933. }
  2934.  
  2935. /**
  2936. * Shows the welcome page, used in group by group and question by question mode
  2937. */
  2938. function display_first_page() {
  2939.     global $clang, $thistpl, $token, $surveyid, $thissurvey, $navigator,$publicurl;
  2940.     sendcacheheaders();
  2941.     doHeader();
  2942.  
  2943.     LimeExpressionManager::StartProcessingPage();
  2944.     LimeExpressionManager::StartProcessingGroup(-1, false, $surveyid);  // start on welcome page
  2945.  
  2946.     echo templatereplace(file_get_contents("$thistpl/startpage.pstpl"));
  2947.     echo "\n<form method='post' action='{$publicurl}/index.php' id='limesurvey' name='limesurvey' autocomplete='off'>\n";
  2948.  
  2949.     echo "\n\n<!-- START THE SURVEY -->\n";
  2950.  
  2951.     echo templatereplace(file_get_contents("$thistpl/welcome.pstpl"))."\n";
  2952.     if ($thissurvey['anonymized'] == "Y")
  2953.     {
  2954.         echo templatereplace(file_get_contents("$thistpl/privacy.pstpl"))."\n";
  2955.     }
  2956.     $navigator = surveymover();
  2957.     echo templatereplace(file_get_contents("$thistpl/navigator.pstpl"));
  2958.     if ($thissurvey['active'] != "Y")
  2959.     {
  2960.         echo "<p style='text-align:center' class='error'>".$clang->gT("This survey is currently not active. You will not be able to save your responses.")."</p>\n";
  2961.     }
  2962.     echo "\n<input type='hidden' name='sid' value='$surveyid' id='sid' />\n";
  2963.     if (isset($token) && !empty($token)) {
  2964.         echo "\n<input type='hidden' name='token' value='$token' id='token' />\n";
  2965.     }
  2966.     echo "\n<input type='hidden' name='lastgroupname' value='_WELCOME_SCREEN_' id='lastgroupname' />\n"; //This is to ensure consistency with mandatory checks, and new group test
  2967.     $loadsecurity = returnglobal('loadsecurity');
  2968.     if (isset($loadsecurity)) {
  2969.         echo "\n<input type='hidden' name='loadsecurity' value='$loadsecurity' id='loadsecurity' />\n";
  2970.     }
  2971.     $_SESSION['LEMpostKey'] = mt_rand();
  2972.     echo "<input type='hidden' name='LEMpostKey' value='{$_SESSION['LEMpostKey']}' id='LEMpostKey' />\n";
  2973.     echo "<input type='hidden' name='thisstep' id='thisstep' value='0' />\n";
  2974.  
  2975.     echo "\n</form>\n";
  2976.     echo templatereplace(file_get_contents("$thistpl/endpage.pstpl"));
  2977.  
  2978.     echo LimeExpressionManager::GetRelevanceAndTailoringJavaScript();
  2979.     LimeExpressionManager::FinishProcessingPage();
  2980.     doFooter();
  2981. }
  2982. // Closing PHP tag intentionally left out - yes, it is okay
  2983. ?>
  2984.  
  2985.  
  2986.  
  2987.  </div>
  2988.                
  2989.             </div>
  2990.            
  2991.             <div class="advertisers"><?php include('../template/right-column.php'); ?></div>
  2992.            
  2993.         </div>
  2994.        
  2995.         <!--<div class="footer"><?php include('template/footer.php'); ?></div>-->
  2996.        
  2997.     </div>
  2998.    
  2999. </body>
  3000. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement