1<?php if (!defined('BASEPATH')) {
2    exit('No direct script access allowed');
3}
4/*
5 * LimeSurvey
6 * Copyright (C) 2007-2011 The LimeSurvey Project Team / Carsten Schmitz
7 * All rights reserved.
8 * License: GNU/GPL License v2 or later, see LICENSE.php
9 * LimeSurvey is free software. This version may have been modified pursuant
10 * to the GNU General Public License, and as distributed it includes or
11 * is derivative of works licensed under the GNU General Public License or
12 * other free or open source software licenses.
13 * See COPYRIGHT.php for copyright notices and details.
14 *
15 */
16
17/**
18 * Statistics Controller
19 *
20 * This controller performs statistics actions
21 *
22 * @package        LimeSurvey
23 * @subpackage    Backend
24 */
25class statistics extends Survey_Common_Action
26{
27
28    function __construct($controller, $id)
29    {
30        parent::__construct($controller, $id);
31
32        Yii::app()->loadHelper("surveytranslator");
33    }
34
35    /**
36     * Constructor
37     */
38    public function run($surveyid = 0, $subaction = null)
39    {
40        $surveyid = sanitize_int($surveyid);
41        $imageurl = Yii::app()->getConfig("imageurl");
42        $aData = array('imageurl' => $imageurl);
43
44        /*
45         * We need this later:
46         *  1 - Array Dual Scale
47         *  5 - 5 Point Choice
48         *  A - Array (5 Point Choice)
49         *  B - Array (10 Point Choice)
50         *  C - Array (Yes/No/Uncertain)
51         *  D - Date
52         *  E - Array (Increase, Same, Decrease)
53         *  F - Array (Flexible Labels)
54         *  G - Gender
55         *  H - Array (Flexible Labels) by Column
56         *  I - Language Switch
57         *  K - Multiple Numerical Input
58         *  L - List (Radio)
59         *  M - Multiple choice
60         *  N - Numerical Input
61         *  O - List With Comment
62         *  P - Multiple choice with comments
63         *  Q - Multiple Short Text
64         *  R - Ranking
65         *  S - Short Free Text
66         *  T - Long Free Text
67         *  U - Huge Free Text
68         *  X - Boilerplate Question
69         *  Y - Yes/No
70         *  ! - List (Dropdown)
71         *  : - Array (Flexible Labels) multiple drop down
72         *  ; - Array (Flexible Labels) multiple texts
73         *  | - File Upload
74
75
76         Debugging help:
77         echo '<script language="javascript" type="text/javascript">alert("HI");</script>';
78         */
79
80        //split up results to extend statistics -> NOT WORKING YET! DO NOT ENABLE THIS!
81        $showcombinedresults = 0;
82
83        /*
84         * this variable is used in the function shortencode() which cuts off a question/answer title
85         * after $maxchars and shows the rest as tooltip
86         */
87        $maxchars = 50;
88
89        //we collect all the output within this variable
90        $statisticsoutput = '';
91
92        //output for chosing questions to cross query
93        $cr_statisticsoutput = '';
94
95        // This gets all the 'to be shown questions' from the POST and puts these into an array
96        $summary = returnGlobal('summary');
97        $statlang = returnGlobal('statlang');
98
99        //if $summary isn't an array we create one
100        if (isset($summary) && !is_array($summary)) {
101            $summary = explode("+", $summary);
102        }
103
104        //no survey ID? -> come and get one
105        if (!isset($surveyid)) {$surveyid = returnGlobal('sid'); }
106
107        //still no survey ID -> error
108        $aData['surveyid'] = $surveyid;
109
110
111        // Set language for questions and answers to base language of this survey
112        $language = Survey::model()->findByPk($surveyid)->language;
113        $aData['language'] = $language;
114
115
116        //Call the javascript file
117        App()->getClientScript()->registerScriptFile(App()->getConfig('adminscripts').'statistics.js', CClientScript::POS_BEGIN);
118        App()->getClientScript()->registerScriptFile(App()->getConfig('adminscripts').'json-js/json2.min.js');
119
120        yii::app()->clientScript->registerPackage('jszip');
121        $aData['display']['menu_bars']['browse'] = gT("Quick statistics");
122
123        //Select public language file
124        $row = Survey::model()->find('sid = :sid', array(':sid' => $surveyid));
125
126        /*
127         * check if there is a datestamp available for this survey
128         * yes -> $datestamp="Y"
129         * no -> $datestamp="N"
130         */
131        $datestamp = $row->datestamp;
132
133        // 1: Get list of questions from survey
134
135        /*
136         * We want to have the following data
137         * a) "questions" -> all table namens, e.g.
138         * qid
139         * sid
140         * gid
141         * type
142         * title
143         * question
144         * preg
145         * help
146         * other
147         * mandatory
148         * lid
149         * lid1
150         * question_order
151         * language
152         *
153         * b) "groups" -> group_name + group_order *
154         */
155
156        //store all the data in $rows
157        $rows = Question::model()->getQuestionList($surveyid, $language);
158
159        //SORT IN NATURAL ORDER!
160        usort($rows, 'groupOrderThenQuestionOrder');
161
162        //put the question information into the filter array
163        $filters = array();
164        $aGroups = array();
165        $keyone = 0;
166        foreach ($rows as $row) {
167            //store some column names in $filters array
168
169            $filters[] = array($row['qid'],
170            $row['gid'],
171            $row['type'],
172            $row['title'],
173            $row['group_name'],
174            flattenText($row['question']));
175
176            if (!in_array($row['group_name'], $aGroups)) {
177                //$aGroups[] = $row['group_name'];
178                $aGroups[$row['group_name']]['gid'] = $row['gid'];
179                $aGroups[$row['group_name']]['name'] = $row['group_name'];
180            }
181            $aGroups[$row['group_name']]['questions'][$keyone] = array($row['qid'],
182            $row['gid'],
183            $row['type'],
184            $row['title'],
185            $row['group_name'],
186            flattenText($row['question'])); ;
187            $keyone = $keyone + 1;
188        }
189        $aData['filters'] = $filters;
190        $aData['aGroups'] = $aGroups;
191
192        //var_dump($filters);
193        // SHOW ID FIELD
194
195        $grapherror = false;
196        $error = '';
197        $usegraph = (int) Yii::app()->request->getPost('usegraph', 0);
198        if (!function_exists("gd_info")) {
199            $grapherror = true;
200            $error .= '<br />'.gT('You do not have the GD Library installed. Showing charts requires the GD library to function properly.');
201            $error .= '<br />'.gT('visit http://us2.php.net/manual/en/ref.image.php for more information').'<br />';
202        } elseif (!function_exists("imageftbbox")) {
203            $grapherror = true;
204            $error .= '<br />'.gT('You do not have the Freetype Library installed. Showing charts requires the Freetype library to function properly.');
205            $error .= '<br />'.gT('visit http://us2.php.net/manual/en/ref.image.php for more information').'<br />';
206        }
207
208        if ($grapherror) {
209            $usegraph = 0;
210        }
211
212
213        //pre-selection of filter forms
214        if (incompleteAnsFilterState() == "complete") {
215            $selecthide = "selected='selected'";
216            $selectshow = "";
217            $selectinc = "";
218        } elseif (incompleteAnsFilterState() == "incomplete") {
219            $selecthide = "";
220            $selectshow = "";
221            $selectinc = "selected='selected'";
222        } else {
223            $selecthide = "";
224            $selectshow = "selected='selected'";
225            $selectinc = "";
226        }
227        $aData['selecthide'] = $selecthide;
228        $aData['selectshow'] = $selectshow;
229        $aData['selectinc'] = $selectinc;
230        $aData['error'] = $error;
231
232        $survlangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
233        $survlangs[] = Survey::model()->findByPk($surveyid)->language;
234        $aData['survlangs'] = $survlangs;
235        $aData['datestamp'] = $datestamp;
236
237        //if the survey contains timestamps you can filter by timestamp, too
238
239        //Output selector
240
241        //second row below options -> filter settings headline
242
243        $filterchoice_state = returnGlobal('filterchoice_state');
244        $aData['filterchoice_state'] = $filterchoice_state;
245
246
247        /*
248         * let's go through the filter array which contains
249         *     ['qid'],
250         ['gid'],
251         ['type'],
252         ['title'],
253         ['group_name'],
254         ['question'],
255         ['lid'],
256         ['lid1']);
257         */
258
259        $currentgroup = '';
260        $counter = 0;
261        foreach ($filters as $key1 => $flt) {
262            //is there a previous question type set?
263
264
265            /*
266             * remember: $flt is structured like this
267             *  ['qid'],
268             ['gid'],
269             ['type'],
270             ['title'],
271             ['group_name'],
272             ['question'],
273             ['lid'],
274             ['lid1']);
275             */
276
277            //SGQ identifier
278
279            //full question title
280
281            /*
282             * Check question type: This question types will be used (all others are separated in the if clause)
283             *  5 - 5 Point Choice
284             G - Gender
285             I - Language Switch
286             L - List (Radio)
287             M - Multiple choice
288             N - Numerical Input
289             | - File Upload
290             O - List With Comment
291             P - Multiple choice with comments
292             Y - Yes/No
293             ! - List (Dropdown) )
294             */
295
296
297            /////////////////////////////////////////////////////////////////////////////////////////////////
298            //This section presents the filter list, in various different ways depending on the question type
299            /////////////////////////////////////////////////////////////////////////////////////////////////
300
301            //let's switch through the question type for each question
302            switch ($flt[2]) {
303                case "K": // Multiple Numerical
304                    //get answers
305                    $result = Question::model()->getQuestionsForStatistics('title as code, question as answer', "parent_qid=$flt[0] AND language = '{$language}'", 'question_order');
306                    $aData['result'][$key1]['key1'] = $result;
307                    break;
308
309
310
311                case "Q": // Multiple Short Text
312
313                    //get subqestions
314                    $result = Question::model()->getQuestionsForStatistics('title as code, question as answer', "parent_qid=$flt[0] AND language = '{$language}'", 'question_order');
315                    $aData['result'][$key1] = $result;
316                    break;
317
318                    //----------------------- ARRAYS --------------------------
319
320                case "A": // ARRAY OF 5 POINT CHOICE QUESTIONS
321
322                    //get answers
323                    $result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid=$flt[0] AND language = '{$language}'", 'question_order');
324                    $aData['result'][$key1] = $result;
325                    break;
326
327
328
329                    //just like above only a different loop
330                case "B": // ARRAY OF 10 POINT CHOICE QUESTIONS
331                    $result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid=$flt[0] AND language = '{$language}'", 'question_order');
332                    $aData['result'][$key1] = $result;
333                    break;
334
335
336
337                case "C": // ARRAY OF YES\No\gT("Uncertain") QUESTIONS
338                    //get answers
339                    $result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid=$flt[0] AND language = '{$language}'", 'question_order');
340                    $aData['result'][$key1] = $result;
341                    break;
342
343
344
345                    //similiar to the above one
346                case "E": // ARRAY OF Increase/Same/Decrease QUESTIONS
347                    $result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid=$flt[0] AND language = '{$language}'", 'question_order');
348                    $aData['result'][$key1] = $result;
349                    break;
350
351                case ";":  //ARRAY (Multi Flex) (Text)
352                    $result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid=$flt[0] AND language = '{$language}' AND scale_id = 0", 'question_order');
353                    $aData['result'][$key1] = $result;
354                    foreach ($result as $key => $row) {
355                        $fresult = Question::model()->getQuestionsForStatistics('title, question', "parent_qid=$flt[0] AND language = '{$language}' AND scale_id = 1", 'question_order');
356                        $aData['fresults'][$key1][$key] = $fresult;
357                    }
358                    break;
359
360                case ":":  //ARRAY (Multi Flex) (Numbers)
361                    $result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid=$flt[0] AND language = '{$language}' AND scale_id = 0", 'question_order');
362                    $aData['result'][$key1] = $result;
363                    foreach ($result as $row) {
364                        $fresult = Question::model()->getQuestionsForStatistics('*', "parent_qid=$flt[0] AND language = '{$language}' AND scale_id = 1", 'question_order, title');
365                        $aData['fresults'][$key1] = $fresult;
366                    }
367                    break;
368                    /*
369                     * For question type "F" and "H" you can use labels.
370                     * The only difference is that the labels are applied to column heading
371                     * or rows respectively
372                     */
373                case "F": // FlEXIBLE ARRAY
374                case "H": // ARRAY (By Column)
375                    //Get answers. We always use the answer code because the label might be too long elsewise
376                    $result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid=$flt[0] AND language = '{$language}'", 'question_order');
377                    $aData['result'][$key1] = $result;
378
379                    //check all the answers
380                    foreach ($result as $row) {
381                        $fresult = Answer::model()->getQuestionsForStatistics('*', "qid=$flt[0] AND language = '{$language}'", 'sortorder, code');
382                        $aData['fresults'][$key1] = $fresult;
383                    }
384
385                    //$statisticsoutput .= "\t\t\t\t<td>\n";
386                    $counter = 0;
387                    break;
388
389
390
391                case "R": //RANKING
392                    //get some answers
393                    $result = Answer::model()->getQuestionsForStatistics('code, answer', "qid=$flt[0] AND language = '{$language}'", 'sortorder, answer');
394                    $aData['result'][$key1] = $result;
395                    break;
396
397                case "1": // MULTI SCALE
398
399                    //get answers
400                    $result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid=$flt[0] AND language = '{$language}'", 'question_order');
401                    $aData['result'][$key1] = $result;
402                    //loop through answers
403                    foreach ($result as $key => $row) {
404
405                        //check if there is a dualscale_headerA/B
406                        $dshresult = QuestionAttribute::model()->getQuestionsForStatistics('value', "qid=$flt[0] AND attribute = 'dualscale_headerA'", '');
407                        $aData['dshresults'][$key1][$key] = $dshresult;
408
409
410                        $fresult = Answer::model()->getQuestionsForStatistics('*', "qid=$flt[0] AND language = '{$language}' AND scale_id = 0", 'sortorder, code');
411
412                        $aData['fresults'][$key1][$key] = $fresult;
413
414
415                        $dshresult2 = QuestionAttribute::model()->getQuestionsForStatistics('value', "qid=$flt[0] AND attribute = 'dualscale_headerB'", '');
416                        $aData['dshresults2'][$key1][$key] = $dshresult2;
417                    }
418                    break;
419
420                case "P":  //P - Multiple choice with comments
421                case "M":  //M - Multiple choice
422
423                    //get answers
424                    $result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid = $flt[0] AND language = '$language'", 'question_order');
425                    $aData['result'][$key1] = $result;
426                    break;
427
428
429                    /*
430                     * This question types use the default settings:
431                     *     L - List (Radio)
432                     O - List With Comment
433                     P - Multiple choice with comments
434                     ! - List (Dropdown)
435                     */
436                default:
437
438                    //get answers
439                    $result = Answer::model()->getQuestionsForStatistics('code, answer', "qid=$flt[0] AND language = '$language'", 'sortorder, answer');
440                    $aData['result'][$key1] = $result;
441                    break;
442
443            }    //end switch -> check question types and create filter forms
444
445            $currentgroup = $flt[1];
446
447            $counter++;
448
449            //temporary save the type of the previous question
450            //used to adjust linebreaks
451            $previousquestiontype = $flt[2];
452
453        }
454
455        // ----------------------------------- END FILTER FORM ---------------------------------------
456
457        Yii::app()->loadHelper('admin/statistics');
458        $helper = new statistics_helper();
459        $showtextinline = (int) Yii::app()->request->getPost('showtextinline', 0);
460        $aData['showtextinline'] = $showtextinline;
461        $aData['usegraph'] = $usegraph;
462
463        //Show Summary results
464        if (isset($summary) && $summary) {
465            $outputType = Yii::app()->request->getPost('outputtype', 'html');
466            switch ($outputType) {
467                case 'html':
468                    $statisticsoutput .= $helper->generate_html_chartjs_statistics($surveyid, $summary, $summary, $usegraph, $outputType, 'DD', $statlang);
469                    break;
470                case 'pdf':
471                    $helper->generate_statistics($surveyid, $summary, $summary, $usegraph, $outputType, 'D', $statlang);
472                    exit;
473                    break;
474                case 'xls':
475                    $helper->generate_statistics($surveyid, $summary, $summary, $usegraph, $outputType, 'DD', $statlang);
476                    exit;
477                    break;
478                default:
479                    break;
480            }
481
482        }    //end if -> show summary results
483
484        $aData['sStatisticsLanguage'] = $statlang;
485        $aData['output'] = $statisticsoutput;
486        $aData['summary'] = $summary;
487
488
489        $error = '';
490        if (!function_exists("gd_info")) {
491            $error .= '<br />'.gT('You do not have the GD Library installed. Showing charts requires the GD library to function properly.');
492            $error .= '<br />'.gT('visit http://us2.php.net/manual/en/ref.image.php for more information').'<br />';
493        } else if (!function_exists("imageftbbox")) {
494            $error .= '<br />'.gT('You do not have the Freetype Library installed. Showing charts requires the Freetype library to function properly.');
495            $error .= '<br />'.gT('visit http://us2.php.net/manual/en/ref.image.php for more information').'<br />';
496        }
497
498        $aData['error'] = $error;
499        $aData['oStatisticsHelper'] = $helper;
500        $aData['fresults'] = (isset($aData['fresults'])) ? $aData['fresults'] : false;
501        $aData['dateformatdetails'] = getDateFormatData(Yii::app()->session['dateformat']);
502
503        if (!isset($aData['result'])) {
504            $aData['result'] = null;
505        }
506
507        $this->_renderWrappedTemplate('export', 'statistics_view', $aData);
508
509    }
510
511
512    /**
513     *  Returns a simple list of values in a particular column, that meet the requirements of the SQL
514     */
515    function listcolumn($surveyid, $column, $sortby = "", $sortmethod = "", $sorttype = "")
516    {
517        Yii::app()->loadHelper('admin/statistics');
518        $helper = new statistics_helper();
519        $aData['data'] = $helper->_listcolumn($surveyid, $column, $sortby, $sortmethod, $sorttype);
520        $aData['surveyid'] = $surveyid;
521        $aData['column'] = $column;
522        $aData['sortby'] = $sortby;
523        $aData['sortmethod'] = $sortmethod;
524        $aData['sorttype'] = $sorttype;
525        App()->getClientScript()->reset();
526        $this->getController()->render('export/statistics_browse_view', $aData);
527    }
528
529
530    function graph()
531    {
532        Yii::app()->loadHelper('admin/statistics');
533        Yii::app()->loadHelper("surveytranslator");
534
535        // Initialise PCHART
536        require_once(Yii::app()->basePath.'/third_party/pchart/pChart.class.php');
537        require_once(Yii::app()->basePath.'/third_party/pchart/pData.class.php');
538        require_once(Yii::app()->basePath.'/third_party/pchart/pCache.class.php');
539
540        Yii::import('application.third_party.ar-php.Arabic', true);
541
542        $tempdir = Yii::app()->getConfig("tempdir");
543        $MyCache = new pCache($tempdir.'/');
544        $aData['success'] = 1;
545        $sStatisticsLanguage = sanitize_languagecode($_POST['sStatisticsLanguage']);
546
547        if (isset($_POST['cmd']) && isset($_POST['id'])) {
548            $sQCode = $_POST['id'];
549            if (!is_numeric(substr($sQCode, 0, 1))) {
550                // Strip first char when not numeric (probably T or D)
551                $sQCode = substr($sQCode, 1);
552            }
553            list($qsid, $qgid, $qqid) = explode("X", substr($sQCode, 0), 3);
554            $survey = Survey::model()->findByPk($qsid);
555
556            $aFieldmap = createFieldMap($survey, 'full', false, false, $sStatisticsLanguage);
557            $qtype = $aFieldmap[$sQCode]['type'];
558            $qqid = $aFieldmap[$sQCode]['qid'];
559            $aattr = QuestionAttribute::model()->getQuestionAttributes($qqid);
560            $field = substr($_POST['id'], 1);
561
562            switch ($_POST['cmd']) {
563                case 'showmap':
564                    if (isset($aattr['location_mapservice'])) {
565
566                        $aData['mapdata'] = array(
567                            "coord" => getQuestionMapData($field, $qsid),
568                            "zoom" => $aattr['location_mapzoom'],
569                            "width" => $aattr['location_mapwidth'],
570                            "height" => $aattr['location_mapheight']
571                        );
572                        QuestionAttribute::model()->setQuestionAttribute($qqid, 'statistics_showmap', 1);
573                    } else {
574                        $aData['success'] = 0;
575                    }
576                    break;
577                case 'hidemap':
578                    if (isset($aattr['location_mapservice'])) {
579                        $aData['success'] = 1;
580                        QuestionAttribute::model()->setQuestionAttribute($qqid, 'statistics_showmap', 0);
581                    } else {
582                        $aData['success'] = 0;
583                    }
584                    break;
585                case 'showgraph':
586                    if (isset($aattr['location_mapservice'])) {
587                        $aData['mapdata'] = array(
588                            "coord" => getQuestionMapData($field, $qsid),
589                            "zoom" => $aattr['location_mapzoom'],
590                            "width" => $aattr['location_mapwidth'],
591                            "height" => $aattr['location_mapheight']
592                        );
593                    }
594
595                    $bChartType = $qtype != "M" && $qtype != "P" && $aattr["statistics_graphtype"] == "1";
596                    $adata = Yii::app()->session['stats'][$_POST['id']];
597                    $aData['chartdata'] = createChart($qqid, $qsid, $bChartType, $adata['lbl'], $adata['gdata'], $adata['grawdata'], $MyCache, $sStatisticsLanguage, $qtype);
598
599
600                    QuestionAttribute::model()->setQuestionAttribute($qqid, 'statistics_showgraph', 1);
601                    break;
602                case 'hidegraph':
603                    QuestionAttribute::model()->setQuestionAttribute($qqid, 'statistics_showgraph', 0);
604                    break;
605                case 'showbar':
606                    if ($qtype == "M" || $qtype == "P") {
607                        $aData['success'] = 0;
608                        break;
609                    }
610
611                    QuestionAttribute::model()->setQuestionAttribute($qqid, 'statistics_graphtype', 0);
612
613                    $adata = Yii::app()->session['stats'][$_POST['id']];
614
615                    $aData['chartdata'] = createChart($qqid, $qsid, 0, $adata['lbl'], $adata['gdata'], $adata['grawdata'], $MyCache, $sStatisticsLanguage, $qtype);
616
617                    break;
618                case 'showpie':
619
620                    if ($qtype == "M" || $qtype == "P") {
621                        $aData['success'] = 0;
622                        break;
623                    }
624
625                    QuestionAttribute::model()->setQuestionAttribute($qqid, 'statistics_graphtype', 1);
626
627                    $adata = Yii::app()->session['stats'][$_POST['id']];
628                    $aData['chartdata'] = createChart($qqid, $qsid, 1, $adata['lbl'], $adata['gdata'], $adata['grawdata'], $MyCache, $sStatisticsLanguage, $qtype);
629
630
631                    break;
632                default:
633                    $aData['success'] = 0;
634                    break;
635            }
636        } else {
637            $aData['success'] = 0;
638        }
639
640        //$this->_renderWrappedTemplate('export', 'statistics_graph_view', $aData);
641        $this->getController()->renderPartial('export/statistics_graph_view', $aData);
642    }
643
644    /**
645     * Render satistics for users
646     */
647        public function simpleStatistics($surveyid)
648        {
649            $usegraph = 1;
650            $iSurveyId = sanitize_int($surveyid);
651            $aData['surveyid'] = $iSurveyId;
652            $showcombinedresults = 0;
653            $maxchars = 50;
654            $statisticsoutput = '';
655            $cr_statisticsoutput = '';
656
657            // Set language for questions and answers to base language of this survey
658            $language = Survey::model()->findByPk($surveyid)->language;
659            $summary = array();
660            $summary[0] = "datestampE";
661            $summary[1] = "datestampG";
662            $summary[2] = "datestampL";
663            $summary[3] = "idG";
664            $summary[4] = "idL";
665
666            // 1: Get list of questions from survey
667            $rows = Question::model()->getQuestionList($surveyid, $language);
668
669            //SORT IN NATURAL ORDER!
670            usort($rows, 'groupOrderThenQuestionOrder');
671
672        // The questions to display (all question)
673        foreach ($rows as $row) {
674            $type = $row['type'];
675            if ($type == "T" || $type == "N") {
676                $summary[] = $type.$iSurveyId.'X'.$row['gid'].'X'.$row['qid'];
677            }
678            switch ($type) {
679
680                // Double scale cases
681                case ":":
682                    $qidattributes = QuestionAttribute::model()->getQuestionAttributes($row['qid']);
683                    if (!$qidattributes['input_boxes']) {
684                        $qid = $row['qid'];
685                        $results = Question::model()->getQuestionsForStatistics('*', "parent_qid='$qid' AND language = '{$language}' AND scale_id = 0", 'question_order, title');
686                        $fresults = Question::model()->getQuestionsForStatistics('*', "parent_qid='$qid' AND language = '{$language}' AND scale_id = 1", 'question_order, title');
687                        foreach ($results as $row1) {
688                            foreach ($fresults as $row2) {
689                                $summary[] = $iSurveyId.'X'.$row['gid'].'X'.$row['qid'].$row1['title'].'_'.$row2['title'];
690                            }
691                        }
692                    }
693                break;
694
695                case "1":
696                    $qid = $row['qid'];
697                    $results = Question::model()->getQuestionsForStatistics('*', "parent_qid='$qid' AND language = '{$language}'", 'question_order, title');
698                    foreach ($results as $row1) {
699                        $summary[] = $iSurveyId.'X'.$row['gid'].'X'.$row['qid'].$row1['title'].'#0';
700                        $summary[] = $iSurveyId.'X'.$row['gid'].'X'.$row['qid'].$row1['title'].'#1';
701                    }
702
703                break;
704
705                case "R": //RANKING
706                    $qid = $row['qid'];
707                    $results = Question::model()->getQuestionsForStatistics('title, question', "parent_qid='$qid' AND language = '{$language}'", 'question_order');
708                    $count = count($results);
709                    //loop through all answers. if there are 3 items to rate there will be 3 statistics
710                    for ($i = 1; $i <= $count; $i++) {
711                        $summary[] = $type.$iSurveyId.'X'.$row['gid'].'X'.$row['qid'].'-'.$i;
712                    }
713                break;
714
715                // Cases with subquestions
716                case "A":
717                case "F": // FlEXIBLE ARRAY
718                case "H": // ARRAY (By Column)
719                case "E":
720                case "B":
721                case "C":
722                    //loop through all answers. if there are 3 items to rate there will be 3 statistics
723                    $qid = $row['qid'];
724                    $results = Question::model()->getQuestionsForStatistics('title, question', "parent_qid='$qid' AND language = '{$language}'", 'question_order');
725                    foreach ($results as $row1) {
726                        $summary[] = $iSurveyId.'X'.$row['gid'].'X'.$row['qid'].$row1['title'];
727                    }
728                break;
729
730                // Cases with subanwsers, need a question type as first letter
731                case "P":  //P - Multiple choice with comments
732                case "M":  //M - Multiple choice
733                case "S":
734                    $summary[] = $type.$iSurveyId.'X'.$row['gid'].'X'.$row['qid'];
735                break;
736
737                // Not shown (else would only show 'no answer' )
738                case "K":
739                case "*":
740                case "D":
741                case "T": // Long free text
742                case "U": // Huge free text
743                case "|": // File Upload, we don't show it
744                case "N":
745                case "Q":
746                case ';':
747
748                    break;
749
750
751                default:
752                    $summary[] = $iSurveyId.'X'.$row['gid'].'X'.$row['qid'];
753                break;
754            }
755        }
756
757
758        // ----------------------------------- END FILTER FORM ---------------------------------------
759
760        Yii::app()->loadHelper('admin/statistics');
761        $helper = new statistics_helper();
762        $showtextinline = (int) Yii::app()->request->getPost('showtextinline', 0);
763        $aData['showtextinline'] = $showtextinline;
764
765        //Show Summary results
766        $aData['usegraph'] = $usegraph;
767        $outputType = 'html';
768        $statlang = returnGlobal('statlang');
769        $statisticsoutput .= $helper->generate_simple_statistics($surveyid, $summary, $summary, $usegraph, $outputType, 'DD', $statlang);
770
771        $aData['sStatisticsLanguage'] = $statlang;
772        $aData['output'] = $statisticsoutput;
773        $aData['summary'] = $summary;
774        $aData['oStatisticsHelper'] = $helper;
775        $aData['menu']['expertstats'] = true;
776
777        //Call the javascript file
778        App()->getClientScript()->registerScriptFile(App()->getConfig('adminscripts').'statistics.js', CClientScript::POS_BEGIN);
779        App()->getClientScript()->registerScriptFile(App()->getConfig('adminscripts').'json-js/json2.min.js');
780        yii::app()->clientScript->registerPackage('jspdf');
781        yii::app()->clientScript->registerPackage('jszip');
782        echo $this->_renderWrappedTemplate('export', 'statistics_user_view', $aData);
783        }
784
785
786    public function setIncompleteanswers()
787    {
788        $sIncompleteAnswers = Yii::app()->request->getPost('state');
789        if (in_array($sIncompleteAnswers, array('all', 'complete', 'incomplete'))) {
790            Yii::app()->session['incompleteanswers'] = $sIncompleteAnswers;
791        }
792
793    }
794
795    /**
796     * Renders template(s) wrapped in header and footer
797     *
798     * @param string $sAction Current action, the folder to fetch views from
799     * @param string $aViewUrls View url(s)
800     * @param array $aData Data to be passed on. Optional.
801     */
802    protected function _renderWrappedTemplate($sAction = 'export', $aViewUrls = array(), $aData = array(), $sRenderFile = false)
803    {
804        yii::app()->clientScript->registerPackage('bootstrap-switch');
805        yii::app()->clientScript->registerPackage('jspdf');
806        $oSurvey = Survey::model()->findByPk($aData['surveyid']);
807
808        $aData['menu']['closeurl'] = Yii::app()->request->getUrlReferrer(Yii::app()->createUrl("/admin/survey/sa/view/surveyid/".$aData['surveyid']));
809
810        $aData['display'] = array();
811        $aData['display']['menu_bars'] = false;
812        $aData['display']['menu_bars']['browse'] = gT('Browse responses'); // browse is independent of the above
813        $aData['menu']['edition'] = true;
814        $aData['menu']['stats'] = true;
815        $aData['menu']['close'] = true;
816        $aData['sidemenu']['state'] = false;
817        $iSurveyId = $aData['surveyid'];
818        $aData['title_bar']['title'] = gT('Browse responses').': '.$oSurvey->currentLanguageSettings->surveyls_title;
819        $aData['subaction'] = gT('Statistics');
820        parent::_renderWrappedTemplate($sAction, $aViewUrls, $aData, $sRenderFile);
821    }
822
823
824}
825