Anonymous Login
2016-12-07 21:14 CET

View Issue Details Jump to Notes ]
IDProjectCategoryView StatusLast Update
03649User patchesStatisticspublic2012-06-21 13:23
Reporterrakete 
Assigned Toelameno 
PrioritynormalSeverityfeature 
StatusclosedResolutionfixed 
Product Version 
Target VersionFixed in Version1.91 
Summary03649: LSRC: retrieve results from a survey
DescriptionA function which retrieve results from a survey and gives back the data.

function call could look like this
- sGetResult($user, $pass, $sid, [$format, $startrow, $endrow])

return could be csv and maybe other.



from thread:

http://www.limesurvey.org/en/support/forums/5-can-i-do-this-with-limesurvey/30568-re3-things-i-need
TagsNo tags attached.
Complete LimeSurvey version number (& build)
Attached Files
  • diff file icon getResults3.diff (80,505 bytes) 2010-02-18 17:06 -
    Index: admin/exportresults.php
    ===================================================================
    --- admin/exportresults.php	(revision 8411)
    +++ admin/exportresults.php	(working copy)
    @@ -358,1060 +358,7 @@
     }
     
     
    +	require_once('exportresults_common.php');
     
    -
    -
    -// ======================================================================
    -// Actual export routines start here !
    -// ======================================================================
    -
    -$tokenTableExists=tableExists('tokens_'.$surveyid);
    -
    -if ($tokenTableExists)
    -{
    -    $attributeFieldAndNames=GetTokenFieldsAndNames($surveyid,true);
    -    $attributeFields=array_keys($attributeFieldAndNames);
    -}
    -
    -//sendcacheheaders();             // sending "cache headers" before this permit us to send something else than a "text/html" content-type
    -switch ( $_POST["type"] ) {     // this is a step to register_globals = false ;c)
    -	case "doc":
    -		header("Content-Disposition: attachment; filename=results-survey".$surveyid.".doc");
    -		header("Content-type: application/vnd.ms-word");
    -		$separator="\t";
    -		break;
    -	case "xls":
    -
    -		$workbook = new Spreadsheet_Excel_Writer();
    -		$workbook->setVersion(8);
    -		// Inform the module that our data will arrive as UTF-8.
    -		// Set the temporary directory to avoid PHP error messages due to open_basedir restrictions and calls to tempnam("", ...)
    -		if (!empty($tempdir)) {
    -			$workbook->setTempDir($tempdir);
    -		}
    -		$workbook->send('results-survey'.$surveyid.'.xls');
    -		// Creating the first worksheet
    -		
    -		$query="SELECT * FROM {$dbprefix}surveys_languagesettings WHERE surveyls_survey_id=".$surveyid;
    -		$result=db_execute_assoc($query) or safe_die("Couldn't get privacy data<br />$query<br />".$connect->ErrorMsg());
    -		$row = $result->FetchRow();
    -		
    -		$sheet =& $workbook->addWorksheet(utf8_decode($row['surveyls_title']));
    -		$sheet->setInputEncoding('utf-8');
    -		$separator="~|";
    -		break;
    -	case "csv":
    -		header("Content-Disposition: attachment; filename=results-survey".$surveyid.".csv");
    -		header("Content-type: text/comma-separated-values; charset=UTF-8");
    -		$separator=",";
    -		break;
    -	case "pdf":
    -		$pdf = new PDF($pdforientation,'mm','A4');
    -		$pdf->SetFont($pdfdefaultfont,'',$pdffontsize);
    -		$pdf->AddPage();
    -		$pdf->intopdf("PDF Export ".date("Y.m.d-H:i",time()));
    -		$query="SELECT * FROM {$dbprefix}surveys_languagesettings WHERE surveyls_survey_id=".$surveyid;
    -		$result=db_execute_assoc($query) or safe_die("Couldn't get privacy data<br />$query<br />".$connect->ErrorMsg());
    -		while ($row = $result->FetchRow())
    -		{
    -			$pdf->intopdf($clang->gT("General information in language: ").getLanguageNameFromCode($row['surveyls_language']),'B');
    -			$pdf->ln();
    -			$pdf->titleintopdf($row['surveyls_title'],$row['surveyls_description']);
    -			$surveyname=$row['surveyls_title'];
    -		}
    -		$pdf->AddPage();
    -		$separator="\t";
    -		break;
    -	default:
    -		header("Content-Disposition: attachment; filename=results-survey".$surveyid.".csv");
    -		header("Content-type: text/comma-separated-values; charset=UTF-8");
    -		$separator=",";
    -		break;
    -}
    -Header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    -
    -// Export Language is set by default to surveybaselang
    -// * the explang language code is used in SQL queries
    -// * the alang object is used to translate headers and hardcoded answers
    -// In the future it might be possible to 'post' the 'export language' from
    -// the exportresults form
    -$explang = $surveybaselang;
    -$elang=new limesurvey_lang($explang);
    -
    -//STEP 1: First line is column headings
    -
    -$fieldmap=createFieldMap($surveyid);
    -
    -// We make the fieldmap alot more accesible by using the SGQA identifier as key
    -// so we do not need ArraySearchByKey later
    -foreach ($fieldmap as $fieldentry)
    -{
    -	$outmap[]=$fieldentry['fieldname'];
    -	$outmap[$fieldentry['fieldname']]['type']= $fieldentry['type'];
    -	$outmap[$fieldentry['fieldname']]['sid']= $fieldentry['sid'];
    -	$outmap[$fieldentry['fieldname']]['gid']= $fieldentry['gid'];
    -	$outmap[$fieldentry['fieldname']]['qid']= $fieldentry['qid'];
    -	$outmap[$fieldentry['fieldname']]['aid']= $fieldentry['aid'];
    -	if (isset($fieldentry['lid1'])) {$outmap[$fieldentry['fieldname']]['lid1']= $fieldentry['lid1'];}
    -	if ($fieldentry['qid']!='')
    -	{
    -		$qq = "SELECT lid, other FROM {$dbprefix}questions WHERE qid={$fieldentry['qid']} and language='$surveybaselang'";
    -		$qr = db_execute_assoc($qq) or safe_die("Error selecting type and lid from questions table.<br />".$qq."<br />".$connect->ErrorMsg());
    -		while ($qrow = $qr->FetchRow())
    -		{
    -			$outmap[$fieldentry['fieldname']]['lid']=$qrow['lid'];
    -			$outmap[$fieldentry['fieldname']]['other']=$qrow['other'];
    -		}
    -	}
    -
    -}
    -//Get the fieldnames from the survey table for column headings
    -$surveytable = "{$dbprefix}survey_$surveyid";
    -if (isset($_POST['colselect']))
    -{
    -	$selectfields="";
    -	foreach($_POST['colselect'] as $cs)
    -	{
    -		if ($cs != 'completed')
    -		{
    -			$selectfields.= db_quote_id($cs).", ";
    -		}
    -		else
    -		{
    -			$selectfields.= "CASE WHEN $surveytable.submitdate IS NULL THEN 'N' ELSE 'Y' END AS completed, ";
    -		}
    -	}
    -	$selectfields = mb_substr($selectfields, 0, strlen($selectfields)-2);
    -}
    -else
    -{
    -	$selectfields="$surveytable.*, CASE WHEN $surveytable.submitdate IS NULL THEN 'N' ELSE 'Y' END AS completed";
    -}
    -
    -$dquery = "SELECT $selectfields";
    -if (isset($_POST['first_name']) && $_POST['first_name']=="on")
    -{
    -	$dquery .= ", {$dbprefix}tokens_$surveyid.firstname";
    -}
    -if (isset($_POST['last_name']) && $_POST['last_name']=="on")
    -{
    -	$dquery .= ", {$dbprefix}tokens_$surveyid.lastname";
    -}
    -if (isset($_POST['email_address']) && $_POST['email_address']=="on")
    -{
    -	$dquery .= ", {$dbprefix}tokens_$surveyid.email";
    -}
    -
    -if ($tokenTableExists && $thissurvey['private']=='N')
    -{
    -    if (isset($_POST['token']) && $_POST['token']=="on")
    -    {
    -	    $dquery .= ", {$dbprefix}tokens_$surveyid.token";
    -    }
    -
    -    foreach ($attributeFields as $attr_name)
    -    {
    -        if (isset($_POST[$attr_name]) && $_POST[$attr_name]=="on")
    -        {
    -            $dquery .= ", {$dbprefix}tokens_$surveyid.$attr_name";
    -        }
    -    }
    -}
    -$dquery .= " FROM $surveytable";
    -
    -if ($tokenTableExists && $thissurvey['private']=='N')
    -{
    -    $dquery .= " LEFT OUTER JOIN {$dbprefix}tokens_$surveyid"
    -	. " ON $surveytable.token = {$dbprefix}tokens_$surveyid.token";
    -}
    -if (incompleteAnsFilterstate() == "filter")
    -{
    -	$dquery .= "  WHERE $surveytable.submitdate is not null ";
    -} elseif (incompleteAnsFilterstate() == "inc")
    -{
    -	$dquery .= "  WHERE $surveytable.submitdate is null ";
    -}
    -
    -$dquery .=" ORDER BY id ";
    -
    -$dresult = db_select_limit_assoc($dquery, 1) or safe_die($clang->gT("Error")." getting results<br />$dquery<br />".$connect->ErrorMsg());
    -$fieldcount = $dresult->FieldCount();
    -$firstline="";
    -$faid="";
    -for ($i=0; $i<$fieldcount; $i++)
    -{
    -	//Iterate through column names and output headings
    -	$field=$dresult->FetchField($i);
    -	$fieldinfo=$field->name;
    -
    -	if ($fieldinfo == "lastname")
    -	{
    -		if ($type == "csv") {$firstline .= "\"".$elang->gT("Last Name")."\"$separator";}
    -		else {$firstline .= $elang->gT("Last Name")."$separator";}
    -	}
    -	elseif ($fieldinfo == "firstname")
    -	{
    -		if ($type == "csv") {$firstline .= "\"".$elang->gT("First Name")."\"$separator";}
    -		else {$firstline .= $elang->gT("First Name")."$separator";}
    -	}
    -	elseif ($fieldinfo == "email")
    -	{
    -		if ($type == "csv") {$firstline .= "\"".$elang->gT("Email Address")."\"$separator";}
    -		else {$firstline .= $elang->gT("Email Address")."$separator";}
    -	}
    -	elseif ($fieldinfo == "token")
    -	{
    -		if ($type == "csv") {$firstline .= "\"".$elang->gT("Token")."\"$separator";}
    -		else {$firstline .= $elang->gT("Token")."$separator";}
    -	}
    -	elseif (substr($fieldinfo,0,10)=="attribute_")
    -	{
    -		if ($type == "csv") {$firstline .= CSVEscape($fieldinfo)."$separator";}
    -		else {$firstline .= $attributeFieldAndNames[$fieldinfo]."$separator";}
    -	}
    -	elseif ($fieldinfo == "id")
    -	{
    -		if ($type == "csv") {$firstline .= "\"id\"$separator";}
    -		else {$firstline .= "id$separator";}
    -	}
    -	elseif ($fieldinfo == "datestamp")
    -	{
    -		if ($type == "csv") {$firstline .= "\"".$elang->gT("Date Last Action")."\"$separator";}
    -		else {$firstline .= $elang->gT("Date Last Action")."$separator";}
    -	}
    -	elseif ($fieldinfo == "startdate")
    -	{
    -		if ($type == "csv") {$firstline .= "\"".$elang->gT("Date Started")."\"$separator";}
    -		else {$firstline .= $elang->gT("Date Started")."$separator";}
    -	}
    -	elseif ($fieldinfo == "completed")
    -	{
    -		if ($type == "csv") {$firstline .= "\"".$elang->gT("Completed")."\"$separator";}
    -		else {$firstline .= $elang->gT("Completed")."$separator";}
    -	}
    -	elseif ($fieldinfo == "ipaddr")
    -	{
    -		if ($type == "csv") {$firstline .= "\"".$elang->gT("IP-Address")."\"$separator";}
    -		else {$firstline .= $elang->gT("IP-Address")."$separator";}
    -	}
    -	elseif ($fieldinfo == "refurl")
    -	{
    -		if ($type == "csv") {$firstline .= "\"".$elang->gT("Referring URL")."\"$separator";}
    -		else {$firstline .= $elang->gT("Referring URL")."$separator";}
    -	}
    -	else
    -	{
    -		//Data fields!
    -		//$fielddata=arraySearchByKey($fieldinfo, $fieldmap, "fieldname", 1);
    -		$fielddata=$outmap[$fieldinfo];
    -
    -		$fqid=$fielddata['qid'];
    -		$ftype=$fielddata['type'];
    -		$fsid=$fielddata['sid'];
    -		$fgid=$fielddata['gid'];
    -		$faid=$fielddata['aid'];
    -		if ($exportstyle == "abrev")
    -		{
    -			$qq = "SELECT question FROM {$dbprefix}questions WHERE qid=$fqid and language='$explang'";
    -			$qr = db_execute_assoc($qq);
    -			while ($qrow=$qr->FetchRow())
    -			{$qname=$qrow['question'];}
    -			$qname=strip_tags_full($qname);
    -			$qname=mb_substr($qname, 0, 15)."..";
    -			$firstline = str_replace("\n", "", $firstline);
    -			$firstline = str_replace("\r", "", $firstline);
    -			if ($type == "csv") {$firstline .= "\"$qname";}
    -			else {$firstline .= "$qname";}
    -			if (isset($faid)) {$firstline .= " [{$faid}]"; $faid="";}
    -			if ($ftype == ":" || $ftype == ";")
    -			{
    -					
    -			}
    -			if ($type == "csv") {$firstline .= "\"";}
    -			$firstline .= "$separator";
    -		}
    -		else    //headcode or full answer
    -		{
    -			$qq = "SELECT question, type, other, title FROM {$dbprefix}questions WHERE qid=$fqid AND language='$explang' ORDER BY gid, title"; //get the question
    -			$qr = db_execute_assoc($qq) or safe_die ("ERROR:<br />".$qq."<br />".$connect->ErrorMsg());
    -			while ($qrow=$qr->FetchRow())
    -			{
    -				if ($exportstyle == "headcodes"){$fquest=$qrow['title'];}
    -				else {$fquest=$qrow['question'];}
    -			}
    -			switch ($ftype)
    -			{
    -				case "R": //RANKING TYPE
    -					$fquest .= " [".$elang->gT("Ranking")." $faid]";
    -					break;
    -				case "L":
    -				case "!":
    -				case "W":
    -				case "Z":
    -					if ($faid == "other") {
    -						$fquest .= " [".$elang->gT("Other")."]";
    -					}
    -					break;
    -				case "O": //DROPDOWN LIST WITH COMMENT
    -					if ($faid == "comment")
    -					{
    -						$fquest .= " - Comment";
    -					}
    -					break;
    -				case "M": //multioption
    -					if ($faid == "other")
    -					{
    -						$fquest .= " [".$elang->gT("Other")."]";
    -					}
    -					else
    -					{
    -						if ($answers == "short") {
    -							$fquest .= " [$faid]"; //Show only the code
    -						}
    -						else
    -						{
    -							$lq = "SELECT * FROM {$dbprefix}answers WHERE qid=$fqid AND code = '$faid' AND language = '$explang'";
    -							$lr = db_execute_assoc($lq);
    -							while ($lrow = $lr->FetchRow())
    -							{
    -								$fquest .= " [".strip_tags_full($lrow['answer'])."]";
    -							}
    -						}
    -					}
    -					break;
    -				case "P": //multioption with comment
    -					if (mb_substr($faid, -7, 7) == "comment")
    -					{
    -						$faid=mb_substr($faid, 0, -7);
    -						$comment=true;
    -					}
    -					if ($faid == "other")
    -					{
    -						$fquest .= " [".$elang->gT("Other")."]";
    -					}
    -					else
    -					{
    -						if ($answers == "short") {
    -							$fquest .= " [$faid]"; //Show only the code
    -						}
    -						else
    -						{
    -							$lq = "SELECT * FROM {$dbprefix}answers WHERE qid=$fqid AND code = '$faid' AND language = '$explang'";
    -							$lr = db_execute_assoc($lq);
    -							while ($lrow = $lr->FetchRow())
    -							{
    -								$fquest .= " [".strip_tags_full($lrow['answer'])."]";
    -							}
    -						}
    -					}
    -					if (isset($comment) && $comment == true) {$fquest .= " - comment"; $comment=false;}
    -					break;
    -				case "A":
    -				case "B":
    -				case "C":
    -				case "E":
    -				case "F":
    -				case "H":
    -				case "K":
    -				case "Q":
    -				case "^":
    -					if ($answers == "short") {
    -						$fquest .= " [$faid]";
    -					}
    -					else
    -					{
    -						$lq = "SELECT * FROM {$dbprefix}answers WHERE qid=$fqid AND code= '$faid' AND language = '$explang'";
    -						$lr = db_execute_assoc($lq);
    -						while ($lrow=$lr->FetchRow())
    -						{
    -							$fquest .= " [".strip_tags_full($lrow['answer'])."]";
    -						}
    -					}
    -					break;
    -				case ":":
    -				case ";":
    -					list($faid, $fcode) = explode("_", $faid);
    -					if ($answers == "short") {
    -						$fquest .= " [$faid] [$fcode]";
    -					} else {
    -						$lq1="SELECT lid FROM {$dbprefix}questions WHERE qid=$fqid";
    -						$lr1=db_execute_assoc($lq1);
    -						while($lrow1=$lr1->FetchRow()) {
    -							$flid = $lrow1['lid'];
    -						}
    -						$lq = "SELECT * FROM {$dbprefix}answers WHERE qid=$fqid AND code= '$faid' AND language = '$explang'";
    -						$lr = db_execute_assoc($lq);
    -						while ($lrow=$lr->FetchRow())
    -						{
    -							$lq2 = "SELECT * FROM {$dbprefix}labels WHERE lid=$flid AND code='$fcode' AND language = '$explang'";
    -							$lr2 = db_execute_assoc($lq2);
    -							while ($lrow2=$lr2->FetchRow())
    -							{
    -								$fquest .= " [".$lrow['answer']."] [".$lrow2['title']."]";
    -							}
    -						}
    -					}
    -					break;
    -				case "1": // multi scale Headline
    -					$flid=$fielddata['lid'];
    -					$flid1=$fielddata['lid1'];
    -					if (mb_substr($fieldinfo,-1) == '0')
    -					{ //TIBO
    -						$strlabel = "1";
    -						$lq = "select a.*, l.*, t.label_name as labeltitle from {$dbprefix}answers as a, {$dbprefix}labels as l, {$dbprefix}labelsets as t where a.code='$faid' and qid=$fqid AND l.lid = $flid AND a.language='$surveybaselang'  AND t.lid=$flid";
    -					}
    -					else
    -					{
    -						$strlabel = "2";
    -						$lq = "select a.*, l.*, t.label_name as labeltitle from {$dbprefix}answers as a, {$dbprefix}labels as l, {$dbprefix}labelsets as t where a.code='$faid' and qid=$fqid AND l.lid = $flid1 AND a.language='$surveybaselang'  AND t.lid=$flid1";
    -					}
    -					$lr = db_execute_assoc($lq);
    -					$j=0;
    -					while ($lrow=$lr->FetchRow())
    -					{
    -						$strlabel = $strlabel."-".$lrow['labeltitle'];
    -						$fquest .= " [".FlattenText($lrow['answer'],true)."][".FlattenText($strlabel,true)."]";
    -						$j++;
    -					}
    -					break;
    -
    -			}
    -			$fquest=FlattenText($fquest,true);
    -			if ($type == "csv")
    -			{
    -				$firstline .="\"$fquest\"$separator";
    -			}
    -			else
    -			{
    -				$firstline .= $fquest.$separator;
    -			}
    -		}
    -		if($convertspacetous == "Y")
    -		{
    -			$firstline=str_replace(" ", "_", $firstline);
    -		}
    -	}
    -}
    -if ($type == "csv") { $firstline = mb_substr(trim($firstline),0,strlen($firstline)-1);}
    -else
    -{
    -	$firstline = trim($firstline);
    -}
    -
    -$firstline .= "\n";
    -
    -if ($type == "doc" || $type == "pdf")
    -{
    -	$flarray=explode($separator, $firstline);
    -
    -}
    -else
    -if ($type == "xls")
    -{
    -	//var_dump ($firstline);
    -	$flarray=explode($separator, $firstline);
    -	$fli=0;
    -	foreach ($flarray as $fl)
    -	{
    -		$sheet->write(0,$fli,$fl);
    -		$fli++;
    -	}
    -	//print_r($fieldmap);
    -}
    -else
    -{
    -	$exportoutput .= $firstline; //Sending the header row
    -}
    -
    -
    -//calculate interval because the second argument at SQL "limit"
    -//is the number of records not the ending point
    -$from_record = sanitize_int($_POST['export_from']) - 1;
    -$limit_interval = sanitize_int($_POST['export_to']) - sanitize_int($_POST['export_from']) + 1;
    -$attributefieldAndNames=array();
    -
    -//Now dump the data
    -if ($tokenTableExists && $thissurvey['private']=='N')
    -{
    -	$dquery = "SELECT $selectfields";
    -	if (isset($_POST['first_name']) && $_POST['first_name']=="on")
    -	{
    -		$dquery .= ", {$dbprefix}tokens_$surveyid.firstname";
    -	}
    -	if (isset($_POST['last_name']) && $_POST['last_name']=="on")
    -	{
    -		$dquery .= ", {$dbprefix}tokens_$surveyid.lastname";
    -	}
    -	if (isset($_POST['email_address']) && $_POST['email_address']=="on")
    -	{
    -		$dquery .= ", {$dbprefix}tokens_$surveyid.email";
    -	}
    -	if (isset($_POST['token']) && $_POST['token']=="on")
    -	{
    -		$dquery .= ", {$dbprefix}tokens_$surveyid.token";
    -	}
    -    foreach ($attributeFields as $attributefield)
    -	{
    -        if (isset($_POST[$attributefield]) && $_POST[$attributefield]=="on")
    -	{
    -            $dquery .= ", {$dbprefix}tokens_$surveyid.$attributefield";
    -	}
    -    }
    -	$dquery	.= " FROM $surveytable "
    -	. "LEFT OUTER JOIN {$dbprefix}tokens_$surveyid "
    -	. "ON $surveytable.token={$dbprefix}tokens_$surveyid.token ";
    -	if (incompleteAnsFilterstate() == "filter")
    -	{
    -		$dquery .= "  WHERE $surveytable.submitdate is not null ";
    -	} elseif (incompleteAnsFilterstate() == "inc")
    -	{
    -		$dquery .= "  WHERE $surveytable.submitdate is null ";
    -	}
    -}
    -else // this applies for exporting everything
    -{
    -	$dquery = "SELECT $selectfields FROM $surveytable ";
    -
    -	if (incompleteAnsFilterstate() == "filter")
    -	{
    -		$dquery .= "  WHERE $surveytable.submitdate is not null ";
    -	} elseif (incompleteAnsFilterstate() == "inc")
    -	{
    -		$dquery .= "  WHERE $surveytable.submitdate is null ";
    -	}
    -}
    -
    -if (isset($_POST['sql'])) //this applies if export has been called from the statistics package
    -{
    -	if ($_POST['sql'] != "NULL")
    -	{
    -		if (incompleteAnsFilterstate() == "filter" || incompleteAnsFilterstate() == "inc") {$dquery .= " AND ".stripcslashes($_POST['sql'])." ";}
    -		else {$dquery .= "WHERE ".stripcslashes($_POST['sql'])." ";}
    -	}
    -}
    -if (isset($_POST['answerid']) && $_POST['answerid'] != "NULL") //this applies if export has been called from single answer view
    -{
    -	if (incompleteAnsFilterstate() == "filter" || incompleteAnsFilterstate() == "inc") {$dquery .= " AND $surveytable.id=".stripcslashes($_POST['answerid'])." ";}
    -	else {$dquery .= "WHERE $surveytable.id=".stripcslashes($_POST['answerid'])." ";}
    -}
    -
    -
    -$dquery .= "ORDER BY $surveytable.id";
    -if ($answers == "short") //Nice and easy. Just dump the data straight
    -{
    -	//$dresult = db_execute_assoc($dquery);
    -	$dresult = db_select_limit_assoc($dquery, $limit_interval, $from_record);
    -	$rowcounter=0;
    -	while ($drow = $dresult->FetchRow())
    -	{
    -		$drow=array_map('strip_tags_full',$drow);
    -		if($convertyto1 == "Y")
    -		//Converts "Y" to "1" in export
    -		{
    -		  $convertyto=returnglobal('convertyto');
    -			foreach($drow as $key=>$dr) {
    -				$fielddata=arraySearchByKey($key, $fieldmap, "fieldname", 1);
    -            if(isset($fielddata['type']) &&
    -			   ($fielddata['type'] == "M" || 
    -			   $fielddata['type'] == "P" ||
    -			   $fielddata['type'] == "Y")
    -			   )
    -				{
    -		      if($dr == "Y") {$dr = $convertyto;}
    -				}
    -				$line[$key]=$dr;
    -			}
    -			$drow=$line;
    -		}
    -		if($convertnto2 == "Y")
    -		//Converts "N" to "2" in export
    -		{
    -		  $convertnto=returnglobal('convertnto');
    -		  foreach($drow as $key=>$dr) {
    -            $fielddata=arraySearchByKey($key, $fieldmap, "fieldname", 1);
    -            if(isset($fielddata['type']) &&
    -			   ($fielddata['type'] == "M" || 
    -			   $fielddata['type'] == "P" ||
    -			   $fielddata['type'] == "Y")
    -			   )
    -            {
    -		      if($dr == "N") {$dr = $convertnto;}
    -		    }
    -		    $line[$key]=$dr;
    -		  }
    -		  $drow=$line;
    -		}
    -		$rowcounter++;
    -		if ($type == "csv")
    -		{
    -			$exportoutput .= "\"".implode("\"$separator\"", str_replace("\"", "\"\"", str_replace("\r\n", " ", $drow))) . "\"\n"; //create dump from each row
    -		}
    -		elseif ($type == "xls")
    -		{
    -			$colcounter=0;
    -			foreach ($drow as $rowfield)
    -			{
    -				$rowfield=str_replace("?","-",$rowfield);
    -				$sheet->write($rowcounter,$colcounter,$rowfield);
    -				$colcounter++;
    -			}
    -		}
    -		else if($type == "pdf")
    -		{
    -			$pdf->titleintopdf($clang->gT("New Record"));
    -			foreach ($drow as $rowfield)
    -			{
    -				$rowfield=str_replace("?","-",$rowfield);
    -				$pdfstring .=$rowfield." | ";
    -			}
    -			$pdf->intopdf($pdfstring);
    -		}
    -		else
    -		{
    -			$exportoutput .= implode($separator, str_replace("\r\n", " ", $drow)) . "\n"; //create dump from each row
    -		}
    -	}
    -}
    -elseif ($answers == "long")        //chose complete answers
    -{
    -
    -	$labelscache=array();
    -	//$dresult = db_execute_num($dquery) or safe_die("ERROR: $dquery -".$connect->ErrorMsg());
    -	$dresult = db_select_limit_num($dquery, $limit_interval, $from_record);
    -	$fieldcount = $dresult->FieldCount();
    -	$rowcounter=0;
    -
    -	while ($drow = $dresult->FetchRow())
    -	{
    -		$rowcounter++;
    -		if ($type == "pdf")
    -		{
    -			//$pdf->Write (5,$exportoutput);
    -			if($rowcounter != 1)
    -			{
    -				$pdf->AddPage();
    -			}
    -			$pdf->Cell(0,10,$elang->gT('NEW RECORD')." ".$rowcounter,1,1);
    -		}
    -
    -		if ($type == "doc")
    -		{
    -			$exportoutput .= "\n\n\n".$elang->gT('NEW RECORD')."\n";
    -		}
    -		for ($i=0; $i<$fieldcount; $i++) //For each field, work out the QID
    -		{
    -			$fqid=0;            // By default fqid is set to zero
    -			$field=$dresult->FetchField($i);
    -			$fieldinfo=$field->name;
    -            if ($fieldinfo != "startlanguage" && $fieldinfo != "id" && $fieldinfo != "datestamp" && $fieldinfo != "startdate" && $fieldinfo != "ipaddr"  && $fieldinfo != "refurl" && $fieldinfo != "token" && $fieldinfo != "firstname" && $fieldinfo != "lastname" && $fieldinfo != "email" && (substr($fieldinfo,0,10)!="attribute_") && $fieldinfo != "completed")
    -			{
    -				//				$fielddata=arraySearchByKey($fieldinfo, $fieldmap, "fieldname", 1);
    -				$fielddata=$outmap[$fieldinfo];
    -				$fqid=$fielddata['qid'];
    -				$ftype=$fielddata['type'];
    -				$fsid=$fielddata['sid'];
    -				$fgid=$fielddata['gid'];
    -				$faid=$fielddata['aid'];
    -				$flid=$fielddata['lid'];
    -				if (isset($fielddata['lid1'])) {$flid1=$fielddata['lid1'];}
    -
    -				$fother=$fielddata['other'];
    -				if ($type == "doc" || $type == "pdf")
    -				{
    -					$ftitle=$flarray[$i];
    -				}
    -			}
    -			else
    -			{
    -				$fsid=""; $fgid="";
    -				if ($type == "doc" || $type == "pdf")
    -				{
    -					switch($fieldinfo)
    -					{
    -						case "datestamp":
    -							$ftitle=$elang->gT("Date Last Action").":";
    -							break;
    -						case "startdate":
    -							$ftitle=$elang->gT("Date Started").":";
    -							break;
    -						case "ipaddr":
    -							$ftitle=$elang->gT("IP Address").":";
    -							break;
    -						case "completed":
    -							$ftitle=$elang->gT("Completed").":";
    -							break;
    -						case "refurl":
    -							$ftitle=$elang->gT("Referring URL").":";
    -							break;
    -						case "firstname":
    -							$ftitle=$elang->gT("First Name").":";
    -							break;
    -						case "lastname":
    -							$ftitle=$elang->gT("Last Name").":";
    -							break;
    -						case "email":
    -							$ftitle=$elang->gT("Email").":";
    -							break;
    -						case "id":
    -							$ftitle=$elang->gT("ID").":";
    -							break;
    -						case "token":
    -							$ftitle=$elang->gT("Token").":";
    -							break;
    -						case "tid":
    -							$ftitle=$elang->gT("Token ID").":";
    -							break;
    -						case "startlanguage":
    -							$ftitle=$elang->gT("Language").":";
    -							break;
    -						default:
    -                        if (substr($fieldinfo,0,10)=='attribute_')
    -                        {
    -                           $ftitle=$attributeFieldAndNames[$fieldinfo]; 
    -                        }
    -                        else
    -                        {
    -                            $fielddata=$outmap[$fieldinfo];  
    -                            if (isset($fielddata['title']) && !isset($ftitle)) {$ftitle=$fielddata['title'].":";}                             
    -                        }
    -					} // switch
    -				}
    -			}
    -			if ($fqid == 0)
    -			{
    -				$ftype = "-";  //   This is set if it not a normal answer field, but something like tokenID, First Name etc
    -			}
    -			if ($type == "csv") {$exportoutput .= "\"";}
    -			if ($type == "doc") {$exportoutput .= "\n$ftitle\n\t";}
    -			if ($type == "pdf"){ $pdf->intopdf($ftitle);}
    -			switch ($ftype)
    -			{
    -				case "-": //SPECIAL Placeholder TYPE
    -					$exportoutput .= $drow[$i];
    -					if($type == "pdf"){$pdf->intopdf($drow[$i]);}
    -					break;
    -				case "R": //RANKING TYPE
    -					$lq = "SELECT * FROM {$dbprefix}answers WHERE qid=$fqid AND language='$explang' AND code = ?";
    -					$lr = db_execute_assoc($lq, array($drow[$i]));
    -					while ($lrow = $lr->FetchRow())
    -					{
    -						$exportoutput .= strip_tags_full($lrow['answer']);
    -						if($type == "pdf"){$pdf->intopdf(strip_tags_full($lrow['answer']));}
    -					}
    -					break;
    -				case "1":
    -					if (mb_substr($fieldinfo,-1) == 0)
    -					{
    -						$lq = "select a.*, l.*, l.code as lcode, l.title as ltitle from {$dbprefix}answers as a, {$dbprefix}labels as l where qid=$fqid AND l.lid =$flid AND a.language='$explang' AND l.code = ? group by l.lid";
    -					}
    -					else
    -					{
    -						$lq = "select a.*, l.*, l.code as lcode, l.title as ltitle from {$dbprefix}answers as a, {$dbprefix}labels as l where qid=$fqid AND l.lid =$flid1 AND a.language='$explang' AND l.code = ? group by l.lid";
    -					}
    -					$lr = db_execute_assoc($lq, array($drow[$i])) or safe_die($lq."<br />ERROR:<br />".$connect->ErrorMsg());
    -					while ($lrow = $lr->FetchRow())
    -					{
    -						$exportoutput .= strip_tags_full($lrow['ltitle']);
    -						if($type == "pdf"){$pdf->intopdf(strip_tags_full($lrow['ltitle']));}
    -					}
    -					break;
    -				case "L": //DROPDOWN LIST
    -				case "!":
    -					if (mb_substr($fieldinfo, -5, 5) == "other")
    -					{
    -						$exportoutput .= strip_tags_full($drow[$i]);
    -						if($type == "pdf"){$pdf->intopdf($drow[$i]);}
    -					}
    -					else
    -					{
    -						if ($drow[$i] == "-oth-")
    -						{
    -							$exportoutput .= $elang->gT("Other");
    -							if($type == "pdf"){$pdf->intopdf($elang->gT("Other"));}
    -						}
    -						else
    -						{
    -							$lq = "SELECT * FROM {$dbprefix}answers WHERE qid=$fqid AND language='$explang' AND code = ?";
    -							$lr = db_execute_assoc($lq, array($drow[$i])) or safe_die($lq."<br />ERROR:<br />".$connect->ErrorMsg());
    -							while ($lrow = $lr->FetchRow())
    -							{
    -								//if ($lrow['code'] == $drow[$i]) {$exportoutput .= $lrow['answer'];}
    -								if ($type == "csv")
    -								{
    -									$exportoutput .= str_replace("\"", "\"\"", strip_tags_full($lrow['answer']));
    -									if($type == "pdf"){$pdf->intopdf(str_replace("\"", "\"\"", strip_tags_full($lrow['answer'])));}
    -								}
    -								else
    -								{
    -									$exportoutput .= strip_tags_full($lrow['answer']);
    -									if($type == "pdf"){$pdf->intopdf(strip_tags_full($lrow['answer']));}
    -								}
    -
    -							}
    -						}
    -					}
    -					break;
    -				case "W":
    -				case "Z":
    -					if (mb_substr($fieldinfo, -5, 5) == "other")
    -					{
    -						$exportoutput .= strip_tags_full($drow[$i]);
    -						if($type == "pdf"){$pdf->intopdf($drow[$i]);}
    -					}
    -					else
    -					{
    -						if ($drow[$i] == "-oth-")
    -						{
    -							$exportoutput .= $elang->gT("Other");
    -							if($type == "pdf"){$pdf->intopdf($elang->gT("Other"));}
    -						}
    -						else
    -						{
    -							$fquery = "SELECT * FROM {$dbprefix}labels WHERE lid=$flid AND language='$explang' AND code='$drow[$i]'";
    -							$fresult = db_execute_assoc($fquery) or safe_die("ERROR:".$fquery."<br />".$qq."<br />".$connect->ErrorMsg());
    -							while ($frow = $fresult->FetchRow())
    -							{
    -								$exportoutput .= strip_tags_full($frow['title']);
    -								if($type == "pdf"){$pdf->intopdf($frow['title']);}
    -							}
    -						}
    -					}
    -					break;
    -				case "O": //DROPDOWN LIST WITH COMMENT
    -					$lq = "SELECT * FROM {$dbprefix}answers WHERE qid=$fqid AND language='$explang' ORDER BY answer";
    -					$lr = db_execute_assoc($lq) or safe_die ("Could do it<br />$lq<br />".$connect->ErrorMsg());
    -					$found = "";
    -					while ($lrow = $lr->FetchRow())
    -					{
    -						if ($lrow['code'] == $drow[$i])
    -						{
    -							$exportoutput .= strip_tags_full($lrow['answer']);
    -							$found = "Y";
    -							if($type == "pdf"){$pdf->intopdf(strip_tags_full($lrow['answer']));}
    -						}
    -					}
    -					//This following section exports the comment field
    -					if ($found != "Y")
    -					{
    -						if ($type == "csv")
    -						{$exportoutput .= str_replace("\r\n", "\n", str_replace("\"", "\"\"", strip_tags_full($drow[$i])));}
    -						else if ($type == "pdf")
    -						{$pdf->intopdf(str_replace("\r\n", " ", strip_tags_full($drow[$i])));}
    -						else
    -						{$exportoutput .= str_replace("\r\n", " ", $drow[$i]);}
    -					}
    -					break;
    -				case "Y": //YES\NO
    -					switch($drow[$i])
    -					{
    -						case "Y":
    -							$exportoutput .= $elang->gT("Yes");
    -							if($type == "pdf"){$pdf->intopdf($elang->gT("Yes"));}
    -							break;
    -						case "N":
    -							$exportoutput .= $elang->gT("No");
    -							if($type == "pdf"){$pdf->intopdf($elang->gT("No"));}
    -							break;
    -						default:
    -							$exportoutput .= $elang->gT("N/A");
    -							if($type == "pdf"){$pdf->intopdf($elang->gT("N/A"));}
    -							break;
    -					}
    -					break;
    -				case "G": //GENDER
    -					switch($drow[$i])
    -					{
    -						case "M":
    -							$exportoutput .= $elang->gT("Male");
    -							if($type == "pdf"){$pdf->intopdf($elang->gT("Male"));}
    -							break;
    -						case "F":
    -							$exportoutput .= $elang->gT("Female");
    -							if($type == "pdf"){$pdf->intopdf($elang->gT("Female"));}
    -							break;
    -						default:
    -							$exportoutput .= $elang->gT("N/A");
    -							if($type == "pdf"){$pdf->intopdf($elang->gT("N/A"));}
    -							break;
    -					}
    -					break;
    -				case "M": //multioption
    -				case "P":
    -					if (mb_substr($fieldinfo, -5, 5) == "other")
    -					{
    -						$exportoutput .= strip_tags_full($drow[$i]);
    -						if($type == "pdf"){$pdf->intopdf($drow[$i]);}
    -					}
    -					elseif (mb_substr($fieldinfo, -7, 7) == "comment")
    -					{
    -						$exportoutput .= strip_tags_full($drow[$i]);
    -						if($type == "pdf"){$pdf->intopdf($drow[$i]);}
    -					}
    -					else
    -					{
    -						switch($drow[$i])
    -						{
    -							case "Y":
    -								$exportoutput .= $elang->gT("Yes");
    -								if($type == "pdf"){$pdf->intopdf($elang->gT("Yes"));}
    -								break;
    -							case "N":
    -								$exportoutput .= $elang->gT("No");
    -								if($type == "pdf"){$pdf->intopdf($elang->gT("No"));}
    -								break;
    -							case "":
    -								$exportoutput .= $elang->gT("No");
    -								if($type == "pdf"){$pdf->intopdf($elang->gT("No"));}
    -								break;
    -							default:
    -								$exportoutput .= $drow[$i];
    -								if($type == "pdf"){$pdf->intopdf($drow[$i]);}
    -								break;
    -						}
    -					}
    -					break;
    -				case "C":
    -					switch($drow[$i])
    -					{
    -						case "Y":
    -							$exportoutput .= $elang->gT("Yes");
    -							if($type == "pdf"){$pdf->intopdf($elang->gT("Yes")); }
    -							break;
    -						case "N":
    -							$exportoutput .= $elang->gT("No");
    -							if($type == "pdf"){$pdf->intopdf($elang->gT("No")); }
    -							break;
    -						case "U":
    -							$exportoutput .= $elang->gT("Uncertain");
    -							if($type == "pdf"){$pdf->intopdf($elang->gT("Uncertain"));}
    -							break;
    -					}
    -				case "E":
    -					switch($drow[$i])
    -					{
    -						case "I":
    -							$exportoutput .= $elang->gT("Increase");
    -							if($type == "pdf"){$pdf->intopdf($elang->gT("Increase"));}
    -							break;
    -						case "S":
    -							$exportoutput .= $elang->gT("Same");
    -							if($type == "pdf"){$pdf->intopdf($elang->gT("Same"));}
    -							break;
    -						case "D":
    -							$exportoutput .= $elang->gT("Decrease");
    -							if($type == "pdf"){$pdf->intopdf($elang->gT("Decrease"));}
    -							break;
    -					}
    -					break;
    -				case "F":
    -				case "H":
    -					if (!isset($labelscache[$flid.'|'.$explang.'|'.$drow[$i]]))
    -					{
    -						$fquery = "SELECT * FROM {$dbprefix}labels WHERE lid=$flid AND language='$explang' AND code='$drow[$i]'";
    -						$fresult = db_execute_assoc($fquery) or safe_die("ERROR:".$fquery."\n".$qq."\n".$connect->ErrorMsg());
    -						if ($fresult)
    -						{
    -							$frow=$fresult->FetchRow();
    -							if($type == "pdf"){$pdf->intopdf(strip_tags_full($frow['title']));}
    -							$exportoutput .= strip_tags_full($frow['title']);
    -							$labelscache[$flid.'|'.$explang.'|'.$drow[$i]]=strip_tags_full($frow['title']);
    -						}
    -					}
    -					else
    -					{
    -						$exportoutput .=$labelscache[$flid.'|'.$explang.'|'.$drow[$i]];
    -						if($type == "pdf"){$pdf->intopdf($labelscache[$flid.'|'.$explang.'|'.$drow[$i]]);}
    -					}
    -					break;
    -				case "1": //dual scale
    -					$flid=$fielddata['lid'];
    -					$flid1=$fielddata['lid1'];
    -					if (mb_substr($fieldinfo,-1) == '0')
    -					{
    -						$strlabel = "1";
    -						$lq = "select title from {$dbprefix}labels as l where l.lid = $flid AND l.language='$surveybaselang'";
    -					}
    -					else
    -					{
    -						$strlabel = "2";
    -						$lq = "select title from {$dbprefix}labels as l where l.lid = $flid1 AND l.language='$surveybaselang'";
    -					}
    -					$lr = db_execute_assoc($lq);
    -					while ($lrow=$lr->FetchRow())
    -					{
    -						$fquest .= " [".strip_tags_full($lrow['title'])."][".strip_tags_full($strlabel).". label]";
    -					}
    -
    -					break;
    -
    -				default: $tempresult=$dresult->FetchField($i);
    -				if ($tempresult->name == "token")
    -				{
    -					$tokenquery = "SELECT firstname, lastname FROM {$dbprefix}tokens_$surveyid WHERE token='$drow[$i]'";
    -					if ($tokenresult = db_execute_assoc($tokenquery)) //or safe_die ("Couldn't get token info<br />$tokenquery<br />".$connect->ErrorMsg());
    -					while ($tokenrow=$tokenresult->FetchRow())
    -					{
    -						$exportoutput .= "{$tokenrow['lastname']}, {$tokenrow['firstname']}";
    -						if($type == "pdf"){$pdf->intopdf($tokenrow['lastname']." , ".$tokenrow['firstname']);}
    -					}
    -					else
    -					{
    -						$exportoutput .= $elang->gT("Tokens problem - token table missing");
    -						if($type == "pdf"){$pdf->intopdf($elang->gT("Tokens problem - token table missing"));}
    -					}
    -				}
    -				else
    -				{
    -					if ($type == "csv")
    -					{$exportoutput .= str_replace("\r\n", "\n", str_replace("\"", "\"\"", strip_tags_full($drow[$i])));}
    -					else if ($type == "pdf")
    -					{$pdf->intopdf(str_replace("\r\n", " ", strip_tags_full($drow[$i])));}
    -					else
    -					{$exportoutput .= str_replace("\r\n", " ", $drow[$i]);}
    -				}
    -			}
    -			if ($type == "csv") {$exportoutput .= "\"";}
    -			$exportoutput .= "$separator";
    -			$ftype = "";
    -		}
    -		$exportoutput=mb_substr($exportoutput,0,-(strlen($separator)));
    -		IF ($type=='xls')
    -		{
    -			$rowarray=explode($separator, $exportoutput);
    -			$fli=0;
    -			foreach ($rowarray as $row)
    -			{
    -				$sheet->write($rowcounter,$fli,$row);
    -				$fli++;
    -			}
    -			$exportoutput='';
    -		}
    -		else {$exportoutput .= "\n";}
    -	}
    -}
    -	if ($type=='xls')
    -	{
    -		$workbook->close();
    -	}
    -	else if($type=='pdf')
    -	{
    -		$pdf->Output($clang->gT($surveyname)." ".$surveyid.".pdf","D");
    -	}
    -	else
    -	{
    -		echo $exportoutput;
    -	}
     	exit;
    -
    -
    -	function strip_tags_full($string) {
    -		$string=html_entity_decode($string, ENT_QUOTES, "UTF-8");
    -		mb_regex_encoding('utf-8');
    -		$pattern = array('\r', '\n', '-oth-');
    -		for ($i=0; $i<sizeof($pattern); $i++) {
    -			$string = mb_ereg_replace($pattern[$i], '', $string);
    -		}
    -		return strip_tags($string);
    -	}
    -
    -	?>
    +?>
    Index: admin/exportresults_common.php
    ===================================================================
    --- admin/exportresults_common.php	(revision 0)
    +++ admin/exportresults_common.php	(revision 0)
    @@ -0,0 +1,1096 @@
    +<?php
    +/*
    + * LimeSurvey
    + * Copyright (C) 2007 The LimeSurvey Project Team / Carsten Schmitz
    + * All rights reserved.
    + * License: GNU/GPL License v2 or later, see LICENSE.php
    + * LimeSurvey is free software. This version may have been modified pursuant
    + * to the GNU General Public License, and as distributed it includes or
    + * is derivative of works licensed under the GNU General Public License or
    + * other free or open source software licenses.
    + * See COPYRIGHT.php for copyright notices and details.
    + *
    + * $Id: exportresults.php 8168 2009-12-15 18:58:11Z c_schmitz $
    + */
    +
    +
    +//Ensure script is not run directly, avoid path disclosure
    +include_once("login_check.php");
    +
    +// ======================================================================
    +// Actual export routines start here !
    +// ======================================================================
    +
    +$tokenTableExists=tableExists('tokens_'.$surveyid);
    +
    +if ($tokenTableExists)
    +{
    +    $attributeFieldAndNames=GetTokenFieldsAndNames($surveyid,true);
    +    $attributeFields=array_keys($attributeFieldAndNames);
    +}
    +
    +//sendcacheheaders();             // sending "cache headers" before this permit us to send something else than a "text/html" content-type
    +switch ( $_POST["type"] ) {     // this is a step to register_globals = false ;c)
    +	case "doc":
    +		header("Content-Disposition: attachment; filename=results-survey".$surveyid.".doc");
    +		header("Content-type: application/vnd.ms-word");
    +		$separator="\t";
    +		break;
    +	case "xls":
    +
    +		$workbook = new Spreadsheet_Excel_Writer();
    +		$workbook->setVersion(8);
    +		// Inform the module that our data will arrive as UTF-8.
    +		// Set the temporary directory to avoid PHP error messages due to open_basedir restrictions and calls to tempnam("", ...)
    +		if (!empty($tempdir)) {
    +			$workbook->setTempDir($tempdir);
    +		}
    +		$workbook->send('results-survey'.$surveyid.'.xls');
    +		// Creating the first worksheet
    +		
    +		$query="SELECT * FROM {$dbprefix}surveys_languagesettings WHERE surveyls_survey_id=".$surveyid;
    +		$result=db_execute_assoc($query) or safe_die("Couldn't get privacy data<br />$query<br />".$connect->ErrorMsg());
    +		$row = $result->FetchRow();
    +		
    +		$sheet =& $workbook->addWorksheet(utf8_decode($row['surveyls_title']));
    +		$sheet->setInputEncoding('utf-8');
    +		$separator="~|";
    +		break;
    +	case "csv":
    +		header("Content-Disposition: attachment; filename=results-survey".$surveyid.".csv");
    +		header("Content-type: text/comma-separated-values; charset=UTF-8");
    +		$separator=",";
    +		break;
    +	case "pdf":
    +		$pdf = new PDF($pdforientation,'mm','A4');
    +		$pdf->SetFont($pdfdefaultfont,'',$pdffontsize);
    +		$pdf->AddPage();
    +		$pdf->intopdf("PDF Export ".date("Y.m.d-H:i",time()));
    +		$query="SELECT * FROM {$dbprefix}surveys_languagesettings WHERE surveyls_survey_id=".$surveyid;
    +		$result=db_execute_assoc($query) or safe_die("Couldn't get privacy data<br />$query<br />".$connect->ErrorMsg());
    +		while ($row = $result->FetchRow())
    +		{
    +			$pdf->intopdf($clang->gT("General information in language: ").getLanguageNameFromCode($row['surveyls_language']),'B');
    +			$pdf->ln();
    +			$pdf->titleintopdf($row['surveyls_title'],$row['surveyls_description']);
    +			$surveyname=$row['surveyls_title'];
    +		}
    +		$pdf->AddPage();
    +		$separator="\t";
    +		break;
    +	default:
    +		header("Content-Disposition: attachment; filename=results-survey".$surveyid.".csv");
    +		header("Content-type: text/comma-separated-values; charset=UTF-8");
    +		$separator=",";
    +		break;
    +}
    +Header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    +
    +// Export Language is set by default to surveybaselang
    +// * the explang language code is used in SQL queries
    +// * the alang object is used to translate headers and hardcoded answers
    +// In the future it might be possible to 'post' the 'export language' from
    +// the exportresults form
    +$explang = $surveybaselang;
    +$elang=new limesurvey_lang($explang);
    +
    +//STEP 1: First line is column headings
    +
    +$fieldmap=createFieldMap($surveyid);
    +
    +// We make the fieldmap alot more accesible by using the SGQA identifier as key
    +// so we do not need ArraySearchByKey later
    +foreach ($fieldmap as $fieldentry)
    +{
    +	$outmap[]=$fieldentry['fieldname'];
    +	$outmap[$fieldentry['fieldname']]['type']= $fieldentry['type'];
    +	$outmap[$fieldentry['fieldname']]['sid']= $fieldentry['sid'];
    +	$outmap[$fieldentry['fieldname']]['gid']= $fieldentry['gid'];
    +	$outmap[$fieldentry['fieldname']]['qid']= $fieldentry['qid'];
    +	$outmap[$fieldentry['fieldname']]['aid']= $fieldentry['aid'];
    +	if (isset($fieldentry['lid1'])) {$outmap[$fieldentry['fieldname']]['lid1']= $fieldentry['lid1'];}
    +	if ($fieldentry['qid']!='')
    +	{
    +		$qq = "SELECT lid, other FROM {$dbprefix}questions WHERE qid={$fieldentry['qid']} and language='$surveybaselang'";
    +		$qr = db_execute_assoc($qq) or safe_die("Error selecting type and lid from questions table.<br />".$qq."<br />".$connect->ErrorMsg());
    +		while ($qrow = $qr->FetchRow())
    +		{
    +			$outmap[$fieldentry['fieldname']]['lid']=$qrow['lid'];
    +			$outmap[$fieldentry['fieldname']]['other']=$qrow['other'];
    +		}
    +	}
    +
    +}
    +//Get the fieldnames from the survey table for column headings
    +$surveytable = "{$dbprefix}survey_$surveyid";
    +if (isset($_POST['colselect']))
    +{
    +	$selectfields="";
    +	foreach($_POST['colselect'] as $cs)
    +	{
    +		if ($cs != 'completed')
    +		{
    +			$selectfields.= db_quote_id($cs).", ";
    +		}
    +		else
    +		{
    +			$selectfields.= "CASE WHEN $surveytable.submitdate IS NULL THEN 'N' ELSE 'Y' END AS completed, ";
    +		}
    +	}
    +	$selectfields = mb_substr($selectfields, 0, strlen($selectfields)-2);
    +}
    +else
    +{
    +	$selectfields="$surveytable.*, CASE WHEN $surveytable.submitdate IS NULL THEN 'N' ELSE 'Y' END AS completed";
    +}
    +
    +$dquery = "SELECT $selectfields";
    +if (isset($_POST['first_name']) && $_POST['first_name']=="on")
    +{
    +	$dquery .= ", {$dbprefix}tokens_$surveyid.firstname";
    +}
    +if (isset($_POST['last_name']) && $_POST['last_name']=="on")
    +{
    +	$dquery .= ", {$dbprefix}tokens_$surveyid.lastname";
    +}
    +if (isset($_POST['email_address']) && $_POST['email_address']=="on")
    +{
    +	$dquery .= ", {$dbprefix}tokens_$surveyid.email";
    +}
    +
    +if ($tokenTableExists && $thissurvey['private']=='N')
    +{
    +    if (isset($_POST['token']) && $_POST['token']=="on")
    +    {
    +	    $dquery .= ", {$dbprefix}tokens_$surveyid.token";
    +    }
    +
    +    foreach ($attributeFields as $attr_name)
    +    {
    +        if (isset($_POST[$attr_name]) && $_POST[$attr_name]=="on")
    +        {
    +            $dquery .= ", {$dbprefix}tokens_$surveyid.$attr_name";
    +        }
    +    }
    +}
    +$dquery .= " FROM $surveytable";
    +
    +if ($tokenTableExists && $thissurvey['private']=='N')
    +{
    +    $dquery .= " LEFT OUTER JOIN {$dbprefix}tokens_$surveyid"
    +	. " ON $surveytable.token = {$dbprefix}tokens_$surveyid.token";
    +}
    +if (incompleteAnsFilterstate() == "filter")
    +{
    +	$dquery .= "  WHERE $surveytable.submitdate is not null ";
    +} elseif (incompleteAnsFilterstate() == "inc")
    +{
    +	$dquery .= "  WHERE $surveytable.submitdate is null ";
    +}
    +
    +$dquery .=" ORDER BY id ";
    +
    +$dresult = db_select_limit_assoc($dquery, 1) or safe_die($clang->gT("Error")." getting results<br />$dquery<br />".$connect->ErrorMsg());
    +$fieldcount = $dresult->FieldCount();
    +$firstline="";
    +$faid="";
    +for ($i=0; $i<$fieldcount; $i++)
    +{
    +	//Iterate through column names and output headings
    +	$field=$dresult->FetchField($i);
    +	$fieldinfo=$field->name;
    +
    +	if ($fieldinfo == "lastname")
    +	{
    +		if ($type == "csv") {$firstline .= "\"".$elang->gT("Last Name")."\"$separator";}
    +		else {$firstline .= $elang->gT("Last Name")."$separator";}
    +	}
    +	elseif ($fieldinfo == "firstname")
    +	{
    +		if ($type == "csv") {$firstline .= "\"".$elang->gT("First Name")."\"$separator";}
    +		else {$firstline .= $elang->gT("First Name")."$separator";}
    +	}
    +	elseif ($fieldinfo == "email")
    +	{
    +		if ($type == "csv") {$firstline .= "\"".$elang->gT("Email Address")."\"$separator";}
    +		else {$firstline .= $elang->gT("Email Address")."$separator";}
    +	}
    +	elseif ($fieldinfo == "token")
    +	{
    +		if ($type == "csv") {$firstline .= "\"".$elang->gT("Token")."\"$separator";}
    +		else {$firstline .= $elang->gT("Token")."$separator";}
    +	}
    +	elseif (substr($fieldinfo,0,10)=="attribute_")
    +	{
    +		if ($type == "csv") {$firstline .= CSVEscape($fieldinfo)."$separator";}
    +		else {$firstline .= $attributeFieldAndNames[$fieldinfo]."$separator";}
    +	}
    +	elseif ($fieldinfo == "id")
    +	{
    +		if ($type == "csv") {$firstline .= "\"id\"$separator";}
    +		else {$firstline .= "id$separator";}
    +	}
    +	elseif ($fieldinfo == "datestamp")
    +	{
    +		if ($type == "csv") {$firstline .= "\"".$elang->gT("Date Last Action")."\"$separator";}
    +		else {$firstline .= $elang->gT("Date Last Action")."$separator";}
    +	}
    +	elseif ($fieldinfo == "startdate")
    +	{
    +		if ($type == "csv") {$firstline .= "\"".$elang->gT("Date Started")."\"$separator";}
    +		else {$firstline .= $elang->gT("Date Started")."$separator";}
    +	}
    +	elseif ($fieldinfo == "completed")
    +	{
    +		if ($type == "csv") {$firstline .= "\"".$elang->gT("Completed")."\"$separator";}
    +		else {$firstline .= $elang->gT("Completed")."$separator";}
    +	}
    +	elseif ($fieldinfo == "ipaddr")
    +	{
    +		if ($type == "csv") {$firstline .= "\"".$elang->gT("IP-Address")."\"$separator";}
    +		else {$firstline .= $elang->gT("IP-Address")."$separator";}
    +	}
    +	elseif ($fieldinfo == "refurl")
    +	{
    +		if ($type == "csv") {$firstline .= "\"".$elang->gT("Referring URL")."\"$separator";}
    +		else {$firstline .= $elang->gT("Referring URL")."$separator";}
    +	}
    +	elseif ($fieldinfo == "submitdate")
    +	{
    +		if ($type == "csv") {$firstline .= "\"".$elang->gT("Submit Date")."\"$separator";}
    +		else {$firstline .= $elang->gT("Submit Date")."$separator";}
    +	}
    +	elseif ($fieldinfo == "lastpage")
    +	{
    +		if ($type == "csv") {$firstline .= "\"".$elang->gT("Last Page")."\"$separator";}
    +		else {$firstline .= $elang->gT("Last Page")."$separator";}
    +	}
    +	elseif ($fieldinfo == "startlanguage")
    +	{
    +		if ($type == "csv") {$firstline .= "\"".$elang->gT("Start Language")."\"$separator";}
    +		else {$firstline .= $elang->gT("Start Language")."$separator";}
    +	}
    +	elseif (!isset($outmap[$fieldinfo])) 
    +	{
    +		//This branch is needed in the case where we have not passed in a colselect parameter.
    +		//This is to trap for a condition where we have additional fields we're iterating
    +		//through that are not questions and have not been addressed in prior if/elseif 
    +		//conditions.  In this case we should report that a field was encountered that 
    +		//needs to be handled by the export code. -- Dave Wolff
    +
    +		//TODO Figure out how best to report the error.
    +		die("Encountered an unexpected column selection '$fieldinfo'.");
    +	}
    +	else
    +	{
    +		//Data fields!
    +		//$fielddata=arraySearchByKey($fieldinfo, $fieldmap, "fieldname", 1);
    +		$fielddata=$outmap[$fieldinfo];
    +
    +		$fqid=$fielddata['qid'];
    +		$ftype=$fielddata['type'];
    +		$fsid=$fielddata['sid'];
    +		$fgid=$fielddata['gid'];
    +		$faid=$fielddata['aid'];
    +		if ($exportstyle == "abrev")
    +		{
    +			$qq = "SELECT question FROM {$dbprefix}questions WHERE qid=$fqid and language='$explang'";
    +			$qr = db_execute_assoc($qq);
    +			while ($qrow=$qr->FetchRow())
    +			{$qname=$qrow['question'];}
    +			$qname=strip_tags_full($qname);
    +			$qname=mb_substr($qname, 0, 15)."..";
    +			$firstline = str_replace("\n", "", $firstline);
    +			$firstline = str_replace("\r", "", $firstline);
    +			if ($type == "csv") {$firstline .= "\"$qname";}
    +			else {$firstline .= "$qname";}
    +			if (isset($faid)) {$firstline .= " [{$faid}]"; $faid="";}
    +			if ($ftype == ":" || $ftype == ";")
    +			{
    +					
    +			}
    +			if ($type == "csv") {$firstline .= "\"";}
    +			$firstline .= "$separator";
    +		}
    +		else    //headcode or full answer
    +		{
    +			$qq = "SELECT question, type, other, title FROM {$dbprefix}questions WHERE qid=$fqid AND language='$explang' ORDER BY gid, title"; //get the question
    +			$qr = db_execute_assoc($qq) or safe_die ("ERROR:<br />".$qq."<br />".$connect->ErrorMsg());
    +			while ($qrow=$qr->FetchRow())
    +			{
    +				if ($exportstyle == "headcodes"){$fquest=$qrow['title'];}
    +				else {$fquest=$qrow['question'];}
    +			}
    +			switch ($ftype)
    +			{
    +				case "R": //RANKING TYPE
    +					$fquest .= " [".$elang->gT("Ranking")." $faid]";
    +					break;
    +				case "L":
    +				case "!":
    +				case "W":
    +				case "Z":
    +					if ($faid == "other") {
    +						$fquest .= " [".$elang->gT("Other")."]";
    +					}
    +					break;
    +				case "O": //DROPDOWN LIST WITH COMMENT
    +					if ($faid == "comment")
    +					{
    +						$fquest .= " - Comment";
    +					}
    +					break;
    +				case "M": //multioption
    +					if ($faid == "other")
    +					{
    +						$fquest .= " [".$elang->gT("Other")."]";
    +					}
    +					else
    +					{
    +						if ($answers == "short") {
    +							$fquest .= " [$faid]"; //Show only the code
    +						}
    +						else
    +						{
    +							$lq = "SELECT * FROM {$dbprefix}answers WHERE qid=$fqid AND code = '$faid' AND language = '$explang'";
    +							$lr = db_execute_assoc($lq);
    +							while ($lrow = $lr->FetchRow())
    +							{
    +								$fquest .= " [".strip_tags_full($lrow['answer'])."]";
    +							}
    +						}
    +					}
    +					break;
    +				case "P": //multioption with comment
    +					if (mb_substr($faid, -7, 7) == "comment")
    +					{
    +						$faid=mb_substr($faid, 0, -7);
    +						$comment=true;
    +					}
    +					if ($faid == "other")
    +					{
    +						$fquest .= " [".$elang->gT("Other")."]";
    +					}
    +					else
    +					{
    +						if ($answers == "short") {
    +							$fquest .= " [$faid]"; //Show only the code
    +						}
    +						else
    +						{
    +							$lq = "SELECT * FROM {$dbprefix}answers WHERE qid=$fqid AND code = '$faid' AND language = '$explang'";
    +							$lr = db_execute_assoc($lq);
    +							while ($lrow = $lr->FetchRow())
    +							{
    +								$fquest .= " [".strip_tags_full($lrow['answer'])."]";
    +							}
    +						}
    +					}
    +					if (isset($comment) && $comment == true) {$fquest .= " - comment"; $comment=false;}
    +					break;
    +				case "A":
    +				case "B":
    +				case "C":
    +				case "E":
    +				case "F":
    +				case "H":
    +				case "K":
    +				case "Q":
    +				case "^":
    +					if ($answers == "short") {
    +						$fquest .= " [$faid]";
    +					}
    +					else
    +					{
    +						$lq = "SELECT * FROM {$dbprefix}answers WHERE qid=$fqid AND code= '$faid' AND language = '$explang'";
    +						$lr = db_execute_assoc($lq);
    +						while ($lrow=$lr->FetchRow())
    +						{
    +							$fquest .= " [".strip_tags_full($lrow['answer'])."]";
    +						}
    +					}
    +					break;
    +				case ":":
    +				case ";":
    +					list($faid, $fcode) = explode("_", $faid);
    +					if ($answers == "short") {
    +						$fquest .= " [$faid] [$fcode]";
    +					} else {
    +						$lq1="SELECT lid FROM {$dbprefix}questions WHERE qid=$fqid";
    +						$lr1=db_execute_assoc($lq1);
    +						while($lrow1=$lr1->FetchRow()) {
    +							$flid = $lrow1['lid'];
    +						}
    +						$lq = "SELECT * FROM {$dbprefix}answers WHERE qid=$fqid AND code= '$faid' AND language = '$explang'";
    +						$lr = db_execute_assoc($lq);
    +						while ($lrow=$lr->FetchRow())
    +						{
    +							$lq2 = "SELECT * FROM {$dbprefix}labels WHERE lid=$flid AND code='$fcode' AND language = '$explang'";
    +							$lr2 = db_execute_assoc($lq2);
    +							while ($lrow2=$lr2->FetchRow())
    +							{
    +								$fquest .= " [".$lrow['answer']."] [".$lrow2['title']."]";
    +							}
    +						}
    +					}
    +					break;
    +				case "1": // multi scale Headline
    +					$flid=$fielddata['lid'];
    +					$flid1=$fielddata['lid1'];
    +					if (mb_substr($fieldinfo,-1) == '0')
    +					{ //TIBO
    +						$strlabel = "1";
    +						$lq = "select a.*, l.*, t.label_name as labeltitle from {$dbprefix}answers as a, {$dbprefix}labels as l, {$dbprefix}labelsets as t where a.code='$faid' and qid=$fqid AND l.lid = $flid AND a.language='$surveybaselang'  AND t.lid=$flid";
    +					}
    +					else
    +					{
    +						$strlabel = "2";
    +						$lq = "select a.*, l.*, t.label_name as labeltitle from {$dbprefix}answers as a, {$dbprefix}labels as l, {$dbprefix}labelsets as t where a.code='$faid' and qid=$fqid AND l.lid = $flid1 AND a.language='$surveybaselang'  AND t.lid=$flid1";
    +					}
    +					$lr = db_execute_assoc($lq);
    +					$j=0;
    +					while ($lrow=$lr->FetchRow())
    +					{
    +						$strlabel = $strlabel."-".$lrow['labeltitle'];
    +						$fquest .= " [".FlattenText($lrow['answer'],true)."][".FlattenText($strlabel,true)."]";
    +						$j++;
    +					}
    +					break;
    +
    +			}
    +			$fquest=FlattenText($fquest,true);
    +			if ($type == "csv")
    +			{
    +				$firstline .="\"$fquest\"$separator";
    +			}
    +			else
    +			{
    +				$firstline .= $fquest.$separator;
    +			}
    +		}
    +		if($convertspacetous == "Y")
    +		{
    +			$firstline=str_replace(" ", "_", $firstline);
    +		}
    +	}
    +}
    +if ($type == "csv") { $firstline = mb_substr(trim($firstline),0,strlen($firstline)-1);}
    +else
    +{
    +	$firstline = trim($firstline);
    +}
    +
    +$firstline .= "\n";
    +
    +if ($type == "doc" || $type == "pdf")
    +{
    +	$flarray=explode($separator, $firstline);
    +
    +}
    +else
    +if ($type == "xls")
    +{
    +	//var_dump ($firstline);
    +	$flarray=explode($separator, $firstline);
    +	$fli=0;
    +	foreach ($flarray as $fl)
    +	{
    +		$sheet->write(0,$fli,$fl);
    +		$fli++;
    +	}
    +	//print_r($fieldmap);
    +}
    +else
    +{
    +	$exportoutput .= $firstline; //Sending the header row
    +}
    +
    +
    +//calculate interval because the second argument at SQL "limit"
    +//is the number of records not the ending point
    +$from_record = $exportFrom - 1;
    +$limit_interval = $exportTo - $exportFrom + 1;
    +$attributefieldAndNames=array();
    +
    +//Now dump the data
    +if ($tokenTableExists && $thissurvey['private']=='N')
    +{
    +	$dquery = "SELECT $selectfields";
    +	if (isset($_POST['first_name']) && $_POST['first_name']=="on")
    +	{
    +		$dquery .= ", {$dbprefix}tokens_$surveyid.firstname";
    +	}
    +	if (isset($_POST['last_name']) && $_POST['last_name']=="on")
    +	{
    +		$dquery .= ", {$dbprefix}tokens_$surveyid.lastname";
    +	}
    +	if (isset($_POST['email_address']) && $_POST['email_address']=="on")
    +	{
    +		$dquery .= ", {$dbprefix}tokens_$surveyid.email";
    +	}
    +	if (isset($_POST['token']) && $_POST['token']=="on")
    +	{
    +		$dquery .= ", {$dbprefix}tokens_$surveyid.token";
    +	}
    +    foreach ($attributeFields as $attributefield)
    +	{
    +        if (isset($_POST[$attributefield]) && $_POST[$attributefield]=="on")
    +	{
    +            $dquery .= ", {$dbprefix}tokens_$surveyid.$attributefield";
    +	}
    +    }
    +	$dquery	.= " FROM $surveytable "
    +	. "LEFT OUTER JOIN {$dbprefix}tokens_$surveyid "
    +	. "ON $surveytable.token={$dbprefix}tokens_$surveyid.token ";
    +	if (incompleteAnsFilterstate() == "filter")
    +	{
    +		$dquery .= "  WHERE $surveytable.submitdate is not null ";
    +	} elseif (incompleteAnsFilterstate() == "inc")
    +	{
    +		$dquery .= "  WHERE $surveytable.submitdate is null ";
    +	}
    +}
    +else // this applies for exporting everything
    +{
    +	$dquery = "SELECT $selectfields FROM $surveytable ";
    +
    +	if (incompleteAnsFilterstate() == "filter")
    +	{
    +		$dquery .= "  WHERE $surveytable.submitdate is not null ";
    +	} elseif (incompleteAnsFilterstate() == "inc")
    +	{
    +		$dquery .= "  WHERE $surveytable.submitdate is null ";
    +	}
    +}
    +
    +if (isset($_POST['sql'])) //this applies if export has been called from the statistics package
    +{
    +	if ($_POST['sql'] != "NULL")
    +	{
    +		if (incompleteAnsFilterstate() == "filter" || incompleteAnsFilterstate() == "inc") {$dquery .= " AND ".stripcslashes($_POST['sql'])." ";}
    +		else {$dquery .= "WHERE ".stripcslashes($_POST['sql'])." ";}
    +	}
    +}
    +if (isset($_POST['answerid']) && $_POST['answerid'] != "NULL") //this applies if export has been called from single answer view
    +{
    +	if (incompleteAnsFilterstate() == "filter" || incompleteAnsFilterstate() == "inc") {$dquery .= " AND $surveytable.id=".stripcslashes($_POST['answerid'])." ";}
    +	else {$dquery .= "WHERE $surveytable.id=".stripcslashes($_POST['answerid'])." ";}
    +}
    +
    +
    +$dquery .= "ORDER BY $surveytable.id";
    +if ($answers == "short") //Nice and easy. Just dump the data straight
    +{
    +	//$dresult = db_execute_assoc($dquery);
    +	$dresult = db_select_limit_assoc($dquery, $limit_interval, $from_record);
    +	$rowcounter=0;
    +	while ($drow = $dresult->FetchRow())
    +	{
    +		$drow=array_map('strip_tags_full',$drow);
    +		if($convertyto1 == "Y")
    +		//Converts "Y" to "1" in export
    +		{
    +		  $convertyto=returnglobal('convertyto');
    +			foreach($drow as $key=>$dr) {
    +				$fielddata=arraySearchByKey($key, $fieldmap, "fieldname", 1);
    +            if(isset($fielddata['type']) &&
    +			   ($fielddata['type'] == "M" || 
    +			   $fielddata['type'] == "P" ||
    +			   $fielddata['type'] == "Y")
    +			   )
    +				{
    +		      if($dr == "Y") {$dr = $convertyto;}
    +				}
    +				$line[$key]=$dr;
    +			}
    +			$drow=$line;
    +		}
    +		if($convertnto2 == "Y")
    +		//Converts "N" to "2" in export
    +		{
    +		  $convertnto=returnglobal('convertnto');
    +		  foreach($drow as $key=>$dr) {
    +            $fielddata=arraySearchByKey($key, $fieldmap, "fieldname", 1);
    +            if(isset($fielddata['type']) &&
    +			   ($fielddata['type'] == "M" || 
    +			   $fielddata['type'] == "P" ||
    +			   $fielddata['type'] == "Y")
    +			   )
    +            {
    +		      if($dr == "N") {$dr = $convertnto;}
    +		    }
    +		    $line[$key]=$dr;
    +		  }
    +		  $drow=$line;
    +		}
    +		$rowcounter++;
    +		if ($type == "csv")
    +		{
    +			$exportoutput .= "\"".implode("\"$separator\"", str_replace("\"", "\"\"", str_replace("\r\n", " ", $drow))) . "\"\n"; //create dump from each row
    +		}
    +		elseif ($type == "xls")
    +		{
    +			$colcounter=0;
    +			foreach ($drow as $rowfield)
    +			{
    +				$rowfield=str_replace("?","-",$rowfield);
    +				$sheet->write($rowcounter,$colcounter,$rowfield);
    +				$colcounter++;
    +			}
    +		}
    +		else if($type == "pdf")
    +		{
    +			$pdf->titleintopdf($clang->gT("New Record"));
    +			foreach ($drow as $rowfield)
    +			{
    +				$rowfield=str_replace("?","-",$rowfield);
    +				$pdfstring .=$rowfield." | ";
    +			}
    +			$pdf->intopdf($pdfstring);
    +		}
    +		else
    +		{
    +			$exportoutput .= implode($separator, str_replace("\r\n", " ", $drow)) . "\n"; //create dump from each row
    +		}
    +	}
    +}
    +elseif ($answers == "long")        //chose complete answers
    +{
    +
    +	$labelscache=array();
    +	//$dresult = db_execute_num($dquery) or safe_die("ERROR: $dquery -".$connect->ErrorMsg());
    +	$dresult = db_select_limit_num($dquery, $limit_interval, $from_record);
    +	$fieldcount = $dresult->FieldCount();
    +	$rowcounter=0;
    +
    +	while ($drow = $dresult->FetchRow())
    +	{
    +		$rowcounter++;
    +		if ($type == "pdf")
    +		{
    +			//$pdf->Write (5,$exportoutput);
    +			if($rowcounter != 1)
    +			{
    +				$pdf->AddPage();
    +			}
    +			$pdf->Cell(0,10,$elang->gT('NEW RECORD')." ".$rowcounter,1,1);
    +		}
    +
    +		if ($type == "doc")
    +		{
    +			$exportoutput .= "\n\n\n".$elang->gT('NEW RECORD')."\n";
    +		}
    +		for ($i=0; $i<$fieldcount; $i++) //For each field, work out the QID
    +		{
    +			$fqid=0;            // By default fqid is set to zero
    +			$field=$dresult->FetchField($i);
    +			$fieldinfo=$field->name;
    +            if ($fieldinfo != "startlanguage" && $fieldinfo != "id" && $fieldinfo != "datestamp" && $fieldinfo != "startdate" && $fieldinfo != "ipaddr"  && $fieldinfo != "refurl" && $fieldinfo != "token" && $fieldinfo != "firstname" && $fieldinfo != "lastname" && $fieldinfo != "email" && (substr($fieldinfo,0,10)!="attribute_") && $fieldinfo != "completed")
    +			{
    +				//				$fielddata=arraySearchByKey($fieldinfo, $fieldmap, "fieldname", 1);
    +				$fielddata=$outmap[$fieldinfo];
    +				$fqid=$fielddata['qid'];
    +				$ftype=$fielddata['type'];
    +				$fsid=$fielddata['sid'];
    +				$fgid=$fielddata['gid'];
    +				$faid=$fielddata['aid'];
    +				$flid=$fielddata['lid'];
    +				if (isset($fielddata['lid1'])) {$flid1=$fielddata['lid1'];}
    +
    +				$fother=$fielddata['other'];
    +				if ($type == "doc" || $type == "pdf")
    +				{
    +					$ftitle=$flarray[$i];
    +				}
    +			}
    +			else
    +			{
    +				$fsid=""; $fgid="";
    +				if ($type == "doc" || $type == "pdf")
    +				{
    +					switch($fieldinfo)
    +					{
    +						case "datestamp":
    +							$ftitle=$elang->gT("Date Last Action").":";
    +							break;
    +						case "startdate":
    +							$ftitle=$elang->gT("Date Started").":";
    +							break;
    +						case "ipaddr":
    +							$ftitle=$elang->gT("IP Address").":";
    +							break;
    +						case "completed":
    +							$ftitle=$elang->gT("Completed").":";
    +							break;
    +						case "refurl":
    +							$ftitle=$elang->gT("Referring URL").":";
    +							break;
    +						case "firstname":
    +							$ftitle=$elang->gT("First Name").":";
    +							break;
    +						case "lastname":
    +							$ftitle=$elang->gT("Last Name").":";
    +							break;
    +						case "email":
    +							$ftitle=$elang->gT("Email").":";
    +							break;
    +						case "id":
    +							$ftitle=$elang->gT("ID").":";
    +							break;
    +						case "token":
    +							$ftitle=$elang->gT("Token").":";
    +							break;
    +						case "tid":
    +							$ftitle=$elang->gT("Token ID").":";
    +							break;
    +						case "startlanguage":
    +							$ftitle=$elang->gT("Language").":";
    +							break;
    +						default:
    +                        if (substr($fieldinfo,0,10)=='attribute_')
    +                        {
    +                           $ftitle=$attributeFieldAndNames[$fieldinfo]; 
    +                        }
    +                        else
    +                        {
    +                            $fielddata=$outmap[$fieldinfo];  
    +                            if (isset($fielddata['title']) && !isset($ftitle)) {$ftitle=$fielddata['title'].":";}                             
    +                        }
    +					} // switch
    +				}
    +			}
    +			if ($fqid == 0)
    +			{
    +				$ftype = "-";  //   This is set if it not a normal answer field, but something like tokenID, First Name etc
    +			}
    +			if ($type == "csv") {$exportoutput .= "\"";}
    +			if ($type == "doc") {$exportoutput .= "\n$ftitle\n\t";}
    +			if ($type == "pdf"){ $pdf->intopdf($ftitle);}
    +			switch ($ftype)
    +			{
    +				case "-": //SPECIAL Placeholder TYPE
    +					$exportoutput .= $drow[$i];
    +					if($type == "pdf"){$pdf->intopdf($drow[$i]);}
    +					break;
    +				case "R": //RANKING TYPE
    +					$lq = "SELECT * FROM {$dbprefix}answers WHERE qid=$fqid AND language='$explang' AND code = ?";
    +					$lr = db_execute_assoc($lq, array($drow[$i]));
    +					while ($lrow = $lr->FetchRow())
    +					{
    +						$exportoutput .= strip_tags_full($lrow['answer']);
    +						if($type == "pdf"){$pdf->intopdf(strip_tags_full($lrow['answer']));}
    +					}
    +					break;
    +				case "1":
    +					if (mb_substr($fieldinfo,-1) == 0)
    +					{
    +						$lq = "select a.*, l.*, l.code as lcode, l.title as ltitle from {$dbprefix}answers as a, {$dbprefix}labels as l where qid=$fqid AND l.lid =$flid AND a.language='$explang' AND l.code = ? group by l.lid";
    +					}
    +					else
    +					{
    +						$lq = "select a.*, l.*, l.code as lcode, l.title as ltitle from {$dbprefix}answers as a, {$dbprefix}labels as l where qid=$fqid AND l.lid =$flid1 AND a.language='$explang' AND l.code = ? group by l.lid";
    +					}
    +					$lr = db_execute_assoc($lq, array($drow[$i])) or safe_die($lq."<br />ERROR:<br />".$connect->ErrorMsg());
    +					while ($lrow = $lr->FetchRow())
    +					{
    +						$exportoutput .= strip_tags_full($lrow['ltitle']);
    +						if($type == "pdf"){$pdf->intopdf(strip_tags_full($lrow['ltitle']));}
    +					}
    +					break;
    +				case "L": //DROPDOWN LIST
    +				case "!":
    +					if (mb_substr($fieldinfo, -5, 5) == "other")
    +					{
    +						$exportoutput .= strip_tags_full($drow[$i]);
    +						if($type == "pdf"){$pdf->intopdf($drow[$i]);}
    +					}
    +					else
    +					{
    +						if ($drow[$i] == "-oth-")
    +						{
    +							$exportoutput .= $elang->gT("Other");
    +							if($type == "pdf"){$pdf->intopdf($elang->gT("Other"));}
    +						}
    +						else
    +						{
    +							$lq = "SELECT * FROM {$dbprefix}answers WHERE qid=$fqid AND language='$explang' AND code = ?";
    +							$lr = db_execute_assoc($lq, array($drow[$i])) or safe_die($lq."<br />ERROR:<br />".$connect->ErrorMsg());
    +							while ($lrow = $lr->FetchRow())
    +							{
    +								//if ($lrow['code'] == $drow[$i]) {$exportoutput .= $lrow['answer'];}
    +								if ($type == "csv")
    +								{
    +									$exportoutput .= str_replace("\"", "\"\"", strip_tags_full($lrow['answer']));
    +									if($type == "pdf"){$pdf->intopdf(str_replace("\"", "\"\"", strip_tags_full($lrow['answer'])));}
    +								}
    +								else
    +								{
    +									$exportoutput .= strip_tags_full($lrow['answer']);
    +									if($type == "pdf"){$pdf->intopdf(strip_tags_full($lrow['answer']));}
    +								}
    +
    +							}
    +						}
    +					}
    +					break;
    +				case "W":
    +				case "Z":
    +					if (mb_substr($fieldinfo, -5, 5) == "other")
    +					{
    +						$exportoutput .= strip_tags_full($drow[$i]);
    +						if($type == "pdf"){$pdf->intopdf($drow[$i]);}
    +					}
    +					else
    +					{
    +						if ($drow[$i] == "-oth-")
    +						{
    +							$exportoutput .= $elang->gT("Other");
    +							if($type == "pdf"){$pdf->intopdf($elang->gT("Other"));}
    +						}
    +						else
    +						{
    +							$fquery = "SELECT * FROM {$dbprefix}labels WHERE lid=$flid AND language='$explang' AND code='$drow[$i]'";
    +							$fresult = db_execute_assoc($fquery) or safe_die("ERROR:".$fquery."<br />".$qq."<br />".$connect->ErrorMsg());
    +							while ($frow = $fresult->FetchRow())
    +							{
    +								$exportoutput .= strip_tags_full($frow['title']);
    +								if($type == "pdf"){$pdf->intopdf($frow['title']);}
    +							}
    +						}
    +					}
    +					break;
    +				case "O": //DROPDOWN LIST WITH COMMENT
    +					$lq = "SELECT * FROM {$dbprefix}answers WHERE qid=$fqid AND language='$explang' ORDER BY answer";
    +					$lr = db_execute_assoc($lq) or safe_die ("Could do it<br />$lq<br />".$connect->ErrorMsg());
    +					$found = "";
    +					while ($lrow = $lr->FetchRow())
    +					{
    +						if ($lrow['code'] == $drow[$i])
    +						{
    +							$exportoutput .= strip_tags_full($lrow['answer']);
    +							$found = "Y";
    +							if($type == "pdf"){$pdf->intopdf(strip_tags_full($lrow['answer']));}
    +						}
    +					}
    +					//This following section exports the comment field
    +					if ($found != "Y")
    +					{
    +						if ($type == "csv")
    +						{$exportoutput .= str_replace("\r\n", "\n", str_replace("\"", "\"\"", strip_tags_full($drow[$i])));}
    +						else if ($type == "pdf")
    +						{$pdf->intopdf(str_replace("\r\n", " ", strip_tags_full($drow[$i])));}
    +						else
    +						{$exportoutput .= str_replace("\r\n", " ", $drow[$i]);}
    +					}
    +					break;
    +				case "Y": //YES\NO
    +					switch($drow[$i])
    +					{
    +						case "Y":
    +							$exportoutput .= $elang->gT("Yes");
    +							if($type == "pdf"){$pdf->intopdf($elang->gT("Yes"));}
    +							break;
    +						case "N":
    +							$exportoutput .= $elang->gT("No");
    +							if($type == "pdf"){$pdf->intopdf($elang->gT("No"));}
    +							break;
    +						default:
    +							$exportoutput .= $elang->gT("N/A");
    +							if($type == "pdf"){$pdf->intopdf($elang->gT("N/A"));}
    +							break;
    +					}
    +					break;
    +				case "G": //GENDER
    +					switch($drow[$i])
    +					{
    +						case "M":
    +							$exportoutput .= $elang->gT("Male");
    +							if($type == "pdf"){$pdf->intopdf($elang->gT("Male"));}
    +							break;
    +						case "F":
    +							$exportoutput .= $elang->gT("Female");
    +							if($type == "pdf"){$pdf->intopdf($elang->gT("Female"));}
    +							break;
    +						default:
    +							$exportoutput .= $elang->gT("N/A");
    +							if($type == "pdf"){$pdf->intopdf($elang->gT("N/A"));}
    +							break;
    +					}
    +					break;
    +				case "M": //multioption
    +				case "P":
    +					if (mb_substr($fieldinfo, -5, 5) == "other")
    +					{
    +						$exportoutput .= strip_tags_full($drow[$i]);
    +						if($type == "pdf"){$pdf->intopdf($drow[$i]);}
    +					}
    +					elseif (mb_substr($fieldinfo, -7, 7) == "comment")
    +					{
    +						$exportoutput .= strip_tags_full($drow[$i]);
    +						if($type == "pdf"){$pdf->intopdf($drow[$i]);}
    +					}
    +					else
    +					{
    +						switch($drow[$i])
    +						{
    +							case "Y":
    +								$exportoutput .= $elang->gT("Yes");
    +								if($type == "pdf"){$pdf->intopdf($elang->gT("Yes"));}
    +								break;
    +							case "N":
    +								$exportoutput .= $elang->gT("No");
    +								if($type == "pdf"){$pdf->intopdf($elang->gT("No"));}
    +								break;
    +							case "":
    +								$exportoutput .= $elang->gT("No");
    +								if($type == "pdf"){$pdf->intopdf($elang->gT("No"));}
    +								break;
    +							default:
    +								$exportoutput .= $drow[$i];
    +								if($type == "pdf"){$pdf->intopdf($drow[$i]);}
    +								break;
    +						}
    +					}
    +					break;
    +				case "C":
    +					switch($drow[$i])
    +					{
    +						case "Y":
    +							$exportoutput .= $elang->gT("Yes");
    +							if($type == "pdf"){$pdf->intopdf($elang->gT("Yes")); }
    +							break;
    +						case "N":
    +							$exportoutput .= $elang->gT("No");
    +							if($type == "pdf"){$pdf->intopdf($elang->gT("No")); }
    +							break;
    +						case "U":
    +							$exportoutput .= $elang->gT("Uncertain");
    +							if($type == "pdf"){$pdf->intopdf($elang->gT("Uncertain"));}
    +							break;
    +					}
    +				case "E":
    +					switch($drow[$i])
    +					{
    +						case "I":
    +							$exportoutput .= $elang->gT("Increase");
    +							if($type == "pdf"){$pdf->intopdf($elang->gT("Increase"));}
    +							break;
    +						case "S":
    +							$exportoutput .= $elang->gT("Same");
    +							if($type == "pdf"){$pdf->intopdf($elang->gT("Same"));}
    +							break;
    +						case "D":
    +							$exportoutput .= $elang->gT("Decrease");
    +							if($type == "pdf"){$pdf->intopdf($elang->gT("Decrease"));}
    +							break;
    +					}
    +					break;
    +				case "F":
    +				case "H":
    +					if (!isset($labelscache[$flid.'|'.$explang.'|'.$drow[$i]]))
    +					{
    +						$fquery = "SELECT * FROM {$dbprefix}labels WHERE lid=$flid AND language='$explang' AND code='$drow[$i]'";
    +						$fresult = db_execute_assoc($fquery) or safe_die("ERROR:".$fquery."\n".$qq."\n".$connect->ErrorMsg());
    +						if ($fresult)
    +						{
    +							$frow=$fresult->FetchRow();
    +							if($type == "pdf"){$pdf->intopdf(strip_tags_full($frow['title']));}
    +							$exportoutput .= strip_tags_full($frow['title']);
    +							$labelscache[$flid.'|'.$explang.'|'.$drow[$i]]=strip_tags_full($frow['title']);
    +						}
    +					}
    +					else
    +					{
    +						$exportoutput .=$labelscache[$flid.'|'.$explang.'|'.$drow[$i]];
    +						if($type == "pdf"){$pdf->intopdf($labelscache[$flid.'|'.$explang.'|'.$drow[$i]]);}
    +					}
    +					break;
    +				case "1": //dual scale
    +					$flid=$fielddata['lid'];
    +					$flid1=$fielddata['lid1'];
    +					if (mb_substr($fieldinfo,-1) == '0')
    +					{
    +						$strlabel = "1";
    +						$lq = "select title from {$dbprefix}labels as l where l.lid = $flid AND l.language='$surveybaselang'";
    +					}
    +					else
    +					{
    +						$strlabel = "2";
    +						$lq = "select title from {$dbprefix}labels as l where l.lid = $flid1 AND l.language='$surveybaselang'";
    +					}
    +					$lr = db_execute_assoc($lq);
    +					while ($lrow=$lr->FetchRow())
    +					{
    +						$fquest .= " [".strip_tags_full($lrow['title'])."][".strip_tags_full($strlabel).". label]";
    +					}
    +
    +					break;
    +
    +				default: $tempresult=$dresult->FetchField($i);
    +				if ($tempresult->name == "token")
    +				{
    +					$tokenquery = "SELECT firstname, lastname FROM {$dbprefix}tokens_$surveyid WHERE token='$drow[$i]'";
    +					if ($tokenresult = db_execute_assoc($tokenquery)) //or safe_die ("Couldn't get token info<br />$tokenquery<br />".$connect->ErrorMsg());
    +					while ($tokenrow=$tokenresult->FetchRow())
    +					{
    +						$exportoutput .= "{$tokenrow['lastname']}, {$tokenrow['firstname']}";
    +						if($type == "pdf"){$pdf->intopdf($tokenrow['lastname']." , ".$tokenrow['firstname']);}
    +					}
    +					else
    +					{
    +						$exportoutput .= $elang->gT("Tokens problem - token table missing");
    +						if($type == "pdf"){$pdf->intopdf($elang->gT("Tokens problem - token table missing"));}
    +					}
    +				}
    +				else
    +				{
    +					if ($type == "csv")
    +					{$exportoutput .= str_replace("\r\n", "\n", str_replace("\"", "\"\"", strip_tags_full($drow[$i])));}
    +					else if ($type == "pdf")
    +					{$pdf->intopdf(str_replace("\r\n", " ", strip_tags_full($drow[$i])));}
    +					else
    +					{$exportoutput .= str_replace("\r\n", " ", $drow[$i]);}
    +				}
    +			}
    +			if ($type == "csv") {$exportoutput .= "\"";}
    +			$exportoutput .= "$separator";
    +			$ftype = "";
    +		}
    +		$exportoutput=mb_substr($exportoutput,0,-(strlen($separator)));
    +		IF ($type=='xls')
    +		{
    +			$rowarray=explode($separator, $exportoutput);
    +			$fli=0;
    +			foreach ($rowarray as $row)
    +			{
    +				$sheet->write($rowcounter,$fli,$row);
    +				$fli++;
    +			}
    +			$exportoutput='';
    +		}
    +		else {$exportoutput .= "\n";}
    +	}
    +}
    +	if ($type=='xls')
    +	{
    +		$workbook->close();
    +	}
    +	else if($type=='pdf')
    +	{
    +		$pdf->Output($clang->gT($surveyname)." ".$surveyid.".pdf","D");
    +	}
    +	else
    +	{
    +		echo $exportoutput;
    +	}
    +
    +        function strip_tags_full($string) {
    +		$string=html_entity_decode($string, ENT_QUOTES, "UTF-8");
    +		mb_regex_encoding('utf-8');
    +		$pattern = array('\r', '\n', '-oth-');
    +		for ($i=0; $i<sizeof($pattern); $i++) {
    +			$string = mb_ereg_replace($pattern[$i], '', $string);
    +		}
    +		return strip_tags($string);
    +	}
    +?>
    Index: admin/exportresults_lsrc.php
    ===================================================================
    --- admin/exportresults_lsrc.php	(revision 0)
    +++ admin/exportresults_lsrc.php	(revision 0)
    @@ -0,0 +1,53 @@
    +<?php
    +/*
    + * LimeSurvey
    + * Copyright (C) 2007 The LimeSurvey Project Team / Carsten Schmitz
    + * All rights reserved.
    + * License: GNU/GPL License v2 or later, see LICENSE.php
    + * LimeSurvey is free software. This version may have been modified pursuant
    + * to the GNU General Public License, and as distributed it includes or
    + * is derivative of works licensed under the GNU General Public License or
    + * other free or open source software licenses.
    + * See COPYRIGHT.php for copyright notices and details.
    + *
    + * $Id: exportresults.php 7487 2009-08-18 22:58:16Z c_schmitz $
    + */
    +
    +
    +//Ensure script is not run directly, avoid path disclosure
    +include_once("login_check.php");
    +
    +
    +if (!isset($imagefiles)) {$imagefiles="./images";}
    +if (!isset($surveyid)) {$surveyid=returnglobal('sid');}
    +if (!isset($exportstyle)) {$exportstyle=returnglobal('exportstyle');}
    +if (!isset($answers)) {$answers=returnglobal('answers');}
    +if (!isset($type)) {$type=returnglobal('type');}
    +if (!isset($convertyto1)) {$convertyto1=returnglobal('convertyto1');}
    +if (!isset($convertnto2)) {$convertnto2=returnglobal('convertnto2');}
    +if (!isset($convertspacetous)) {$convertspacetous=returnglobal('convertspacetous');}
    +if (!isset($exportFrom)) {$exportFrom=sanitize_int(returnglobal('export_from'));}
    +if (!isset($exportTo)) {$exportTo=sanitize_int(returnglobal('export_to'));} 
    +
    +$sumquery5 = "SELECT b.* FROM {$dbprefix}surveys AS a INNER JOIN {$dbprefix}surveys_rights AS b ON a.sid = b.sid WHERE a.sid=$surveyid AND b.uid = ".$_SESSION['loginID']; //Getting rights for this survey and user
    +$sumresult5 = db_execute_assoc($sumquery5);
    +$sumrows5 = $sumresult5->FetchRow();
    +
    +if ($sumrows5['export'] != "1" && $_SESSION['USER_RIGHT_SUPERADMIN'] != 1)
    +{
    +	exit;
    +}
    +
    +include_once("login_check.php");
    +include_once(dirname(__FILE__)."/classes/pear/Spreadsheet/Excel/Writer.php");
    +include_once(dirname(__FILE__)."/classes/tcpdf/extensiontcpdf.php");
    +
    +$surveybaselang=GetBaseLanguageFromSurveyID($surveyid);
    +$exportoutput="";
    +
    +// Get info about the survey
    +$thissurvey=getSurveyInfo($surveyid);
    +
    +require_once("exportresults_common.php");
    +
    +?>
    Index: admin/remotecontrol/lsrc_orig.wsdl
    ===================================================================
    --- admin/remotecontrol/lsrc_orig.wsdl	(revision 8411)
    +++ admin/remotecontrol/lsrc_orig.wsdl	(working copy)
    @@ -296,6 +296,21 @@
       <message name="sGetFieldmapFault">
       	<part name="fault" element="xsd:string"></part>
       </message>
    +  <message name="sGetResultsRequest">
    +        <part name="sUser" type="xsd:string"></part>
    +        <part name="sPass" type="xsd:string"></part>
    +      	<part name="iVid" type="xsd:int"></part>
    +	<part name="sFilter" type="xsd:string"></part>
    +	<part name="sFormat" type="xsd:string"></part>
    +	<part name="iFromRecord" type="xsd:int"></part>
    +	<part name="iToRecord" type="xsd:int"></part>
    +  </message>
    +  <message name="sGetResultsResponse">
    +	<part name="return" type="xsd:string"></part>
    +  </message>
    +  <message name="sGetResultsFault">
    +	<part name="fault" element="xsd:string"></part>
    +  </message>
       <message name="fSendStatisticRequest">
       	<part name="sUser" type="xsd:string"></part>
       	<part name="sPass" type="xsd:string"></part>
    @@ -385,6 +400,11 @@
         	<output message="tns:sGetFieldmapResponse" name="sGetFieldmapResponse"></output>
                 <fault name="sGetFieldmapFault" message="tns:sGetFieldmapFault"></fault>
             </operation>
    +    <operation name="sGetResults">
    +	<input message="sGetResultsRequest" name="sGetResultsRequest"></input>
    +	<output message="sGetResultsResponse" name="sGetResultsResponse"></output>
    +	    <fault name="sGetResultsFault" message="tns:sGetResultsFault"></fault>
    +    </operation>
         <operation name="fSendStatistic">
         	<input message="tns:fSendStatisticRequest" name="fSendStatisticRequest"></input>
         	<output message="tns:fSendStatisticResponse" name="fSendStatisticResponse"></output>
    @@ -416,7 +436,21 @@
       				name="sGetFieldmapFault" />
       		</fault>
       	</operation>
    -
    +        <operation name="sGetResults">
    +	        <soap:operation soapAction="urn:lsrcNamespaceAction" stype="rpc" />
    +	        <input name="sGetResultsRequest">
    +	                <soap:body namespace="urn:lsrcNamespace" 
    +		                encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
    +	        </input>
    +	        <output name="sGetResultsResponse">
    +	                <soap:body namespace="urn:lsrcNamespace" 
    +		                encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
    +	        </output>
    +	        <fault name="sGetResultsFault">
    +	                <soap:fault name="sGetResultsFault" namespace="urn:lsrcNamespace" 
    +		                encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
    +	        </fault>
    +        </operation>
       	<operation name="sSendEmail">
     
       		<soap:operation soapAction="urn:lsrcNamespace/sSendEmail" />
    @@ -728,4 +762,4 @@
        </port>
       </service>
     
    -</definitions>
    \ No newline at end of file
    +</definitions>
    Index: admin/remotecontrol/lsrc.config.php
    ===================================================================
    --- admin/remotecontrol/lsrc.config.php	(revision 8411)
    +++ admin/remotecontrol/lsrc.config.php	(working copy)
    @@ -19,7 +19,8 @@
     // only include if this config is not used to save a survey.csv for the lsrc
     if(!isset($export4lsrc))
     {
    -	include_once("../../config-defaults.php");
    +	include("../../config-defaults.php");
    +	include("../../config.php");
     	require_once(dirname(__FILE__).'/../../common.php');
     }
     ### Error Handling
    @@ -75,4 +76,4 @@
     $sDatasetSeperator = "::"; //default: "::"
     $sDatafieldSeperator = ";"; //default: ";"
     
    -?>
    \ No newline at end of file
    +?>
    Index: admin/remotecontrol/lsrc.server.php
    ===================================================================
    --- admin/remotecontrol/lsrc.server.php	(revision 8411)
    +++ admin/remotecontrol/lsrc.server.php	(working copy)
    @@ -95,6 +95,7 @@
     $server->addFunction("sSendEmail");
     $server->addFunction("sGetFieldmap");
     $server->addFunction("fSendStatistic");
    +$server->addFunction("sGetResults");
     // handle the soap request!
     if($enableLsrc===true)
     {
    @@ -1206,4 +1207,52 @@
     
     }
     
    -?>
    \ No newline at end of file
    +function sGetResults($sUser, $sPass, $iVid, $sFilter = 'show', $sFormat = 'csv', $iFromRecord = 1, $iToRecord = 500) 
    +{
    +	require('lsrc.config.php');
    +	$lsrcHelper = new lsrcHelper();
    +
    +	if(!$lsrcHelper->checkUser($sUser, $sPass))
    +	{
    +		throw new SoapFault("Authentication: ", "User or password wrong");
    +		exit;
    +	}
    +	if($lsrcHelper->getSurveyOwner($iVid)!=$_SESSION['loginID'] && !$_SESSION['USER_RIGHT_SUPERADMIN']=='1')
    +	{
    +		throw new SoapFault("Authentication: ", "You have no right to get results from other people's surveys");
    +		exit;
    +	}
    +	if(!$lsrcHelper->surveyExists($iVid))
    +	{
    +		throw new SoapFault("Database: ", "Survey $iVid does not exist");
    +		exit;
    +	}
    +
    +	//This has only been tested with CSV output, although it could theoretically be used to 
    +	//generate any form of output the exportresults.php page can generate.  For now this is
    +	//being limited to csv format. -- Dave Wolff
    +	if($sFormat != 'csv')
    +	{
    +		throw new SoapFault("Format: ", "At this time only 'csv' format is supported'.");
    +		exit;
    +	}
    +
    +	$_REQUEST['filterinc'] = $sFilter;
    +	$surveyid = $iVid;
    +	$exportstyle = 'headcodes';
    +	$answers = 'short';
    +	$type = $sFormat;
    +	$convertyto1 = 'N';
    +	$convertnto2 = 'N';
    +	$convertspacetous = 'N';
    +	$exportFrom = $iFromRecord;
    +	$exportTo = $iToRecord;
    +
    +	ob_start();
    +	require_once('../exportresults_lsrc.php');
    +	$returnCSV = "".ob_get_contents();
    +	ob_end_clean();
    +	return $returnCSV;
    +}
    +
    +?>
    
    diff file icon getResults3.diff (80,505 bytes) 2010-02-18 17:06 +

-Relationships
+Relationships

-Notes

~10423

elameno (reporter)

Hello rakete. I've taken some time to get to know some of the code and I've written a web service call that taps into the spss_export_data routine which works well; however, looking at what you've posted up above as the possible function call it seems you were thinking of tapping into the exportresults.php file? It looks like exportresults.php has a lot of features that would be helpful with the web service export so I'd like to use that code if possible (without duplication).

I've been having trouble running and capturing results from the exportresults.php and figured I'd ask you what your approach would be before banging my head against too many walls here :)

~10425

Mazi (developer)

Tim, can you take care of this so we can create a nice patch which will be included at the core later on?

~10517

elameno (reporter)

I've updated my 1.86 release to include a web service call that has the following signature: sGetResults($sUser, $sPass, $iVid, $sFilter, $sFormat, $iFromRecord, $iToRecord)

I ended up using a good portion of exportresults.php and have taken the common code and put it in a exportresults_guts.php file, then included the guts in both the exportresults.php and the exportresults_lsrc.php so there isn't any duplication of all that export logic. The way I have it set up, exportresults.php is mostly just the UI layout and logic to get the information to the "guts".

I'd be happy to put together a patch so you can see what I've done, but it looks like there's active development going on in the trunk on the exportresults.php file that has caused some issues. Should I create a patch from the 1.85 release branch? At the worst I could include a zip of the files that I've edited (there aren't many). Let me know what you prefer.

Thanks!

~10725

elameno (reporter)

Well, I haven't heard anything so for now I've uploaded a zip containing all the files I've modified from the 1.86 release to get what I have working. I'm sure it needs to tweaking as far as checking input parameters and whatnot, but I wanted to get a copy of what I've been doing out to you guys. Once again, if you'd like a patch let me know where I should patch from.

I'd really like to hear from a developer on changes that should be made or better approaches than the one I've taken.

To get this working, all that needs to be done is to copy the contents of the zip into the root of a 1.86 lime install with the LSRC enabled. It will overwrite a few files and add a couple new ones.

~10726

Mazi (developer)

Thanks for your feedback! The developer who has created LSRC is very busy at the moment. Your improvements won't get lost, it just takes sometime at open source projects.

~10727

user372

@ elameno: better than adding the whole files (against v1.86) would be if you could provide a SVN diff-patch against the latest version (=v1.87+) - Thx!

~10829

elameno (reporter)

Okay...I've made the changes from the http://limesurvey.svn.sourceforge.net/svnroot/limesurvey/source/limesurvey repo and have uploaded the diff.

I haven't been able to do extensive testing against this, but I think it will get you the majority of the way there (if not all the way).

~11118

elameno (reporter)

I had a bug with a mismatch on the column headers and fields that were being returned by the sGetResults web service call. I've fixed that and the patch is in getResults_ColumnFix.diff.

~11131

elameno (reporter)

Well, I found yet another problem with my 1.87 patch. I had forgotten to import some changes from that 1.86 fix I had put together. The prior patches will disregard the fromRecord and toRecord inputs. I've verified that the patch I'm sending in now works with the export page from the UI and the web service calls. The new file is getResults3.diff. My fingers are crossed that this will give you a good idea of what I'm trying to accomplish. Any suggestions are welcome.


The behavior for the sGetResults web service call is that it will return the header line on every call and, if there are results to return within the to and from range, it will tack on the results. This way you can tell if you've reached the end of the results by checking if there are lines after the header.

The changes to the exportresults.php and the new files are described as follows:
- exportresults.php is now just the mark-up to generate the web interface.
- exportresults_common.php is the routines that create the output for the export.
- exportresults_lsrc.php is a file that the lsrc.server.php sGetResults function calls into to do some additional setup (I suppose this could be moved into lsrc.helper.php?)

All other changes are relatively minor (web service plumbing and whatnot).

~11359

c_schmitz (administrator)

Elameno, that is a great patch. Would you be interested to join the LimeSurvey team and get direct SVN access? That way we could get your feature into Ls 1.90, too.

Let me know!

~11507

elameno (reporter)

Hello c_schmitz,
   I would be happy to lend a hand and get this patch in place for a future release. This work has been done as a part of my work hours at the University and, just as an FYI, I don't think that I will have much time to offer outside of the features that we need here. If you're comfortable with that then sign me up :)

Thanks!
Dave

~13075

c_schmitz (administrator)

Please set to resolved when implemented. Thank you!

~13917

elameno (reporter)

- The core of the export results logic was reimplemented and an sGetResults feature was added to the Lime Survey Remote Control. CSV exporting is now supported via LSRC.
+Notes

Issue Community Support
This issue is already marked as resolved.
If you feel that is not the case, please reopen it and explain why.
Supporters: No one explicitly supports this issue yet.
Opponents: No one explicitly opposes this issue yet.

-Issue History
Date Modified Username Field Change
2009-09-04 14:53 rakete New Issue
2009-09-04 14:56 rakete Description Updated
2009-12-03 17:18 elameno Note Added: 10423
2009-12-03 17:59 Mazi Note Added: 10425
2009-12-03 17:59 Mazi Status new => feedback
2009-12-08 15:43 elameno Note Added: 10517
2009-12-08 17:14 Mazi Status feedback => assigned
2009-12-08 17:14 Mazi Assigned To => rakete
2010-01-06 19:18 elameno File Added: admin.zip
2010-01-06 19:22 elameno Note Added: 10725
2010-01-06 21:13 Mazi Note Added: 10726
2010-01-07 08:00 user372 Note Added: 10727
2010-01-20 18:31 elameno File Added: getResults.diff
2010-01-20 18:33 elameno Note Added: 10829
2010-02-17 16:38 elameno File Added: getResults_ColumnFix.diff
2010-02-17 16:39 elameno Note Added: 11118
2010-02-18 17:06 elameno Note Added: 11131
2010-02-18 17:06 elameno File Added: getResults3.diff
2010-03-13 16:13 c_schmitz Status assigned => acknowledged
2010-03-15 17:41 c_schmitz File Deleted: admin.zip
2010-03-15 17:41 c_schmitz File Deleted: getResults.diff
2010-03-15 17:41 c_schmitz File Deleted: getResults_ColumnFix.diff
2010-03-15 17:43 c_schmitz Note Added: 11359
2010-03-15 17:43 c_schmitz Assigned To rakete => c_schmitz
2010-03-15 17:43 c_schmitz Status acknowledged => feedback
2010-03-25 15:29 elameno Note Added: 11507
2010-04-27 02:26 c_schmitz Assigned To c_schmitz => rakete
2010-04-27 02:26 c_schmitz Status feedback => assigned
2010-10-11 17:44 c_schmitz Assigned To rakete => elameno
2010-10-11 17:45 c_schmitz Note Added: 13075
2011-01-14 17:01 elameno Note Added: 13917
2011-01-14 17:01 elameno Status assigned => resolved
2011-01-14 17:01 elameno Fixed in Version => 1.91
2011-01-14 17:01 elameno Resolution open => fixed
2012-06-21 13:23 c_schmitz Status resolved => closed
+Issue History