/**
* Generates statistics
*
* @param int $surveyid The survey id
* @param mixed $allfields
* @param mixed $q2show
* @param mixed $usegraph
* @param string $outputType Optional - Can be xls, html or pdf - Defaults to pdf
* @param string $pdfOutput Sets the target for the PDF output: DD=File download , F=Save file to local disk
* @param string $statlangcode Lamguage for statistics
* @param mixed $browse  Show browse buttons
* @return buffer
*/
function generate_statistics($surveyid, $allfields, $q2show = 'all', $usegraph = 0, $outputType = 'pdf', $pdfOutput = 'I', $statlangcode = null, $browse = true)
{
    global $pdfdefaultfont, $pdffontsize;
    $astatdata = array();
    //astatdata generates data for the output page's javascript so it can rebuild graphs on the fly
    //load surveytranslator helper
    Yii::import('application.helpers.surveytranslator_helper', true);
    $statisticsoutput = "";
    //This string carries all the actual HTML code to print.
    $imagedir = Yii::app()->getConfig("imagedir");
    $tempdir = Yii::app()->getConfig("tempdir");
    $tempurl = Yii::app()->getConfig("tempurl");
    $clang = Yii::app()->lang;
    $pdf = array();
    //Make sure $pdf exists - it will be replaced with an object if a $pdf is actually being created
    // Used for getting coordinates for google maps
    $agmapdata = array();
    //pick the best font file if font setting is 'auto'
    if (is_null($statlangcode)) {
        $statlangcode = getBaseLanguageFromSurveyID($surveyid);
    } else {
        $statlang = new Limesurvey_lang($statlangcode);
    }
    /*
     * this variable is used in the function shortencode() which cuts off a question/answer title
     * after $maxchars and shows the rest as tooltip (in html mode)
     */
    $maxchars = 13;
    //we collect all the html-output within this variable
    $statisticsoutput = '';
    /**
     * $outputType: html || pdf ||
     */
    /**
     * get/set Survey Details
     */
    //no survey ID? -> come and get one
    if (!isset($surveyid)) {
        $surveyid = returnGlobal('sid');
    }
    //Get an array of codes of all available languages in this survey
    $surveylanguagecodes = Survey::model()->findByPk($surveyid)->additionalLanguages;
    $surveylanguagecodes[] = Survey::model()->findByPk($surveyid)->language;
    $fieldmap = createFieldMap($surveyid, "full", false, false, $statlang->getlangcode());
    // Set language for questions and answers to base language of this survey
    $language = $statlangcode;
    if ($q2show == 'all') {
        $summarySql = " SELECT gid, parent_qid, qid, type " . " FROM {{questions}} WHERE parent_qid=0" . " AND sid={$surveyid} ";
        $summaryRs = Yii::app()->db->createCommand($summarySql)->query()->readAll();
        foreach ($summaryRs as $field) {
            $myField = $surveyid . "X" . $field['gid'] . "X" . $field['qid'];
            // Multiple choice get special treatment
            if ($field['type'] == "M") {
                $myField = "M{$myField}";
            }
            if ($field['type'] == "P") {
                $myField = "P{$myField}";
            }
            //numerical input will get special treatment (arihtmetic mean, standard derivation, ...)
            if ($field['type'] == "N") {
                $myField = "N{$myField}";
            }
            if ($field['type'] == "|") {
                $myField = "|{$myField}";
            }
            if ($field['type'] == "Q") {
                $myField = "Q{$myField}";
            }
            // textfields get special treatment
            if ($field['type'] == "S" || $field['type'] == "T" || $field['type'] == "U") {
                $myField = "T{$myField}";
            }
            //statistics for Date questions are not implemented yet.
            if ($field['type'] == "D") {
                $myField = "D{$myField}";
            }
            if ($field['type'] == "F" || $field['type'] == "H") {
                //Get answers. We always use the answer code because the label might be too long elsewise
                $query = "SELECT code, answer FROM {{answers}} WHERE qid='" . $field['qid'] . "' AND scale_id=0 AND language='{$language}' ORDER BY sortorder, answer";
                $result = Yii::app()->db->createCommand($query)->query();
                $counter2 = 0;
                //check all the answers
                foreach ($result->readAll() as $row) {
                    $row = array_values($row);
                    $myField = "{$myField}{$row[0]}";
                }
                //$myField = "{$surveyid}X{$flt[1]}X{$flt[0]}{$row[0]}[]";
            }
            if ($q2show == 'all') {
                $summary[] = $myField;
            }
            //$allfields[]=$myField;
        }
    } else {
        // This gets all the 'to be shown questions' from the POST and puts these into an array
        if (!is_array($q2show)) {
            $summary = returnGlobal('summary');
        } else {
            $summary = $q2show;
        }
        //print_r($_POST);
        //if $summary isn't an array we create one
        if (isset($summary) && !is_array($summary)) {
            $summary = explode("+", $summary);
        }
    }
    /**
     * pdf Config
     */
    if ($outputType == 'pdf') {
        //require_once('classes/tcpdf/config/lang/eng.php');
        global $l;
        $l['w_page'] = $statlang->gT("Page", 'unescaped');
        //require_once('classes/tcpdf/mypdf.php');
        Yii::import('application.libraries.admin.pdf', true);
        // create new PDF document
        $pdf = new Pdf();
        $pdf->SetFont($pdfdefaultfont, '', $pdffontsize);
        $surveyInfo = getSurveyInfo($surveyid, $language);
        // set document information
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('LimeSurvey');
        $pdf->SetTitle('Statistic survey ' . $surveyid);
        $pdf->SetSubject($surveyInfo['surveyls_title']);
        $pdf->SetKeywords('LimeSurvey, Statistics, Survey ' . $surveyid . '');
        $pdf->SetDisplayMode('fullpage', 'two');
        // set header and footer fonts
        $pdf->setHeaderFont(array($pdfdefaultfont, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(array($pdfdefaultfont, '', PDF_FONT_SIZE_DATA));
        // set default header data
        $pdf->SetHeaderData("statistics.png", 10, $statlang->gT("Quick statistics", 'unescaped'), $statlang->gT("Survey") . " " . $surveyid . " '" . flattenText($surveyInfo['surveyls_title'], false, true, 'UTF-8') . "'");
        // set default monospaced font
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
        //set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
        //set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        //set image scale factor
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
        //set some language-dependent strings
        $pdf->setLanguageArray($l);
    }
    if ($outputType == 'xls') {
        /**
         * Initiate the Spreadsheet_Excel_Writer
         */
        Yii::import('application.libraries.admin.pear.Spreadsheet.Excel.Xlswriter', true);
        if ($pdfOutput == 'F') {
            $sFileName = $tempdir . '/statistic-survey' . $surveyid . '.xls';
            $workbook = new Xlswriter($sFileName);
        } else {
            $workbook = new Xlswriter();
        }
        $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("", ...)
        $workbook->setTempDir($tempdir);
        // 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);
        }
        if ($pdfOutput != 'F') {
            $workbook->send('statistic-survey' . $surveyid . '.xls');
        }
        // Creating the first worksheet
        $sheet =& $workbook->addWorksheet(utf8_decode('results-survey' . $surveyid));
        $sheet->setInputEncoding('utf-8');
        $sheet->setColumn(0, 20, 20);
        $separator = "~|";
        /**XXX*/
    }
    /**
     * Start generating
     */
    $selects = buildSelects($allfields, $surveyid, $language);
    //count number of answers
    $query = "SELECT count(*) FROM {{survey_{$surveyid}}}";
    //if incompleted answers should be filtert submitdate has to be not null
    if (incompleteAnsFilterState() == "inc") {
        $query .= " WHERE submitdate is null";
    } elseif (incompleteAnsFilterState() == "filter") {
        $query .= " WHERE submitdate is not null";
    }
    $result = Yii::app()->db->createCommand($query)->query();
    //$total = total number of answers
    $row = $result->read();
    $total = reset($row);
    //are there any filters that have to be taken care of?
    if (isset($selects) && $selects) {
        //filter incomplete answers?
        if (incompleteAnsFilterState() == "filter" || incompleteAnsFilterState() == "inc") {
            $query .= " AND ";
        } else {
            $query .= " WHERE ";
        }
        //add filter criteria to SQL
        $query .= implode(" AND ", $selects);
    }
    //get me some data Scotty
    $result = Yii::app()->db->createCommand($query)->query();
    //put all results into $results
    $row = $result->read();
    $results = reset($row);
    if ($total) {
        $percent = sprintf("%01.2f", $results / $total * 100);
    }
    switch ($outputType) {
        case "xls":
            $xlsRow = 0;
            $sheet->write($xlsRow, 0, $statlang->gT("Number of records in this query:", 'unescaped'));
            $sheet->write($xlsRow, 1, $results);
            ++$xlsRow;
            $sheet->write($xlsRow, 0, $statlang->gT("Total records in survey:", 'unescaped'));
            $sheet->write($xlsRow, 1, $total);
            if ($total) {
                ++$xlsRow;
                $sheet->write($xlsRow, 0, $statlang->gT("Percentage of total:", 'unescaped'));
                $sheet->write($xlsRow, 1, $percent . "%");
            }
            break;
        case 'pdf':
            // add summary to pdf
            $array = array();
            //$array[] = array($statlang->gT("Results"),"");
            $array[] = array($statlang->gT("Number of records in this query:", 'unescaped'), $results);
            $array[] = array($statlang->gT("Total records in survey:", 'unescaped'), $total);
            if ($total) {
                $array[] = array($statlang->gT("Percentage of total:", 'unescaped'), $percent . "%");
            }
            $pdf->addPage('P', 'A4');
            $pdf->Bookmark($pdf->delete_html($statlang->gT("Results", 'unescaped')), 0, 0);
            $pdf->titleintopdf($statlang->gT("Results", 'unescaped'), $statlang->gT("Survey", 'unescaped') . " " . $surveyid);
            $pdf->tableintopdf($array);
            $pdf->addPage('P', 'A4');
            break;
        case 'html':
            $statisticsoutput .= "<br />\n<table class='statisticssummary' >\n" . "\t<thead><tr><th colspan='2'>" . $statlang->gT("Results") . "</th></tr></thead>\n" . "\t<tr><th >" . $statlang->gT("Number of records in this query:") . '</th>' . "<td>{$results}</td></tr>\n" . "\t<tr><th>" . $statlang->gT("Total records in survey:") . '</th>' . "<td>{$total}</td></tr>\n";
            //only calculate percentage if $total is set
            if ($total) {
                $percent = sprintf("%01.2f", $results / $total * 100);
                $statisticsoutput .= "\t<tr><th align='right'>" . $statlang->gT("Percentage of total:") . '</th>' . "<td>{$percent}%</td></tr>\n";
            }
            $statisticsoutput .= "</table>\n";
            break;
        default:
            break;
    }
    //put everything from $selects array into a string connected by AND
    //This string ($sql) can then be passed on to other functions so you can
    //browse these results
    if (isset($selects) && $selects) {
        $sql = implode(" AND ", $selects);
    } elseif (!empty($newsql)) {
        $sql = $newsql;
    }
    if (!isset($sql) || !$sql) {
        $sql = "NULL";
    }
    //only continue if we have something to output
    if ($results > 0) {
        if ($outputType == 'html' && $browse === true) {
            //add a buttons to browse results
            $statisticsoutput .= "<form action='" . Yii::app()->getController()->createUrl("admin/responses/index/surveyid/{$surveyid}") . "' method='post' target='_blank'>\n" . "\t\t<p>" . "\t\t\t<input type='submit' value='" . $statlang->gT("Browse") . "'  />\n" . "\t\t\t<input type='hidden' name='sid' value='{$surveyid}' />\n" . "\t\t\t<input type='hidden' name='sql' value=\"{$sql}\" />\n" . "\t\t\t<input type='hidden' name='subaction' value='all' />\n" . "\t\t</p>" . "\t\t</form>\n";
        }
    }
    //end if (results > 0)
    /* Show Summary results
     * The $summary array contains each fieldname that we want to display statistics for
     *
     * */
    if (isset($summary) && $summary) {
        //let's run through the survey
        $runthrough = $summary;
        //START Chop up fieldname and find matching questions
        //loop through all selected questions
        foreach ($runthrough as $rt) {
            //Step 1: Get information about this response field (SGQA) for the summary
            $outputs = buildOutputList($rt, $language, $surveyid, $outputType, $sql, $statlang);
            $statisticsoutput .= $outputs['statisticsoutput'];
            //2. Collect and Display results #######################################################################
            if (isset($outputs['alist']) && $outputs['alist']) {
                $display = displayResults($outputs, $results, $rt, $outputType, $surveyid, $sql, $usegraph, $browse, $pdf, $statlang);
                $statisticsoutput .= $display['statisticsoutput'];
                $astatdata = array_merge($astatdata, $display['astatdata']);
            }
            //end if -> collect and display results
            //Delete Build Outputs data
            unset($outputs);
            unset($display);
        }
        // end foreach -> loop through all questions
        //output
        if ($outputType == 'html') {
            $statisticsoutput .= "<br />&nbsp;\n";
        }
    }
    //end if -> show summary results
    switch ($outputType) {
        case 'xls':
            $workbook->close();
            if ($pdfOutput == 'F') {
                return $sFileName;
            } else {
                return;
            }
            break;
        case 'pdf':
            $pdf->lastPage();
            if ($pdfOutput == 'F') {
                // This is only used by lsrc to send an E-Mail attachment, so it gives back the filename to send and delete afterwards
                $pdf->Output($tempdir . "/" . $statlang->gT('Survey') . '_' . $surveyid . "_" . $surveyInfo['surveyls_title'] . '.pdf', $pdfOutput);
                return $tempdir . "/" . $statlang->gT('Survey') . '_' . $surveyid . "_" . $surveyInfo['surveyls_title'] . '.pdf';
            } else {
                return $pdf->Output($statlang->gT('Survey') . '_' . $surveyid . "_" . $surveyInfo['surveyls_title'] . '.pdf', $pdfOutput);
            }
            break;
        case 'html':
            $statisticsoutput .= "<script type=\"text/javascript\" src=\"http://maps.googleapis.com/maps/api/js?sensor=false\"></script>\n" . "<script type=\"text/javascript\">var site_url='" . Yii::app()->baseUrl . "';var temppath='{$tempurl}';var imgpath='" . Yii::app()->getConfig('adminimageurl') . "';var aGMapData=" . ls_json_encode($agmapdata) . ";var aStatData=" . ls_json_encode($astatdata) . "</script>";
            return $statisticsoutput;
            break;
        default:
            return $statisticsoutput;
            break;
    }
}