/**
  * 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)
 {
     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)) {
         $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 (!isset($_SESSION['survey_' . $iSurveyID]['finished']) || !isset($_SESSION['survey_' . $iSurveyID]['srid'])) {
         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");}
     if ($aSurveyInfo['printanswers'] == 'N') {
         die;
         //Die quietly if print answers is not permitted
     }
     //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
     $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>";
     if ($sExportType == 'pdf') {
         //require (Yii::app()->getConfig('rootdir').'/application/config/tcpdf.php');
         Yii::import('application.libraries.admin.pdf', true);
         Yii::import('application.helpers.pdfHelper');
         $aPdfLanguageSettings = pdfHelper::getPdfLanguageSettings($clang->langcode);
         $oPDF = new pdf();
         $oPDF->SetTitle($clang->gT("Survey name (ID)", 'unescaped') . ": {$sSurveyName} ({$iSurveyID})");
         $oPDF->SetSubject($sSurveyName);
         $oPDF->SetDisplayMode('fullpage', 'two');
         $oPDF->setLanguageArray($aPdfLanguageSettings['lg']);
         $oPDF->setHeaderFont(array($aPdfLanguageSettings['pdffont'], '', PDF_FONT_SIZE_MAIN));
         $oPDF->setFooterFont(array($aPdfLanguageSettings['pdffont'], '', PDF_FONT_SIZE_DATA));
         $oPDF->SetFont($aPdfLanguageSettings['pdffont'], '', $aPdfLanguageSettings['pdffontsize']);
         $oPDF->AddPage();
         $oPDF->titleintopdf($clang->gT("Survey name (ID)", 'unescaped') . ": {$sSurveyName} ({$iSurveyID})");
     }
     $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 (substr($sFieldname, 0, 4) == 'qid_') {
             $sOutput .= "\t<tr class='printanswersquestionhead'><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>";
             }
         } else {
             $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
     if ($sExportType == 'pdf') {
         $oPDF->writeHTML($sOutput);
         header("Pragma: public");
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         $sExportFileName = sanitize_filename($sSurveyName);
         $oPDF->Output($sExportFileName . "-" . $iSurveyID . ".pdf", "D");
     } else {
         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();
     }
     LimeExpressionManager::FinishProcessingGroup();
     LimeExpressionManager::FinishProcessingPage();
 }
/**
* Send a submit notification to the email address specified in the notifications tab in the survey settings
*/
function sendSubmitNotifications($surveyid)
{
    // @todo: Remove globals
    global $thissurvey, $maildebug, $tokensexist;
    if (trim($thissurvey['adminemail']) == '') {
        return;
    }
    $homeurl = Yii::app()->createAbsoluteUrl('/admin');
    $clang = Yii::app()->lang;
    $sitename = Yii::app()->getConfig("sitename");
    $debug = Yii::app()->getConfig('debug');
    $bIsHTML = $thissurvey['htmlemail'] == 'Y';
    $aReplacementVars = array();
    if ($thissurvey['allowsave'] == "Y" && isset($_SESSION['survey_' . $surveyid]['scid'])) {
        $aReplacementVars['RELOADURL'] = "" . Yii::app()->getController()->createUrl("/survey/index/sid/{$surveyid}/loadall/reload/scid/" . $_SESSION['survey_' . $surveyid]['scid'] . "/loadname/" . urlencode($_SESSION['survey_' . $surveyid]['holdname']) . "/loadpass/" . urlencode($_SESSION['survey_' . $surveyid]['holdpass']) . "/lang/" . urlencode($clang->langcode));
        if ($bIsHTML) {
            $aReplacementVars['RELOADURL'] = "<a href='{$aReplacementVars['RELOADURL']}'>{$aReplacementVars['RELOADURL']}</a>";
        }
    } else {
        $aReplacementVars['RELOADURL'] = '';
    }
    if (!isset($_SESSION['survey_' . $surveyid]['srid'])) {
        $srid = null;
    } else {
        $srid = $_SESSION['survey_' . $surveyid]['srid'];
    }
    $aReplacementVars['ADMINNAME'] = $thissurvey['adminname'];
    $aReplacementVars['ADMINEMAIL'] = $thissurvey['adminemail'];
    $aReplacementVars['VIEWRESPONSEURL'] = Yii::app()->createAbsoluteUrl("/admin/responses/sa/view/surveyid/{$surveyid}/id/{$srid}");
    $aReplacementVars['EDITRESPONSEURL'] = Yii::app()->createAbsoluteUrl("/admin/dataentry/sa/editdata/subaction/edit/surveyid/{$surveyid}/id/{$srid}");
    $aReplacementVars['STATISTICSURL'] = Yii::app()->createAbsoluteUrl("/admin/statistics/sa/index/surveyid/{$surveyid}");
    if ($bIsHTML) {
        $aReplacementVars['VIEWRESPONSEURL'] = "<a href='{$aReplacementVars['VIEWRESPONSEURL']}'>{$aReplacementVars['VIEWRESPONSEURL']}</a>";
        $aReplacementVars['EDITRESPONSEURL'] = "<a href='{$aReplacementVars['EDITRESPONSEURL']}'>{$aReplacementVars['EDITRESPONSEURL']}</a>";
        $aReplacementVars['STATISTICSURL'] = "<a href='{$aReplacementVars['STATISTICSURL']}'>{$aReplacementVars['STATISTICSURL']}</a>";
    }
    $aReplacementVars['ANSWERTABLE'] = '';
    $aEmailResponseTo = array();
    $aEmailNotificationTo = array();
    $sResponseData = "";
    if (!empty($thissurvey['emailnotificationto'])) {
        $aRecipient = explode(";", ReplaceFields($thissurvey['emailnotificationto'], array('ADMINEMAIL' => $thissurvey['adminemail']), true));
        foreach ($aRecipient as $sRecipient) {
            $sRecipient = trim($sRecipient);
            if (validateEmailAddress($sRecipient)) {
                $aEmailNotificationTo[] = $sRecipient;
            }
        }
    }
    if (!empty($thissurvey['emailresponseto'])) {
        // there was no token used so lets remove the token field from insertarray
        if (!isset($_SESSION['survey_' . $surveyid]['token']) && $_SESSION['survey_' . $surveyid]['insertarray'][0] == 'token') {
            unset($_SESSION['survey_' . $surveyid]['insertarray'][0]);
        }
        //Make an array of email addresses to send to
        $aRecipient = explode(";", ReplaceFields($thissurvey['emailresponseto'], array('ADMINEMAIL' => $thissurvey['adminemail']), true));
        foreach ($aRecipient as $sRecipient) {
            $sRecipient = trim($sRecipient);
            if (validateEmailAddress($sRecipient)) {
                $aEmailResponseTo[] = $sRecipient;
            }
        }
        $aFullResponseTable = getFullResponseTable($surveyid, $_SESSION['survey_' . $surveyid]['srid'], $_SESSION['survey_' . $surveyid]['s_lang']);
        $ResultTableHTML = "<table class='printouttable' >\n";
        $ResultTableText = "\n\n";
        $oldgid = 0;
        $oldqid = 0;
        foreach ($aFullResponseTable as $sFieldname => $fname) {
            if (substr($sFieldname, 0, 4) == 'gid_') {
                $ResultTableHTML .= "\t<tr class='printanswersgroup'><td colspan='2'>" . strip_tags($fname[0]) . "</td></tr>\n";
                $ResultTableText .= "\n{$fname[0]}\n\n";
            } elseif (substr($sFieldname, 0, 4) == 'qid_') {
                $ResultTableHTML .= "\t<tr class='printanswersquestionhead'><td  colspan='2'>" . strip_tags($fname[0]) . "</td></tr>\n";
                $ResultTableText .= "\n{$fname[0]}\n";
            } else {
                $ResultTableHTML .= "\t<tr class='printanswersquestion'><td>" . strip_tags("{$fname[0]} {$fname[1]}") . "</td><td class='printanswersanswertext'>" . CHtml::encode($fname[2]) . "</td></tr>\n";
                $ResultTableText .= "     {$fname[0]} {$fname[1]}: {$fname[2]}\n";
            }
        }
        $ResultTableHTML .= "</table>\n";
        $ResultTableText .= "\n\n";
        if ($bIsHTML) {
            $aReplacementVars['ANSWERTABLE'] = $ResultTableHTML;
        } else {
            $aReplacementVars['ANSWERTABLE'] = $ResultTableText;
        }
    }
    $sFrom = $thissurvey['adminname'] . ' <' . $thissurvey['adminemail'] . '>';
    $aAttachments = unserialize($thissurvey['attachments']);
    $aRelevantAttachments = array();
    /*
     * Iterate through attachments and check them for relevance.
     */
    if (isset($aAttachments['admin_notification'])) {
        foreach ($aAttachments['admin_notification'] as $aAttachment) {
            $relevance = $aAttachment['relevance'];
            // If the attachment is relevant it will be added to the mail.
            if (LimeExpressionManager::ProcessRelevance($relevance) && file_exists($aAttachment['url'])) {
                $aRelevantAttachments[] = $aAttachment['url'];
            }
        }
    }
    $redata = compact(array_keys(get_defined_vars()));
    if (count($aEmailNotificationTo) > 0) {
        $sMessage = templatereplace($thissurvey['email_admin_notification'], $aReplacementVars, $redata, 'frontend_helper[1398]', $thissurvey['anonymized'] == "Y", NULL, array(), true);
        $sSubject = templatereplace($thissurvey['email_admin_notification_subj'], $aReplacementVars, $redata, 'frontend_helper[1399]', $thissurvey['anonymized'] == "Y", NULL, array(), true);
        foreach ($aEmailNotificationTo as $sRecipient) {
            if (!SendEmailMessage($sMessage, $sSubject, $sRecipient, $sFrom, $sitename, true, getBounceEmail($surveyid), $aRelevantAttachments)) {
                if ($debug > 0) {
                    echo '<br />Email could not be sent. Reason: ' . $maildebug . '<br/>';
                }
            }
        }
    }
    $aRelevantAttachments = array();
    /*
     * Iterate through attachments and check them for relevance.
     */
    if (isset($aAttachments['detailed_admin_notification'])) {
        foreach ($aAttachments['detailed_admin_notification'] as $aAttachment) {
            $relevance = $aAttachment['relevance'];
            // If the attachment is relevant it will be added to the mail.
            if (LimeExpressionManager::ProcessRelevance($relevance) && file_exists($aAttachment['url'])) {
                $aRelevantAttachments[] = $aAttachment['url'];
            }
        }
    }
    if (count($aEmailResponseTo) > 0) {
        $sMessage = templatereplace($thissurvey['email_admin_responses'], $aReplacementVars, $redata, 'frontend_helper[1414]', $thissurvey['anonymized'] == "Y", NULL, array(), true);
        $sSubject = templatereplace($thissurvey['email_admin_responses_subj'], $aReplacementVars, $redata, 'frontend_helper[1415]', $thissurvey['anonymized'] == "Y", NULL, array(), true);
        foreach ($aEmailResponseTo as $sRecipient) {
            if (!SendEmailMessage($sMessage, $sSubject, $sRecipient, $sFrom, $sitename, true, getBounceEmail($surveyid), $aRelevantAttachments)) {
                if ($debug > 0) {
                    echo '<br />Email could not be sent. Reason: ' . $maildebug . '<br/>';
                }
            }
        }
    }
}
 /**
  * Returns the answer table of a response to be used
  * as a replacement for {ANSWERTABLE}
  * This is mostly a copy/paste of core code because of lack of factorization.
  * @param int $surveyid : the survey id number
  * @param int $srid : the response id number
  * @param string $lang : the lang code for localization
  * @param boolean $bIsHTML : TRUE if the returned string is HTML formatted
  * @param array $aFilteredFields : array of filtered response fields
  * return string : the replacement string for {ANSWERTABLE}
  **/
 private function translateAnswerTable($surveyid, $srid, $lang, $bIsHTML = true, $aFilteredFields = array())
 {
     $aFullResponseTable = getFullResponseTable($surveyid, $srid, $lang);
     $ResultTableHTML = "<table class='printouttable' >\n";
     $ResultTableText = "\n\n";
     $oldgid = 0;
     $oldqid = 0;
     foreach ($aFullResponseTable as $sFieldname => $fname) {
         if (substr($sFieldname, 0, 4) == 'gid_') {
             $ResultTableHTML .= "\t<tr class='printanswersgroup'><td colspan='2'>" . strip_tags($fname[0]) . "</td></tr>\n";
             $ResultTableText .= "\n{$fname[0]}\n\n";
         } elseif (substr($sFieldname, 0, 4) == 'qid_') {
             $ResultTableHTML .= "\t<tr class='printanswersquestionhead'><td  colspan='2'>" . strip_tags($fname[0]) . "</td></tr>\n";
             $ResultTableText .= "\n{$fname[0]}\n";
         } elseif (!in_array($sFieldname, $aFilteredFields)) {
             $ResultTableHTML .= "\t<tr class='printanswersquestion'><td>" . strip_tags("{$fname[0]} {$fname[1]}") . "</td><td class='printanswersanswertext'>" . CHtml::encode($fname[2]) . "</td></tr>\n";
             $ResultTableText .= "     {$fname[0]} {$fname[1]}: {$fname[2]}\n";
         }
     }
     $ResultTableHTML .= "</table>\n";
     $ResultTableText .= "\n\n";
     if ($bIsHTML) {
         return $ResultTableHTML;
     } else {
         return $ResultTableText;
     }
 }
 /**
  * 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)
 {
     global $siteadminname, $siteadminemail;
     Yii::app()->loadHelper("frontend");
     Yii::import('application.libraries.admin.pdf');
     $surveyid = (int) $surveyid;
     Yii::app()->loadHelper('database');
     if (isset($_SESSION['survey_' . $surveyid]['sid'])) {
         $surveyid = $_SESSION['survey_' . $surveyid]['sid'];
     } else {
         die('Invalid survey/session');
     }
     //Debut session time out
     if (!isset($_SESSION['survey_' . $surveyid]['finished']) || !isset($_SESSION['survey_' . $surveyid]['srid'])) {
         //require_once($rootdir.'/classes/core/language.php');
         $baselang = Survey::model()->findByPk($surveyid)->language;
         Yii::import('application.libraries.Limesurvey_lang', true);
         $clang = new Limesurvey_lang($baselang);
         //A nice exit
         sendCacheHeaders();
         doHeader();
         echo templatereplace(file_get_contents(getTemplatePath(validateTemplateDir("default")) . "/startpage.pstpl"), array(), 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."), $siteadminname, $siteadminemail) . "\n" . "</center><br />\n";
         echo templatereplace(file_get_contents(getTemplatePath(validateTemplateDir("default")) . "/endpage.pstpl"), array(), array());
         doFooter();
         exit;
     }
     //Fin session time out
     $id = $_SESSION['survey_' . $surveyid]['srid'];
     //I want to see the answers with this id
     $clang = $_SESSION['survey_' . $surveyid]['s_lang'];
     //Ensure script is not run directly, avoid path disclosure
     //if (!isset($rootdir) || isset($_REQUEST['$rootdir'])) {die( "browse - Cannot run this script directly");}
     // Set the language for dispay
     //require_once($rootdir.'/classes/core/language.php');  // has been secured
     if (isset($_SESSION['survey_' . $surveyid]['s_lang'])) {
         $clang = SetSurveyLanguage($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
         $language = $_SESSION['survey_' . $surveyid]['s_lang'];
     } else {
         $language = Survey::model()->findByPk($surveyid)->language;
         $clang = SetSurveyLanguage($surveyid, $language);
     }
     // Get the survey inforamtion
     $thissurvey = getSurveyInfo($surveyid, $language);
     //SET THE TEMPLATE DIRECTORY
     if (!isset($thissurvey['templatedir']) || !$thissurvey['templatedir']) {
         $thistpl = validateTemplateDir("default");
     } else {
         $thistpl = validateTemplateDir($thissurvey['templatedir']);
     }
     if ($thissurvey['printanswers'] == 'N') {
         die;
         //Die quietly if print answers is not permitted
     }
     //CHECK IF SURVEY IS ACTIVATED AND EXISTS
     $surveytable = "{{survey_{$surveyid}}}";
     $surveyname = $thissurvey['surveyls_title'];
     $anonymized = $thissurvey['anonymized'];
     //OK. IF WE GOT THIS FAR, THEN THE SURVEY EXISTS AND IT IS ACTIVE, SO LETS GET TO WORK.
     //SHOW HEADER
     $printoutput = '';
     $printoutput .= "<form action='" . Yii::app()->getController()->createUrl('printanswers/view/surveyid/' . $surveyid . '/printableexport/pdf') . "' method='post'>\n<center><input type='submit' value='" . $clang->gT("PDF export") . "'id=\"exportbutton\"/><input type='hidden' name='printableexport' /></center></form>";
     if ($printableexport == 'pdf') {
         require Yii::app()->getConfig('rootdir') . '/application/config/tcpdf.php';
         Yii::import('application.libraries.admin.pdf', true);
         $pdf = new pdf();
         $pdf->setConfig($tcpdf);
         //$pdf->SetFont($pdfdefaultfont,'',$pdffontsize);
         $pdf->AddPage();
         //$pdf->titleintopdf($clang->gT("Survey name (ID)",'unescaped').": {$surveyname} ({$surveyid})");
         $pdf->SetTitle($clang->gT("Survey name (ID)", 'unescaped') . ": {$surveyname} ({$surveyid})");
     }
     $printoutput .= "\t<div class='printouttitle'><strong>" . $clang->gT("Survey name (ID):") . "</strong> {$surveyname} ({$surveyid})</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, $thissurvey['anonymized'] != "N", $surveyid);
     $aFullResponseTable = getFullResponseTable($surveyid, $id, $language, true);
     //Get the fieldmap @TODO: do we need to filter out some fields?
     unset($aFullResponseTable['id']);
     unset($aFullResponseTable['token']);
     unset($aFullResponseTable['lastpage']);
     unset($aFullResponseTable['startlanguage']);
     unset($aFullResponseTable['datestamp']);
     unset($aFullResponseTable['startdate']);
     $printoutput .= "<table class='printouttable' >\n";
     if ($printableexport == 'pdf') {
         $pdf->intopdf($clang->gT("Question", 'unescaped') . ": " . $clang->gT("Your answer", 'unescaped'));
     }
     $oldgid = 0;
     $oldqid = 0;
     foreach ($aFullResponseTable as $sFieldname => $fname) {
         if (substr($sFieldname, 0, 4) == 'gid_') {
             if ($printableexport) {
                 $pdf->intopdf(flattenText($fname[0], false, true));
                 $pdf->ln(2);
             } else {
                 $printoutput .= "\t<tr class='printanswersgroup'><td colspan='2'>{$fname[0]}</td></tr>\n";
             }
         } elseif (substr($sFieldname, 0, 4) == 'qid_') {
             if ($printableexport == 'pdf') {
                 $pdf->intopdf(flattenText($fname[0] . $fname[1], false, true) . ": " . $fname[2]);
                 $pdf->ln(2);
             } else {
                 $printoutput .= "\t<tr class='printanswersquestionhead'><td  colspan='2'>{$fname[0]}</td></tr>\n";
             }
         } elseif ($sFieldname == 'submitdate') {
             if ($anonymized != 'Y') {
                 if ($printableexport == 'pdf') {
                     $pdf->intopdf(flattenText($fname[0] . $fname[1], false, true) . ": " . $fname[2]);
                     $pdf->ln(2);
                 } else {
                     $printoutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]} {$sFieldname}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>";
                 }
             }
         } else {
             if ($printableexport == 'pdf') {
                 $pdf->intopdf(flattenText($fname[0] . $fname[1], false, true) . ": " . $fname[2]);
                 $pdf->ln(2);
             } else {
                 $printoutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>";
             }
         }
     }
     $printoutput .= "</table>\n";
     if ($printableexport == 'pdf') {
         header("Pragma: public");
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         $sExportFileName = sanitize_filename($surveyname);
         $pdf->Output($sExportFileName . "-" . $surveyid . ".pdf", "D");
     }
     //Display the page with user answers
     if (!$printableexport) {
         sendCacheHeaders();
         doHeader();
         echo templatereplace(file_get_contents(getTemplatePath($thistpl) . '/startpage.pstpl'));
         echo templatereplace(file_get_contents(getTemplatePath($thistpl) . '/printanswers.pstpl'), array('ANSWERTABLE' => $printoutput));
         echo templatereplace(file_get_contents(getTemplatePath($thistpl) . '/endpage.pstpl'));
         echo "</body></html>";
     }
     LimeExpressionManager::FinishProcessingGroup();
     LimeExpressionManager::FinishProcessingPage();
 }
 /**
  * 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)
 {
     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)) {
         $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
     } else {
         $iSurveyID = 0;
         $sLanguage = Yii::app()->getConfig("defaultlang");
     }
     SetSurveyLanguage($iSurveyID, $sLanguage);
     $aSurveyInfo = getSurveyInfo($iSurveyID, $sLanguage);
     $oTemplate = Template::model()->getInstance(null, $iSurveyID);
     //Survey is not finished or don't exist
     if (!isset($_SESSION['survey_' . $iSurveyID]['finished']) || !isset($_SESSION['survey_' . $iSurveyID]['srid'])) {
         sendCacheHeaders();
         doHeader();
         /// $oTemplate is a global variable defined in controller/survey/index
         echo templatereplace(file_get_contents($oTemplate->viewPath . '/startpage.pstpl'), array());
         echo "<center><br />\n" . "\t<font color='RED'><strong>" . gT("Error") . "</strong></font><br />\n" . "\t" . gT("We are sorry but your session has expired.") . "<br />" . 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(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($oTemplate->viewPath . '/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 class='btn btn-default' type='submit' value='" . gT("PDF export") . "'id=\"exportbutton\"/><input type='hidden' name='printableexport' /></center></form>";
         $sOutput .= "\t<div class='printouttitle'><strong>" . 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";
                 $sOutput .= "\t<tr class='printanswersgroupdesc'><td colspan='2'>{$fname[1]}</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_') {
                 $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($oTemplate->viewPath . '/startpage.pstpl'), array(), $sData);
         echo templatereplace(file_get_contents($oTemplate->viewPath . '/printanswers.pstpl'), array('ANSWERTABLE' => $sOutput), $sData);
         echo templatereplace(file_get_contents($oTemplate->viewPath . '/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(App()->language);
         $oPDF = new pdf();
         $sDefaultHeaderString = $sSurveyName . " (" . gT("ID", 'unescaped') . ":" . $iSurveyID . ")";
         $oPDF->initAnswerPDF($aSurveyInfo, $aPdfLanguageSettings, Yii::app()->getConfig('sitename'), $sSurveyName, $sDefaultHeaderString);
         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], $fname[1]);
             } elseif ($sFieldname == 'submitdate') {
                 if ($sAnonymized != 'Y') {
                     $oPDF->addAnswer($fname[0] . " " . $fname[1], $fname[2]);
                 }
             } elseif (substr($sFieldname, 0, 4) != 'qid_') {
                 $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();
 }
Example #6
0
/**
 * Send a submit notification to the email address specified in the notifications tab in the survey settings
 */
function sendSubmitNotifications($surveyid)
{
    global $thissurvey, $debug;
    global $homeurl, $maildebug, $tokensexist;
    $clang = Yii::app()->lang;
    $sitename = Yii::app()->getConfig("sitename");
    $bIsHTML = $thissurvey['htmlemail'] == 'Y';
    $aReplacementVars = array();
    if ($thissurvey['allowsave'] == "Y" && isset($_SESSION['survey_' . $surveyid]['scid'])) {
        $aReplacementVars['RELOADURL'] = "" . Yii::app()->getController()->createUrl("/survey/index/sid/{$surveyid}/loadall/reload/scid/" . $_SESSION['survey_' . $surveyid]['scid'] . "/loadname/" . urlencode($_SESSION['survey_' . $surveyid]['holdname']) . "/loadpass/" . urlencode($_SESSION['survey_' . $surveyid]['holdpass']));
        if ($bIsHTML) {
            $aReplacementVars['RELOADURL'] = "<a href='{$aReplacementVars['RELOADURL']}'>{$aReplacementVars['RELOADURL']}</a>";
        }
    } else {
        $aReplacementVars['RELOADURL'] = '';
    }
    if (!isset($_SESSION['survey_' . $surveyid]['srid'])) {
        $srid = null;
    } else {
        $srid = $_SESSION['survey_' . $surveyid]['srid'];
    }
    $aReplacementVars['ADMINNAME'] = $thissurvey['adminname'];
    $aReplacementVars['ADMINEMAIL'] = $thissurvey['adminemail'];
    $aReplacementVars['VIEWRESPONSEURL'] = "{$homeurl}/admin.php?action=browse&sid={$surveyid}&subaction=id&id=" . $srid;
    $aReplacementVars['EDITRESPONSEURL'] = "{$homeurl}/admin.php?action=dataentry&sid={$surveyid}&subaction=edit&surveytable=survey_{$surveyid}&id=" . $srid;
    $aReplacementVars['STATISTICSURL'] = "{$homeurl}/admin.php?action=statistics&sid={$surveyid}";
    if ($bIsHTML) {
        $aReplacementVars['VIEWRESPONSEURL'] = "<a href='{$aReplacementVars['VIEWRESPONSEURL']}'>{$aReplacementVars['VIEWRESPONSEURL']}</a>";
        $aReplacementVars['EDITRESPONSEURL'] = "<a href='{$aReplacementVars['EDITRESPONSEURL']}'>{$aReplacementVars['EDITRESPONSEURL']}</a>";
        $aReplacementVars['STATISTICSURL'] = "<a href='{$aReplacementVars['STATISTICSURL']}'>{$aReplacementVars['STATISTICSURL']}</a>";
    }
    $aReplacementVars['ANSWERTABLE'] = '';
    $aEmailResponseTo = array();
    $aEmailNotificationTo = array();
    $sResponseData = "";
    if (!empty($thissurvey['emailnotificationto'])) {
        $aRecipient = explode(";", $thissurvey['emailnotificationto']);
        foreach ($aRecipient as $sRecipient) {
            $sRecipient = ReplaceFields($sRecipient, array('ADMINEMAIL' => $thissurvey['adminemail']), true);
            // Only need INSERTANS, ADMINMAIL and TOKEN
            if (validateEmailAddress($sRecipient)) {
                $aEmailNotificationTo[] = $sRecipient;
            }
        }
    }
    if (!empty($thissurvey['emailresponseto'])) {
        if (isset($_SESSION['survey_' . $surveyid]['token']) && $_SESSION['survey_' . $surveyid]['token'] != '' && tableExists('{{tokens_' . $surveyid . '}}')) {
            //Gather token data for tokenised surveys
            $_SESSION['survey_' . $surveyid]['thistoken'] = getTokenData($surveyid, $_SESSION['survey_' . $surveyid]['token']);
        } elseif ($_SESSION['survey_' . $surveyid]['insertarray'][0] == 'token') {
            unset($_SESSION['survey_' . $surveyid]['insertarray'][0]);
        }
        //Make an array of email addresses to send to
        $aRecipient = explode(";", $thissurvey['emailresponseto']);
        foreach ($aRecipient as $sRecipient) {
            $sRecipient = ReplaceFields($sRecipient, array('ADMINEMAIL' => $thissurvey['adminemail']), true);
            // Only need INSERTANS, ADMINMAIL and TOKEN
            if (validateEmailAddress($sRecipient)) {
                $aEmailResponseTo[] = $sRecipient;
            }
        }
        $aFullResponseTable = getFullResponseTable($surveyid, $_SESSION['survey_' . $surveyid]['srid'], $_SESSION['survey_' . $surveyid]['s_lang']);
        $ResultTableHTML = "<table class='printouttable' >\n";
        $ResultTableText = "\n\n";
        $oldgid = 0;
        $oldqid = 0;
        foreach ($aFullResponseTable as $sFieldname => $fname) {
            if (substr($sFieldname, 0, 4) == 'gid_') {
                $ResultTableHTML .= "\t<tr class='printanswersgroup'><td colspan='2'>{$fname[0]}</td></tr>\n";
                $ResultTableText .= "\n{$fname[0]}\n\n";
            } elseif (substr($sFieldname, 0, 4) == 'qid_') {
                $ResultTableHTML .= "\t<tr class='printanswersquestionhead'><td  colspan='2'>{$fname[0]}</td></tr>\n";
                $ResultTableText .= "\n{$fname[0]}\n";
            } else {
                $ResultTableHTML .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>";
                $ResultTableText .= "     {$fname[0]} {$fname[1]}: {$fname[2]}\n";
            }
        }
        $ResultTableHTML .= "</table>\n";
        $ResultTableText .= "\n\n";
        if ($bIsHTML) {
            $aReplacementVars['ANSWERTABLE'] = $ResultTableHTML;
        } else {
            $aReplacementVars['ANSWERTABLE'] = $ResultTableText;
        }
    }
    $sFrom = $thissurvey['adminname'] . ' <' . $thissurvey['adminemail'] . '>';
    $redata = compact(array_keys(get_defined_vars()));
    if (count($aEmailNotificationTo) > 0) {
        $sMessage = templatereplace($thissurvey['email_admin_notification'], $aReplacementVars, $redata, 'frontend_helper[1398]', $thissurvey['anonymized'] == "Y");
        $sSubject = templatereplace($thissurvey['email_admin_notification_subj'], $aReplacementVars, $redata, 'frontend_helper[1399]', $thissurvey['anonymized'] == "Y");
        foreach ($aEmailNotificationTo as $sRecipient) {
            if (!SendEmailMessage($sMessage, $sSubject, $sRecipient, $sFrom, $sitename, true, getBounceEmail($surveyid))) {
                if ($debug > 0) {
                    echo '<br />Email could not be sent. Reason: ' . $maildebug . '<br/>';
                }
            }
        }
    }
    if (count($aEmailResponseTo) > 0) {
        $sMessage = templatereplace($thissurvey['email_admin_responses'], $aReplacementVars, $redata, 'frontend_helper[1414]', $thissurvey['anonymized'] == "Y");
        $sSubject = templatereplace($thissurvey['email_admin_responses_subj'], $aReplacementVars, $redata, 'frontend_helper[1415]', $thissurvey['anonymized'] == "Y");
        foreach ($aEmailResponseTo as $sRecipient) {
            if (!SendEmailMessage($sMessage, $sSubject, $sRecipient, $sFrom, $sitename, true, getBounceEmail($surveyid))) {
                if ($debug > 0) {
                    echo '<br />Email could not be sent. Reason: ' . $maildebug . '<br/>';
                }
            }
        }
    }
}