load Session / survey results by 3rd party php script

More
2 years 11 months ago #115697 by dwehrmann
dwehrmann created the topic: load Session / survey results by 3rd party php script
Hi,

sorry for the double post. I realized my question belongs here instead of the "can I do this..." section.

What I'm trying to do is to load the results of a survey session into an external php file (on the same server) in order to create a PDF using mPDF. For various reasons my surveys can't use tokens.

I have created a button in completed.pstpl that links to a new php file (print2pdf.php)

contents of print2pdf.php:
<?php
include('mpdf/mpdf.php');
$results =  file_get_contents('http://localhost/cootb/limesurvey/index.php/printanswers/view/surveyid/976474');
$mpdf=new mPDF();
$mpdf->WriteHTML($results);
$mpdf->Output();
exit;
?>

I am basically trying to turn the printanswers view into a PDF. The mpdf part works, however, the pdf created simply has the session timeout error on it.

I guess somehow I need to transfer the session somehow to the php script – I have tried appending the cookie values for SESSID to the url but that didn't help.

Any tips would be greatly appreciated.
Thanks
Dennis

Please Log in to join the conversation.

More
2 years 11 months ago #115698 by Mazi
Mazi replied the topic: load Session / survey results by 3rd party php script
To my knowledge the session gets destroyed after the "print answers" overview screen was created.


Best regards/Beste Grüße,
Dr. Marcel Minke
(Limesurvey Head of Support)
Need Help? We offer professional Limesurvey support
Contact: marcel.minke(at)survey-consulting.com'"

Please Log in to join the conversation.

More
2 years 11 months ago #115705 by dwehrmann
dwehrmann replied the topic: load Session / survey results by 3rd party php script
Hi Mazi,

Thanks for getting back to me. Are there any other ways of getting a clean pdf out of the survey answers? I have tried using the built-in pdf creation button but the results were not as hoped. Apart from the "design" aspect there were a lot of answer codes also printed into the pdf.

I have created a text message that sums up all the answers and can easily access them via the EM but I have a hard time putting all this into a PDF. Are there any alternative ways you can think of?

Thanks
Dennis

Please Log in to join the conversation.

More
2 years 11 months ago #115706 by Mazi
Mazi replied the topic: load Session / survey results by 3rd party php script
Why not using some HTML/JS to put a "print overview" link to the HTML page. That link can call the browsers print option using JS.
Most browsers support direct PDF printing.


Best regards/Beste Grüße,
Dr. Marcel Minke
(Limesurvey Head of Support)
Need Help? We offer professional Limesurvey support
Contact: marcel.minke(at)survey-consulting.com'"

Please Log in to join the conversation.

More
2 years 11 months ago #115715 by DenisChenu
DenisChenu replied the topic: load Session / survey results by 3rd party php script
And if you want alternative system for PDF print : i think it's best to use a plugin.

Assistance on LimeSurvey forum and LimeSurvey core development are on my free time.
I'm not a LimeSurvey GmbH member, professional service on demand (or search sondages pro).
An error happen ? Before make a new topic : remind the Debug mode .

Please Log in to join the conversation.

More
2 years 11 months ago #115730 by dwehrmann
dwehrmann replied the topic: load Session / survey results by 3rd party php script
Thanks for the tip, Denis. PDF notify sounds just like what I need, but the developers site seems to be down ... I guess I'll have to keep looking.

Please Log in to join the conversation.

More
2 years 11 months ago #115731 by dwehrmann
dwehrmann replied the topic: load Session / survey results by 3rd party php script
Can anybody of you put me into contact with the developer of the plugin "pdf notify"? The site lime-support.com/ seems to be down.

Thanks!
Dennis

Please Log in to join the conversation.

More
2 years 11 months ago #115737 by DenisChenu
DenisChenu replied the topic: load Session / survey results by 3rd party php script
Hi,

I don't think using existing plugin , but do own plugin ;).
Take a look at plugins/Demo/showResponse plugin.

Denis

Assistance on LimeSurvey forum and LimeSurvey core development are on my free time.
I'm not a LimeSurvey GmbH member, professional service on demand (or search sondages pro).
An error happen ? Before make a new topic : remind the Debug mode .

Please Log in to join the conversation.

More
2 years 5 months ago #121590 by DWS
DWS replied the topic: load Session / survey results by 3rd party php script
Hi, I'm trying to do some similar but can't find this Demo plugin

Please Log in to join the conversation.

More
2 years 5 months ago #121592 by Ben_V
Ben_V replied the topic: load Session / survey results by 3rd party php script
Hi,
download the last software version and search into folders
/plugins/Demo/ShowResponse

=> Plugin related old post

Benoît

EM Variables => bit.ly/1TKQyNu | EM Roadmap => bit.ly/1UTrOB4
Last Releases => 2.6x.x goo.gl/ztWfIV | 2.06/2.6.x => bit.ly/1Qv44A1
Demo Surveys => goo.gl/HuR6Xe (already included in /docs/demosurveys)

Please Log in to join the conversation.

More
2 years 4 months ago #122254 by DWS
DWS replied the topic: load Session / survey results by 3rd party php script
Somedays after... but thanks Ben_V

Please Log in to join the conversation.

More
2 years 4 months ago - 2 years 4 months ago #122256 by DWS
DWS replied the topic: load Session / survey results by 3rd party php script
Hello,

here you can find my customized (hacked) application\controllers\PrintanswersController.php (Version 2.05+ Build 150520)


Line 33: added var $idtoprint (this is the response id to print, you can pass it by url, for example)
Lines 75-89: pass the session validation if $idtoprint > 0
Line 177: give the value to $sSRID if $idtoprint is present




I hope that this code will be usefull for you and that if anyone from the Limesurvey Team can add as or plugin or something similar.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    /*
    * LimeSurvey
    * Copyright (C) 2007-2011 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.
    *
    */
 
    /**
    * printanswers
    *
    * @package LimeSurvey
    * @copyright 2011
    * @access public
    */
    class PrintanswersController extends LSYii_Controller {
 
 
 
        /**
        * printanswers::view()
        * View answers at the end of a survey in one place. To export as pdf, set 'usepdfexport' = 1 in lsconfig.php and $printableexport='pdf'.
        * @param mixed $surveyid
        * @param bool $printableexport
        * @return
        */
        function actionView($surveyid,$printableexport=FALSE, $idtoprint)
        {
            Yii::app()->loadHelper("frontend");
            Yii::import('application.libraries.admin.pdf');
 
            $iSurveyID = (int)$surveyid;
            $sExportType = $printableexport;
 
            Yii::app()->loadHelper('database');
 
            if (isset($_SESSION['survey_'.$iSurveyID]['sid']))
            {
                $iSurveyID = $_SESSION['survey_'.$iSurveyID]['sid'];
            }
            else
            {
                //die('Invalid survey/session');
            }
            // Get the survey inforamtion
            // Set the language for dispay
            if (isset($_SESSION['survey_'.$iSurveyID]['s_lang']))
            {
                $sLanguage = $_SESSION['survey_'.$iSurveyID]['s_lang'];
            }
            elseif(Survey::model()->findByPk($iSurveyID))// survey exist
            {
                $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
            }
            else
            {
                $iSurveyID=0;
                $sLanguage = Yii::app()->getConfig("defaultlang");
            }
            $clang = SetSurveyLanguage($iSurveyID, $sLanguage);
            $aSurveyInfo = getSurveyInfo($iSurveyID,$sLanguage);
            //SET THE TEMPLATE DIRECTORY
            if (!isset($aSurveyInfo['templatedir']) || !$aSurveyInfo['templatedir'])
            {
                $aSurveyInfo['templatedir']=Yii::app()->getConfig('defaulttemplate');
            }
            $sTemplate = validateTemplateDir($aSurveyInfo['templatedir']);
            //Survey is not finished or don't exist
            if($idtoprint ==0) { if (!isset($_SESSION['survey_'.$iSurveyID]['finished']) || !isset($_SESSION['survey_'.$iSurveyID]['srid']))
            //display "sorry but your session has expired"
            {
                sendCacheHeaders();
                doHeader();
                echo templatereplace(file_get_contents(getTemplatePath($sTemplate).'/startpage.pstpl'),array());
                echo "<center><br />\n"
                ."\t<font color='RED'><strong>".$clang->gT("Error")."</strong></font><br />\n"
                ."\t".$clang->gT("We are sorry but your session has expired.")."<br />".$clang->gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection.")."<br />\n"
                ."\t".sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), Yii::app()->getConfig("siteadminname"), Yii::app()->getConfig("siteadminemail"))."\n"
                ."</center><br />\n";
                echo templatereplace(file_get_contents(getTemplatePath($sTemplate).'/endpage.pstpl'),array());
                doFooter();
                exit;
            }  }
            //Fin session time out
            $sSRID = $_SESSION['survey_'.$iSurveyID]['srid']; //I want to see the answers with this id
            //Ensure script is not run directly, avoid path disclosure
            //if (!isset($rootdir) || isset($_REQUEST['$rootdir'])) {die( "browse - Cannot run this script directly");}
 
            //Ensure Participants printAnswer setting is set to true or that the logged user have read permissions over the responses.
            if ($aSurveyInfo['printanswers'] == 'N' && !Permission::model()->hasSurveyPermission($iSurveyID,'responses','read'))
            {
                throw new CHttpException(401, 'You are not allowed to print answers.');
            }
 
            //CHECK IF SURVEY IS ACTIVATED AND EXISTS
            $sSurveyName = $aSurveyInfo['surveyls_title'];
            $sAnonymized = $aSurveyInfo['anonymized'];
            //OK. IF WE GOT THIS FAR, THEN THE SURVEY EXISTS AND IT IS ACTIVE, SO LETS GET TO WORK.
            //SHOW HEADER
            if ($sExportType != 'pdf')
            {
                $sOutput = CHtml::form(array("printanswers/view/surveyid/{$iSurveyID}/printableexport/pdf"), 'post')
                ."<center><input type='submit' value='".$clang->gT("PDF export")."'id=\"exportbutton\"/><input type='hidden' name='printableexport' /></center></form>";
                $sOutput .= "\t<div class='printouttitle'><strong>".$clang->gT("Survey name (ID):")."</strong> $sSurveyName ($iSurveyID)</div><p>&nbsp;\n";
                LimeExpressionManager::StartProcessingPage(true);  // means that all variables are on the same page
                // Since all data are loaded, and don't need JavaScript, pretend all from Group 1
                LimeExpressionManager::StartProcessingGroup(1,($aSurveyInfo['anonymized']!="N"),$iSurveyID);
                $printanswershonorsconditions = Yii::app()->getConfig('printanswershonorsconditions');
                $aFullResponseTable = getFullResponseTable($iSurveyID,$sSRID,$sLanguage,$printanswershonorsconditions);
                //Get the fieldmap @TODO: do we need to filter out some fields?
                if($aSurveyInfo['datestamp']!="Y" || $sAnonymized == 'Y'){
                    unset ($aFullResponseTable['submitdate']);
                }else{
                    unset ($aFullResponseTable['id']);
                }
                unset ($aFullResponseTable['token']);
                unset ($aFullResponseTable['lastpage']);
                unset ($aFullResponseTable['startlanguage']);
                unset ($aFullResponseTable['datestamp']);
                unset ($aFullResponseTable['startdate']);
                $sOutput .= "<table class='printouttable' >\n";
                foreach ($aFullResponseTable as $sFieldname=>$fname)
                {
                    if (substr($sFieldname,0,4) == 'gid_')
                    {
                            $sOutput .= "\t<tr class='printanswersgroup'><td colspan='2'>{$fname[0]}</td></tr>\n";
                    }
                    elseif ($sFieldname=='submitdate')
                    {
                        if($sAnonymized != 'Y')
                        {
                                $sOutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]} {$sFieldname}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>";
                        }
                    }
                    elseif (substr($sFieldname,0,4) != 'qid_') // Question text is already in subquestion text, skipping it
                    {
                        $sOutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]}</td><td class='printanswersanswertext'>".flattenText($fname[2])."</td></tr>";
                    }
                }
                $sOutput .= "</table>\n";
                $sData['thissurvey']=$aSurveyInfo;
                $sOutput=templatereplace($sOutput, array() , $sData, '', $aSurveyInfo['anonymized']=="Y",NULL, array(), true);// Do a static replacement
                ob_start(function($buffer, $phase) {
                    App()->getClientScript()->render($buffer);
                    App()->getClientScript()->reset();
                    return $buffer;
                });
                ob_implicit_flush(false);
 
                sendCacheHeaders();
                doHeader();
                echo templatereplace(file_get_contents(getTemplatePath($sTemplate).'/startpage.pstpl'),array(),$sData);
                echo templatereplace(file_get_contents(getTemplatePath($sTemplate).'/printanswers.pstpl'),array('ANSWERTABLE'=>$sOutput),$sData);
                echo templatereplace(file_get_contents(getTemplatePath($sTemplate).'/endpage.pstpl'),array(),$sData);
                echo "</body></html>";
 
                ob_flush();
            }
            if($sExportType == 'pdf')
            {
                // Get images for TCPDF from template directory
                define('K_PATH_IMAGES', getTemplatePath($aSurveyInfo['template']).DIRECTORY_SEPARATOR);
 
                Yii::import('application.libraries.admin.pdf', true);
                Yii::import('application.helpers.pdfHelper');
                $aPdfLanguageSettings=pdfHelper::getPdfLanguageSettings($clang->langcode);
 
                $oPDF = new pdf();
                $sDefaultHeaderString = $sSurveyName." (".$clang->gT("ID",'unescaped').":".$iSurveyID.")";
                $oPDF->initAnswerPDF($aSurveyInfo, $aPdfLanguageSettings, Yii::app()->getConfig('sitename'), $sSurveyName, $sDefaultHeaderString);
				if($idtoprint > 0) {$sSRID=$idtoprint;}
                LimeExpressionManager::StartProcessingPage(true);  // means that all variables are on the same page
                // Since all data are loaded, and don't need JavaScript, pretend all from Group 1
                LimeExpressionManager::StartProcessingGroup(1,($aSurveyInfo['anonymized']!="N"),$iSurveyID);
                $printanswershonorsconditions = Yii::app()->getConfig('printanswershonorsconditions');
                $aFullResponseTable = getFullResponseTable($iSurveyID,$sSRID,$sLanguage,$printanswershonorsconditions);
                //Get the fieldmap @TODO: do we need to filter out some fields?
                if($aSurveyInfo['datestamp']!="Y" || $sAnonymized == 'Y'){
                    unset ($aFullResponseTable['submitdate']);
                }else{
                    unset ($aFullResponseTable['id']);
                }
                unset ($aFullResponseTable['token']);
                unset ($aFullResponseTable['lastpage']);
                unset ($aFullResponseTable['startlanguage']);
                unset ($aFullResponseTable['datestamp']);
                unset ($aFullResponseTable['startdate']);
                foreach ($aFullResponseTable as $sFieldname=>$fname)
                {
                    if (substr($sFieldname,0,4) == 'gid_')
                    {
                        $oPDF->addGidAnswer($fname[0]);
                    }
                    elseif ($sFieldname=='submitdate')
                    {
                        if($sAnonymized != 'Y')
                        {
                            $oPDF->addAnswer($fname[0]." ".$fname[1], $fname[2]);
                        }
                    }
                    elseif (substr($sFieldname,0,4) != 'qid_') // Question text is already in subquestion text, skipping it
                    {
                        $oPDF->addAnswer($fname[0]." ".$fname[1], $fname[2]);
                    }
                }
 
                header("Pragma: public");
                header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                $sExportFileName = sanitize_filename($sSurveyName);
                $oPDF->Output($sExportFileName."-".$iSurveyID.".pdf","D");
            }
 
            LimeExpressionManager::FinishProcessingGroup();
            LimeExpressionManager::FinishProcessingPage();
        }
    }
Last Edit: 2 years 4 months ago by DWS. Reason: no file attached
The following user(s) said Thank You: Ben_V

Please Log in to join the conversation.

More
2 years 4 months ago #122257 by Ben_V
Ben_V replied the topic: load Session / survey results by 3rd party php script
It's a really great and useful hack! Thanks for sharing it :)

Benoît

EM Variables => bit.ly/1TKQyNu | EM Roadmap => bit.ly/1UTrOB4
Last Releases => 2.6x.x goo.gl/ztWfIV | 2.06/2.6.x => bit.ly/1Qv44A1
Demo Surveys => goo.gl/HuR6Xe (already included in /docs/demosurveys)

Please Log in to join the conversation.

More
2 years 4 months ago #122316 by DenisChenu
DenisChenu replied the topic: load Session / survey results by 3rd party php script

DWS wrote: ...
I hope that this code will be usefull for you and that if anyone from the Limesurvey Team can add as or plugin or something similar.....

Please : github.com/LimeSurvey/LimeSurvey/pulls

Assistance on LimeSurvey forum and LimeSurvey core development are on my free time.
I'm not a LimeSurvey GmbH member, professional service on demand (or search sondages pro).
An error happen ? Before make a new topic : remind the Debug mode .

Please Log in to join the conversation.

More
2 years 4 months ago #122477 by Mazi
Mazi replied the topic: load Session / survey results by 3rd party php script
Denis, do we have a plugin function within the printanswers feature that allows extend the current feature?
I guess that would be very helpful.


Best regards/Beste Grüße,
Dr. Marcel Minke
(Limesurvey Head of Support)
Need Help? We offer professional Limesurvey support
Contact: marcel.minke(at)survey-consulting.com'"

Please Log in to join the conversation.

Start now!

Just create your account and start using Limesurvey today.

Register now
Join our Newsletter!