'; } if (!function_exists('mb_convert_encoding')) { $dieoutput .= "This script needs the PHP Multibyte String Functions library installed: See FAQ and PHP documentation
"; } if ($dieoutput!='') die($dieoutput); if (!isset($debug)) {$debug=0;} // for some older config.php's if ($debug>0) {//For debug purposes - switch on in config.php @ini_set("display_errors", 1); error_reporting(E_ALL); } if ($debug>2) {//For debug purposes - switch on in config.php error_reporting(E_ALL | E_STRICT); } if (ini_get("max_execution_time")<600) @set_time_limit(600); // Maximum execution time - works only if safe_mode is off @ini_set("memory_limit",$memorylimit); // Set Memory Limit for big surveys $maildebug=''; // The following function (when called) includes FireBug Lite if true define('FIREBUG' , $use_firebug_lite); define('ADODB_ASSOC_CASE', 2); // needed to set proper upper/lower casing for mssql ################################################################################## require_once ($rootdir.'/classes/adodb/adodb.inc.php'); require_once ($rootdir.'/classes/datetimeconverter/class.datetimeconverter.php'); require_once ($rootdir.'/classes/phpmailer/class.phpmailer.php'); require_once ($rootdir.'/classes/php-gettext/gettext.inc'); require_once ($rootdir.'/classes/core/surveytranslator.php'); require_once ($rootdir.'/classes/core/sanitize.php'); $dbprefix=strtolower($dbprefix); define("_PHPVERSION", phpversion()); // This is the same as the server defined 'PHP_VERSION' //Deal with Xitami server issues //Todo: find out if this still is an issue with the latest Xitami server version if(isset($_SERVER['SERVER_SOFTWARE']) && $_SERVER['SERVER_SOFTWARE'] == "Xitami") { $_SERVER['PHP_SELF'] = substr($_SERVER['SERVER_URL'], 0, -1) .$_SERVER['SCRIPT_NAME']; } // Deal with server systems having not set a default time zone if(function_exists("date_default_timezone_set") and function_exists("date_default_timezone_get")) @date_default_timezone_set(@date_default_timezone_get()); //Every 50th time clean up the temp directory of old files (older than 1 day) //depending on the load the probability might be set higher or lower if (rand(1,50)==25) { cleanTempDirectory(); } // Array of JS and CSS scripts to include in client header $js_header_includes = array(); $css_header_includes = array(); // JS scripts and CSS to include in admin header // updated by admin scripts $js_adminheader_includes = array(); $css_adminheader_includes = array(); /* * $sourcefrom variable checks the location of the current script against * the administration directory, and if the current script is running * in the administration directory, it is set to "admin". Otherwise it is set * to "public". When $sourcefrom is "admin" certain administration only functions * are loaded. */ $scriptlocation=realpath("."); $slashlesspath=str_replace(array("\\", "/"), "", $scriptlocation); $slashlesshome=str_replace(array("\\", "/"), "", $homedir); // Uncomment the following line for debug purposes // echo $slashlesspath." - ".$slashlesshome; if (strcasecmp($slashlesshome, $slashlesspath) == 0) { if (strcasecmp($slashlesshome."install", $slashlesspath) != 0) { $sourcefrom="admin"; } else { $sourcefrom="install"; } } else { $sourcefrom="public"; } // Set path for captcha verification.php if ($sourcefrom == "admin") { $captchapath='../'; } else { $captchapath=''; } //BEFORE SESSIONCONTOL BECAUSE OF THE CONNECTION //CACHE DATA $connect=ADONewConnection($databasetype); $database_exists = FALSE; switch ($databasetype) { case "postgres": case "mysqli": case "mysql": if ($databaseport!="default") {$dbhost="$databaselocation:$databaseport";} else {$dbhost=$databaselocation;} break; case "mssql_n": case "mssql": if ($databaseport!="default") {$dbhost="$databaselocation,$databaseport";} else {$dbhost=$databaselocation;} break; case "odbc_mssql": $dbhost="Driver={SQL Server};Server=$databaselocation;Database=".$databasename; break; default: safe_die("Unknown database type"); } // Now try connecting to the database if ($databasepersistent==true) { if (@$connect->PConnect($dbhost, $databaseuser, $databasepass, $databasename)) { $database_exists = TRUE; } else { // If that doesnt work try connection without database-name $connect->database = ''; if (!@$connect->PConnect($dbhost, $databaseuser, $databasepass)) { safe_die("Can't connect to LimeSurvey database. Reason: ".$connect->ErrorMsg()); } } } else { if (@$connect->Connect($dbhost, $databaseuser, $databasepass, $databasename)) { $database_exists = TRUE; } else { // If that doesnt work try connection without database-name $connect->database = ''; if (!@$connect->Connect($dbhost, $databaseuser, $databasepass)) { safe_die("Can't connect to LimeSurvey database. Reason: ".$connect->ErrorMsg()); } } } // AdoDB seems to be defaulting to ADODB_FETCH_NUM and we want to be sure that the right default mode is set $connect->SetFetchMode(ADODB_FETCH_ASSOC); $dbexistsbutempty=($database_exists && !tableExists('surveys')); if ($databasetype=='mysql' || $databasetype=='mysqli') { if ($debug>1) { @$connect->Execute("SET SESSION SQL_MODE='STRICT_ALL_TABLES,ANSI'"); } //for development - use mysql in the strictest mode //Checked $infoarray=$connect->ServerInfo(); if (version_compare ($infoarray['version'],'4.1','<')) { safe_die ("
Error: You need at least MySQL version 4.1 to run LimeSurvey. Your version:".$infoarray['version']); } @$connect->Execute("SET CHARACTER SET 'utf8'"); //Checked @$connect->Execute("SET NAMES 'utf8'"); //Checked } // Setting dateformat for mssql driver. It seems if you don't do that the in- and output format could be different if ($databasetype=='odbc_mssql' || $databasetype=='odbtp' || $databasetype=='mssql_n') { @$connect->Execute('SET DATEFORMAT ymd;'); //Checked @$connect->Execute('SET QUOTED_IDENTIFIER ON;'); //Checked } // Check if the DB is up to date If( $dbexistsbutempty && !stristr( $_SERVER['PHP_SELF'] , '/install/index/php' ) ) { die ("
The LimeSurvey database does exist but it seems to be empty. Please run the install script to create the necessary tables."); } // Default global values that should not appear in config-defaults.php $updateavailable=0; $updatebuild=''; $updateversion=''; $updatelastcheck=''; $updatekey=''; $updatekeyvaliduntil=''; require ($homedir.'/globalsettings.php'); // Check if the DB is up to date If (!$dbexistsbutempty && $sourcefrom=='admin') { $usrow = getGlobalSetting('DBVersion'); if (intval($usrow)<$dbversionnumber) { $action=''; require_once($rootdir.'/classes/core/language.php'); $clang = new limesurvey_lang($defaultlang); include_once($homedir.'/update/updater.php'); $output=CheckForDBUpgrades(); echo $output; echo "
".$clang->gT("Back to main menu").""; updatecheck(); die(); } if (is_dir($homedir."/install") && $debug<2) { die ("
Everything is fine - you just forgot to delete or rename your LimeSurvey installation directory (/admin/install).
Please do so since it may be a security risk."); } } //Admin menus and standards //IF THIS IS AN ADMIN SCRIPT, RUN THE SESSIONCONTROL SCRIPT if ($sourcefrom == "admin") { include($homedir."/sessioncontrol.php"); /** * @param string $htmlheader * This is the html header text for all administration pages * */ $htmlheader = getAdminHeader(); } //SET LANGUAGE DIRECTORY if ($sourcefrom == "admin") { $langdir="$publicurl/locale/".$_SESSION['adminlang']."/help"; $langdirlocal="$rootdir/locale/".$_SESSION['adminlang']."/help"; if (!is_dir($langdirlocal)) // is_dir only works on local dirs { $langdir="$publicurl/locale/en/help"; //default to english if there is no matching language dir } } if ($sourcefrom == "admin" && $buildnumber != "" && $updatecheckperiod>0 && $updatelastcheckgT("Warning: You are still using the default password ('password'). Please change your password and re-login again.")."";} $adminmenu .="\n" . "\n" . "\n"; // $adminmenu .= "

 

"; //CSS Firefox 2 transition fix if (!isset($action) && !isset($surveyid)) { $adminmenu.= '
' .'

'.sprintf($clang->gT("Welcome to %s!"),'LimeSurvey').'

' .'

'.$clang->gT("There are four easy steps to create your own survey:").'
' .'

    ' .'
  1. '.sprintf($clang->gT('Create a new survey clicking on the %s icon in the upper right.'),"". $clang->gT("Add survey")."").'
  2. ' .'
  3. '.$clang->gT('Create a new question group inside your survey.').'
  4. ' .'
  5. '.$clang->gT('Create one or more question inside the new question group.').'
  6. ' .'
  7. '.sprintf($clang->gT('Done. Test your survey using the %s icon.'),"". $clang->gT("Test survey")."").'
  8. ' .'


 
'; } } return $adminmenu; } //DATA TYPES $qtypeselect = getqtypelist(); function &db_execute_num($sql,$inputarr=false) { global $connect; $connect->SetFetchMode(ADODB_FETCH_NUM); $dataset=$connect->Execute($sql,$inputarr); //Checked return $dataset; } function &db_select_limit_num($sql,$numrows=-1,$offset=-1,$inputarr=false) { global $connect; $connect->SetFetchMode(ADODB_FETCH_NUM); $dataset=$connect->SelectLimit($sql,$numrows,$offset,$inputarr=false) or safe_die($sql); return $dataset; } function &db_execute_assoc($sql,$inputarr=false,$silent=false) { global $connect; $connect->SetFetchMode(ADODB_FETCH_ASSOC); $dataset=$connect->Execute($sql,$inputarr); //Checked if (!$silent && !$dataset) {safe_die($connect->ErrorMsg().':'.$sql);} return $dataset; } function &db_select_limit_assoc($sql,$numrows=-1,$offset=-1,$inputarr=false,$dieonerror=true) { global $connect; $connect->SetFetchMode(ADODB_FETCH_ASSOC); $dataset=$connect->SelectLimit($sql,$numrows,$offset,$inputarr=false); if (!$dataset && $dieonerror) {safe_die($connect->ErrorMsg().':'.$sql);} return $dataset; } /** * Returns the first row of values of the $sql query result * as a 1-dimensional array * * @param mixed $sql */ function &db_select_column($sql) { global $connect; $connect->SetFetchMode(ADODB_FETCH_NUM); $dataset=$connect->Execute($sql); $resultarray=array(); while ($row = $dataset->fetchRow()) { $resultarray[]=$row[0]; } return $resultarray; } /** * This functions quotes fieldnames accordingly * * @param mixed $id Fieldname to be quoted */ function db_quote_id($id) { global $databasetype; // WE DONT HAVE nor USE other thing that alfanumeric characters in the field names // $quote = $connect->nameQuote; // return $quote.str_replace($quote,$quote.$quote,$id).$quote; switch ($databasetype) { case "mysqli" : case "mysql" : return "`".$id."`"; break; case "mssql_n" : case "mssql" : case "odbc_mssql" : return "[".$id."]"; break; case "postgres": return "\"".$id."\""; break; default: return "`".$id."`"; } } function db_random() { global $connect,$databasetype; if ($databasetype=='odbc_mssql' || $databasetype=='mssql_n' || $databasetype=='odbtp') {$srandom='NEWID()';} else {$srandom=$connect->random;} return $srandom; } function db_quote($str,$ispostvar=false) // This functions escapes the string only inside { global $connect; if ($ispostvar) { return $connect->escape($str, get_magic_quotes_gpc());} else {return $connect->escape($str);} } function db_quoteall($str,$ispostvar=false) // This functions escapes the string inside and puts quotes around the string according to the used db type // IF you are quoting a variable from a POST/GET then set $ispostvar to true so it doesnt get quoted twice. { global $connect; if ($ispostvar) { return $connect->qstr($str, get_magic_quotes_gpc());} else {return $connect->qstr($str);} } function db_table_name($name) { global $dbprefix; return db_quote_id($dbprefix.$name); } /** * returns the table name without quotes * * @param mixed $name */ function db_table_name_nq($name) { global $dbprefix; return $dbprefix.$name; } /** * Return a sql statement for finding LIKE named tables * * @param mixed $table */ function db_select_tables_like($table) { global $databasetype; switch ($databasetype) { case 'mysqli': case 'mysql' : return "SHOW TABLES LIKE '$table'"; case 'odbtp' : case 'mssql_n' : case 'odbc_mssql' : return "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES where TABLE_TYPE='BASE TABLE' and TABLE_NAME LIKE '$table'"; case 'postgres' : return "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' and table_name like '$table'"; default: safe_die ("Couldn't create 'select tables like' query for connection type 'databaseType'"); } } /** * Return a boolean stating if the table(s) exist(s) * Accepts '%' in names since it uses the 'like' statement * * @param mixed $table */ function db_tables_exist($table) { global $connect; $surveyHasTokensTblQ = db_select_tables_like("$table"); $surveyHasTokensTblResult = db_execute_num($surveyHasTokensTblQ); //Checked if ($surveyHasTokensTblResult->RecordCount() >= 1) { return TRUE; } else { return FALSE; } } /** * getsurveylist() Queries the database (survey table) for a list of existing surveys * * @param mixed $returnarray boolean - if set to true an array instead of an HTML option list is given back * * @global string $surveyid * @global string $dbprefix * @global string $scriptname * @global string $connect * @global string $clang * * @return string This string is returned containing formatted list of existing surveys * */ function getsurveylist($returnarray=false) { global $surveyid, $dbprefix, $scriptname, $connect, $clang, $timeadjust; static $cached = null; if(is_null($cached)) { $surveyidquery = " SELECT a.*, surveyls_title, surveyls_description, surveyls_welcometext, surveyls_url " ." FROM ".db_table_name('surveys')." AS a " . "INNER JOIN ".db_table_name('surveys_languagesettings')." on (surveyls_survey_id=a.sid and surveyls_language=a.language) "; if ($_SESSION['USER_RIGHT_SUPERADMIN'] != 1) { $surveyidquery .= " INNER JOIN ".db_table_name('surveys_rights')." AS b ON a.sid = b.sid "; $surveyidquery .= "WHERE b.uid =".$_SESSION['loginID']; } $surveyidquery .= " order by active DESC, surveyls_title"; $surveyidresult = db_execute_assoc($surveyidquery); //Checked if (!$surveyidresult) {return "Database Error";} $surveynames = $surveyidresult->GetRows(); $cached=$surveynames; } else { $surveynames = $cached; } $surveyselecter = ""; if ($returnarray===true) return $surveynames; $activesurveys=''; $inactivesurveys=''; $expiredsurveys=''; if ($surveynames) { foreach($surveynames as $sv) { $sv['surveyls_title']=htmlspecialchars(strip_tags($sv['surveyls_title'])); if($sv['active']!='Y') { $inactivesurveys .= "\n"; $surveyselecter .= $expiredsurveys . ""; } if ($inactivesurveys!='') { $surveyselecter .= "\n"; $surveyselecter .= $inactivesurveys . ""; } if (!isset($svexist)) {$surveyselecter = "\n".$surveyselecter;} else {$surveyselecter = "\n".$surveyselecter;} return $surveyselecter; } /** * getQuestions() queries the database for an list of all questions matching the current survey and group id * * @global string $surveyid * @global string $gid * @global string $selectedqid * * @return This string is returned containing formatted list of questions in the current survey and group */ function getQuestions($surveyid,$gid,$selectedqid) { global $dbprefix, $scriptname, $connect, $clang; $s_lang = GetBaseLanguageFromSurveyID($surveyid); $qquery = 'SELECT * FROM '.db_table_name('questions')." WHERE sid=$surveyid AND gid=$gid AND language='{$s_lang}' order by question_order"; $qresult = db_execute_assoc($qquery); //checked $qrows = $qresult->GetRows(); if (!isset($questionselecter)) {$questionselecter="";} foreach ($qrows as $qrow) { $qrow['title'] = strip_tags($qrow['title']); $questionselecter .= "\n".$questionselecter; } return $questionselecter; } /** * Gets number of groups inside a particular survey * * @param string $surveyid * @param mixed $lang */ function getGroupSum($surveyid, $lang) { global $surveyid,$dbprefix ; $sumquery3 = "SELECT * FROM ".db_table_name('groups')." WHERE sid=$surveyid AND language='".$lang."'"; //Getting a count of questions for this survey $sumresult3 = db_execute_assoc($sumquery3); //Checked $groupscount = $sumresult3->RecordCount(); return $groupscount ; } /** * Gets number of questions inside a particular group * * @param string $surveyid * @param mixed $groupid */ function getQuestionSum($surveyid, $groupid) { global $surveyid,$dbprefix ; $s_lang = GetBaseLanguageFromSurveyID($surveyid); $sumquery3 = "SELECT * FROM ".db_table_name('questions')." WHERE gid=$groupid and sid=$surveyid AND language='{$s_lang}'"; //Getting a count of questions for this survey $sumresult3 = db_execute_assoc($sumquery3); //Checked $questionscount = $sumresult3->RecordCount(); return $questionscount ; } /** * getMaxgrouporder($surveyid) queries the database for the maximum sortorder of a group. * * @param mixed $surveyid * @global string $surveyid */ function getMaxgrouporder($surveyid) { global $surveyid ; $s_lang = GetBaseLanguageFromSurveyID($surveyid); $max_sql = "SELECT max( group_order ) AS max FROM ".db_table_name('groups')." WHERE sid =$surveyid AND language='{$s_lang}'" ; $max_result =db_execute_assoc($max_sql) ; //Checked $maxrow = $max_result->FetchRow() ; $current_max = $maxrow['max']; if($current_max=="") { return "0" ; } else return ++$current_max ; } /** * getGroupOrder($surveyid,$gid) queries the database for the sortorder of a group. * * @param mixed $surveyid * @param mixed $gid * @return mixed */ function getGroupOrder($surveyid,$gid) { $s_lang = GetBaseLanguageFromSurveyID($surveyid); $grporder_sql = "SELECT group_order FROM ".db_table_name('groups')." WHERE sid =$surveyid AND language='{$s_lang}' AND gid=$gid" ; $grporder_result =db_execute_assoc($grporder_sql); //Checked $grporder_row = $grporder_result->FetchRow() ; $group_order = $grporder_row['group_order']; if($group_order=="") { return "0" ; } else return $group_order ; } /** * getMaxquestionorder($gid) queries the database for the maximum sortorder of a question. * * @global string $surveyid */ function getMaxquestionorder($gid) { global $surveyid ; $gid=sanitize_int($gid); $s_lang = GetBaseLanguageFromSurveyID($surveyid); $max_sql = "SELECT max( question_order ) AS max FROM ".db_table_name('questions')." WHERE gid='$gid' AND language='$s_lang'"; $max_result =db_execute_assoc($max_sql) ; //Checked $maxrow = $max_result->FetchRow() ; $current_max = $maxrow['max']; if($current_max=="") { return "0" ; } else return $current_max ; } /** * getqtypelist() Returns list of question types available in LimeSurvey. Edit this if you are adding a new * question type * * @global string $publicurl * @global string $sourcefrom * * @param string $SelectedCode Value of the Question Type (defaults to "T") * @param string $ReturnType Type of output from this function (defaults to selector) * * @return depending on $ReturnType param, returns a straight "array" of question types, or an list */ function getqtypelist($SelectedCode = "T", $ReturnType = "selector") { global $publicurl; global $sourcefrom, $clang; if ($sourcefrom == "admin") { $qtypes = array( "1"=>$clang->gT("Array (Flexible Labels) Dual Scale"), "5"=>$clang->gT("5 Point Choice"), "A"=>$clang->gT("Array (5 Point Choice)"), "B"=>$clang->gT("Array (10 Point Choice)"), "C"=>$clang->gT("Array (Yes/No/Uncertain)"), "D"=>$clang->gT("Date"), "E"=>$clang->gT("Array (Increase, Same, Decrease)"), "F"=>$clang->gT("Array (Flexible Labels)"), "G"=>$clang->gT("Gender"), "H"=>$clang->gT("Array (Flexible Labels) by Column"), "I"=>$clang->gT("Language Switch"), "K"=>$clang->gT("Multiple Numerical Input"), "L"=>$clang->gT("List (Radio)"), "M"=>$clang->gT("Multiple Options"), "N"=>$clang->gT("Numerical Input"), "O"=>$clang->gT("List With Comment"), "P"=>$clang->gT("Multiple Options With Comments"), "Q"=>$clang->gT("Multiple Short Text"), "R"=>$clang->gT("Ranking"), "S"=>$clang->gT("Short Free Text"), "T"=>$clang->gT("Long Free Text"), "U"=>$clang->gT("Huge Free Text"), "W"=>$clang->gT("List (Flexible Labels) (Dropdown)"), "X"=>$clang->gT("Boilerplate Question"), "Y"=>$clang->gT("Yes/No"), "Z"=>$clang->gT("List (Flexible Labels) (Radio)"), "!"=>$clang->gT("List (Dropdown)"), ":"=>$clang->gT("Array (Multi Flexible) (Numbers)"), ";"=>$clang->gT("Array (Multi Flexible) (Text)"), ); asort($qtypes); if ($ReturnType == "array") {return $qtypes;} $qtypeselecter = ""; foreach($qtypes as $TypeCode=>$TypeDescription) { $qtypeselecter .= "