Esempio n. 1
0
 /**
  * RPC routine to export statistics of a survey to a user.
  * Returns string - base64 encoding of the statistics.
  *
  * @access public
  * @param string $sSessionKey Auth credentials
  * @param int $iSurveyID Id of the Survey
  * @param string $docType Type of documents the exported statistics should be
  * @param string $sLanguage Optional language of the survey to use
  * @param string $graph Create graph option
  * @return string Base64 encoded string with the statistics file
  */
 public function export_statistics($sSessionKey, $iSurveyID, $docType = 'pdf', $sLanguage = null, $graph = '0')
 {
     Yii::app()->loadHelper('admin/statistics');
     $tempdir = Yii::app()->getConfig("tempdir");
     if (!$this->_checkSessionKey($sSessionKey)) {
         return array('status' => 'Invalid session key');
     }
     $oSurvey = Survey::model()->findByPk($iSurveyID);
     if (!isset($oSurvey)) {
         return array('status' => 'Error: Invalid survey ID');
     }
     if (Survey::model()->findByPk($iSurveyID)->owner_id != $_SESSION['loginID']) {
         return array('status' => 'Error: No Permission');
     }
     $aAdditionalLanguages = array_filter(explode(" ", $oSurvey->additional_languages));
     if (is_null($sLanguage) || !in_array($sLanguage, $aAdditionalLanguages)) {
         $sLanguage = $oSurvey->language;
     }
     $oAllQuestions = Questions::model()->findAllByAttributes(array('sid' => $iSurveyID, 'parent_qid' => '0', 'language' => $sLanguage));
     $aSummary = createCompleteSGQA($iSurveyID, $oAllQuestions, $sLanguage);
     switch ($docType) {
         case 'pdf':
             $sTempFile = generate_statistics($iSurveyID, $aSummary, $aSummary, $graph, $docType, 'F', $sLanguage);
             $sResult = file_get_contents($sTempFile);
             unlink($sTempFile);
             break;
         case 'xls':
             $sTempFile = generate_statistics($iSurveyID, $aSummary, $aSummary, '0', $docType, 'F', $sLanguage);
             $sResult = file_get_contents($sTempFile);
             unlink($sTempFile);
             break;
         case 'html':
             $sResult = generate_statistics($iSurveyID, $aSummary, $aSummary, '0', $docType, 'DD', $sLanguage);
             break;
     }
     return base64_encode($sResult);
 }
Esempio n. 2
0
/**
 *
 * Enter description here...
 * @param $sUser Limesurvey user
 * @param $sPass Password
 * @param $iVid	surveyid
 * @param $email e-mail adress of the recipient
 * @param $docType pdf, xls or html
 * @param $graph with 1 it includes graphs in pdf files
 * @return "OK" or SoapFault
 */
function fSendStatistic($sUser, $sPass, $iVid, $email, $docType = 'pdf', $graph = '0')
{
    global $connect;
    global $dbprefix;
    $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
    include "lsrc.config.php";
    $lsrcHelper = new lsrcHelper();
    // Check if all mandatory parameters are present, else abort...
    if (!is_int($iVid) || $iVid == 0 || $email == '') {
        throw new SoapFault("Server: ", "Mandatory Parameters missing");
        exit;
    }
    if (!$lsrcHelper->checkUser($sUser, $sPass)) {
        throw new SoapFault("Authentication: ", "User or password wrong");
        exit;
    }
    if ($lsrcHelper->getSurveyOwner($iVid) != $_SESSION['loginID'] && !$_SESSION['USER_RIGHT_SUPERADMIN'] == '1') {
        throw new SoapFault("Authentication: ", "You have no right to send statistics from other peoples Surveys");
        exit;
    }
    if (!$lsrcHelper->surveyExists($iVid)) {
        throw new SoapFault("Database: ", "Survey {$iVid} does not exists");
        exit;
    }
    $lsrcHelper->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ",sid={$iVid} email={$email} doctype={$docType} graph={$graph} START OK ");
    /**
     * Build up the fields to generate statistics from
     */
    $summarySql = " SELECT gid, lid, qid, type " . " FROM {$dbprefix}questions " . " WHERE sid={$surveyid} ";
    $summaryRs = $connect->Execute($summarySql);
    $lsrcHelper->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ",sid={$iVid} OK ");
    foreach ($summaryRs as $field) {
        $myField = $surveyid . "X" . $field['gid'] . "X" . $field['qid'];
        // Multiple choice get special treatment
        if ($field['type'] == "M" || $field['type'] == "P") {
            $myField = "M{$myField}";
        }
        //numerical input will get special treatment (arihtmetic mean, standard derivation, ...)
        if ($field['type'] == "N") {
            $myField = "N{$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") {
            $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
            //Get answers. We always use the answer code because the label might be too long elsewise
            $query = "SELECT code, answer FROM " . db_table_name("answers") . " WHERE qid='" . $field['qid'] . "' AND language='{$language}' ORDER BY sortorder, answer";
            $result = $connect->Execute($query) or safe_die("Couldn't get answers!<br />{$query}<br />" . $connect->ErrorMsg());
            $counter2 = 0;
            //check all the answers
            while ($row = $result->FetchRow()) {
                $myField = "{$myField}{$row[0]}";
            }
            //$myField = "{$surveyid}X{$flt[1]}X{$flt[0]}{$row[0]}[]";
        }
        $summary[] = $myField;
    }
    //$lsrcHelper->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.",".print_r($summary)." ");
    switch ($docType) {
        case 'pdf':
            $tempFile = generate_statistics($iVid, $summary, 'all', $graph, $docType, 'F');
            if ($lsrcHelper->sendStatistic($iVid, $email, $tempFile)) {
                unlink($tempFile);
                return 'PDF send';
            } else {
                unlink($tempFile);
                throw new SoapFault("Mail System", "Mail could not be send! Check LimeSurveys E-Mail Settings.");
                exit;
            }
            break;
        case 'xls':
            $tempFile = generate_statistics($iVid, $summary, 'all', 0, $docType, 'F');
            if ($lsrcHelper->sendStatistic($iVid, $email, $tempFile)) {
                unlink($tempFile);
                return 'XLS send';
            } else {
                unlink($tempFile);
                throw new SoapFault("Mail System", "Mail could not be send! Check LimeSurveys E-Mail Settings.");
                exit;
            }
            break;
        case 'html':
            $html = generate_statistics($iVid, $summary, 'all', 0, $docType, 'F');
            if ($lsrcHelper->sendStatistic($iVid, $email, null, $html)) {
                return 'HTML send';
            } else {
                throw new SoapFault("Mail System", "Mail could not be send! Check LimeSurveys E-Mail Settings.");
                exit;
            }
            break;
    }
}
Esempio n. 3
0
if (isset($summary) && $summary) {
    //"Generating Summaries ..." is shown above the progress bar
    $prb->setLabelValue('txt1', $clang->gT('Generating summaries ...'));
    $prb->moveStep($process_status);
    //let's run through the survey // Fixed bug 3053 with array_unique
    $runthrough = array_unique($summary);
    //loop through all selected questions
    foreach ($runthrough as $rt) {
        //update progress bar
        if ($process_status < 100) {
            $process_status++;
        }
        $prb->moveStep($process_status);
    }
    // end foreach -> loop through all questions
    $statisticsoutput .= generate_statistics($surveyid, $summary, $summary, $publicgraphs, 'html', null, $language, false);
    //output
    $statisticsoutput .= "<br />\n" . "</div>\n";
}
//end if -> show summary results
//done! set progress bar to 100%
if (isset($prb)) {
    $prb->setLabelValue('txt1', $clang->gT('Completed'));
    $prb->moveStep(100);
    $prb->hide();
}
//output everything:
echo $statisticsoutput;
//output footer
echo getFooter();
//Delete all Session Data
Esempio n. 4
0
    if (isset($_POST['usegraph'])) {
        $usegraph = 1;
    } else {
        $usegraph = 0;
    }
    include_once "statistics_function.php";
    $outputType = $_POST['outputtype'];
    switch ($outputType) {
        case 'html':
            $statisticsoutput .= generate_statistics($surveyid, $summary, $summary, $usegraph, $outputType, 'DD', $statlang);
            break;
        case 'pdf':
            generate_statistics($surveyid, $summary, $summary, $usegraph, $outputType, 'DD', $statlang);
            break;
        case 'xls':
            generate_statistics($surveyid, $summary, $summary, $usegraph, $outputType, 'DD', $statlang);
            break;
        default:
            break;
    }
    //print_r($summary); exit;
}
//end if -> show summary results
function showSpeaker($hinttext)
{
    global $clang, $imagefiles, $maxchars;
    if (!isset($maxchars)) {
        $maxchars = 100;
    }
    $htmlhinttext = str_replace("'", '&#039;', $hinttext);
    //the string is already HTML except for single quotes so we just replace these only
 function actionAction($surveyid, $language)
 {
     $iSurveyID = (int) $surveyid;
     //$postlang = returnglobal('lang');
     Yii::import('application.libraries.admin.progressbar', true);
     Yii::app()->loadHelper("admin/statistics");
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('surveytranslator');
     $data = array();
     //XXX enable/disable this for testing
     //$publicgraphs = 1;
     //$showaggregateddata = 1;
     /*
      * List of important settings:
      * - publicstatistics: General survey setting which determines if public statistics for this survey
      * 	 should be shown at all.
      *
      * - publicgraphs: General survey setting which determines if public statistics for this survey
      * 	 should include graphs or only show a tabular overview.
      *
      * - public_statistics: Question attribute which has to be applied to each question so that
      * 	 its statistics will be shown to the user. If not set no statistics for this question will be shown.
      *
      * - filterout_incomplete_answers: Setting taken from config-defaults.php which determines if
      * 	 not completed answers will be filtered.
      */
     if (!isset($iSurveyID)) {
         $iSurveyID = returnGlobal('sid');
     } else {
         $iSurveyID = (int) $iSurveyID;
     }
     if (!$iSurveyID) {
         //This next line ensures that the $iSurveyID value is never anything but a number.
         safeDie('You have to provide a valid survey ID.');
     }
     if ($iSurveyID) {
         $actresult = Survey::model()->findAll('sid = :sid AND active = :active', array(':sid' => $iSurveyID, ':active' => 'Y'));
         //Checked
         if (count($actresult) == 0) {
             safeDie('You have to provide a valid survey ID.');
         } else {
             $surveyinfo = getSurveyInfo($iSurveyID);
             // CHANGE JSW_NZ - let's get the survey title for display
             $thisSurveyTitle = $surveyinfo["name"];
             // CHANGE JSW_NZ - let's get css from individual template.css - so define path
             $thisSurveyCssPath = getTemplateURL($surveyinfo["template"]);
             if ($surveyinfo['publicstatistics'] != 'Y') {
                 safeDie('The public statistics for this survey are deactivated.');
             }
             //check if graphs should be shown for this survey
             if ($surveyinfo['publicgraphs'] == 'Y') {
                 $publicgraphs = 1;
             } else {
                 $publicgraphs = 0;
             }
         }
     }
     //we collect all the output within this variable
     $statisticsoutput = '';
     //for creating graphs we need some more scripts which are included here
     //True -> include
     //False -> forget about charts
     if (isset($publicgraphs) && $publicgraphs == 1) {
         require_once APPPATH . 'third_party/pchart/pchart/pChart.class';
         require_once APPPATH . 'third_party/pchart/pchart/pData.class';
         require_once APPPATH . 'third_party/pchart/pchart/pCache.class';
         $MyCache = new pCache(Yii::app()->getConfig("tempdir") . '/');
         //$currentuser is created as prefix for pchart files
         if (isset($_SERVER['REDIRECT_REMOTE_USER'])) {
             $currentuser = $_SERVER['REDIRECT_REMOTE_USER'];
         } else {
             if (session_id()) {
                 $currentuser = substr(session_id(), 0, 15);
             } else {
                 $currentuser = "******";
             }
         }
     }
     // Set language for questions and labels to base language of this survey
     if (isset($postlang) && $postlang != null) {
         $language = $postlang;
     } else {
         $language = Survey::model()->findByPk($iSurveyID)->language;
     }
     $chartfontfile = Yii::app()->getConfig("chartfontfile");
     //pick the best font file if font setting is 'auto'
     if ($chartfontfile == 'auto') {
         $chartfontfile = 'vera.ttf';
         if ($language == 'ar') {
             $chartfontfile = 'KacstOffice.ttf';
         } elseif ($language == 'fa') {
             $chartfontfile = 'KacstFarsi.ttf';
         }
     }
     //set survey language for translations
     $clang = SetSurveyLanguage($iSurveyID, $language);
     //Create header (fixes bug #3097)
     $surveylanguage = $language;
     sendCacheHeaders();
     $condition = false;
     $header = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" . "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"" . $surveylanguage . "\" lang=\"" . $surveylanguage . "\"";
     if (getLanguageRTL($surveylanguage)) {
         $condition = true;
         $header .= " dir=\"rtl\" ";
     }
     $sitename = Yii::app()->getConfig("sitename");
     $data['surveylanguage'] = $surveylanguage;
     $data['sitename'] = $sitename;
     $data['condition'] = $condition;
     $data['thisSurveyCssPath'] = $thisSurveyCssPath;
     /*
      * only show questions where question attribute "public_statistics" is set to "1"
      */
     $query = "SELECT q.* , group_name, group_order FROM {{questions}} q, {{groups}} g, {{question_attributes}} qa \n                    WHERE g.gid = q.gid AND g.language = :lang AND q.language = :lang AND q.sid = :surveyid AND q.qid = qa.qid AND q.parent_qid = 0 AND qa.attribute = 'public_statistics'";
     $databasetype = Yii::app()->db->getDriverName();
     if ($databasetype == 'mssql' || $databasetype == "sqlsrv") {
         $query .= "AND CAST(CAST(qa.value as varchar) as int)='1'\n";
     } else {
         $query .= "AND qa.value='1'\n";
     }
     //execute query
     $result = Yii::app()->db->createCommand($query)->bindParam(":lang", $language, PDO::PARAM_STR)->bindParam(":surveyid", $iSurveyID, PDO::PARAM_INT)->queryAll();
     //store all the data in $rows
     $rows = $result;
     //SORT IN NATURAL ORDER!
     usort($rows, 'groupOrderThenQuestionOrder');
     //put the question information into the filter array
     foreach ($rows as $row) {
         //store some column names in $filters array
         $filters[] = array($row['qid'], $row['gid'], $row['type'], $row['title'], $row['group_name'], flattenText($row['question']));
     }
     //number of records for this survey
     $totalrecords = 0;
     //count number of answers
     $query = "SELECT count(*) FROM {{survey_" . intval($iSurveyID) . "}}";
     //if incompleted answers should be filtert submitdate has to be not null
     //this setting is taken from config-defaults.php
     if (Yii::app()->getConfig("filterout_incomplete_answers") == true) {
         $query .= " WHERE {{survey_" . intval($iSurveyID) . "}}.submitdate is not null";
     }
     $result = Yii::app()->db->createCommand($query)->queryAll();
     //$totalrecords = total number of answers
     foreach ($result as $row) {
         $totalrecords = reset($row);
     }
     //this is the array which we need later...
     $summary = array();
     //...while this is the array from copy/paste which we don't want to replace because this is a nasty source of error
     $allfields = array();
     //---------- CREATE SGQA OF ALL QUESTIONS WHICH USE "PUBLIC_STATISTICS" ----------
     /*
     		 * let's go through the filter array which contains
     		 * 	['qid'],
     		 ['gid'],
     		 ['type'],
     		 ['title'],
     		 ['group_name'],
     		 ['question'];
     */
     $currentgroup = '';
     // use to check if there are any question with public statistics
     if (isset($filters)) {
         foreach ($filters as $flt) {
             //SGQ identifier
             $myfield = "{$iSurveyID}X{$flt[1]}X{$flt[0]}";
             //let's switch through the question type for each question
             switch ($flt[2]) {
                 case "K":
                     // Multiple Numerical
                 // Multiple Numerical
                 case "Q":
                     // Multiple Short Text
                     //get answers
                     $query = "SELECT title as code, question as answer FROM {{questions}} WHERE parent_qid=:flt_0 AND language = :lang ORDER BY question_order";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $language, PDO::PARAM_STR)->queryAll();
                     //go through all the (multiple) answers
                     foreach ($result as $row) {
                         $myfield2 = $flt[2] . $myfield . reset($row);
                         $allfields[] = $myfield2;
                     }
                     break;
                 case "A":
                     // ARRAY OF 5 POINT CHOICE QUESTIONS
                 // ARRAY OF 5 POINT CHOICE QUESTIONS
                 case "B":
                     // ARRAY OF 10 POINT CHOICE QUESTIONS
                 // ARRAY OF 10 POINT CHOICE QUESTIONS
                 case "C":
                     // ARRAY OF YES\No\$clang->gT("Uncertain") QUESTIONS
                 // ARRAY OF YES\No\$clang->gT("Uncertain") QUESTIONS
                 case "E":
                     // ARRAY OF Increase/Same/Decrease QUESTIONS
                 // ARRAY OF Increase/Same/Decrease QUESTIONS
                 case "F":
                     // FlEXIBLE ARRAY
                 // FlEXIBLE ARRAY
                 case "H":
                     // ARRAY (By Column)
                     //get answers
                     $query = "SELECT title as code, question as answer FROM {{questions}} WHERE parent_qid=:flt_0 AND language = :lang ORDER BY question_order";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $language, PDO::PARAM_STR)->queryAll();
                     //go through all the (multiple) answers
                     foreach ($result as $row) {
                         $myfield2 = $myfield . reset($row);
                         $allfields[] = $myfield2;
                     }
                     break;
                     // all "free text" types (T, U, S)  get the same prefix ("T")
                 // all "free text" types (T, U, S)  get the same prefix ("T")
                 case "T":
                     // Long free text
                 // Long free text
                 case "U":
                     // Huge free text
                 // Huge free text
                 case "S":
                     // Short free text
                     $myfield = "T{$myfield}";
                     $allfields[] = $myfield;
                     break;
                 case ";":
                     //ARRAY (Multi Flex) (Text)
                 //ARRAY (Multi Flex) (Text)
                 case ":":
                     //ARRAY (Multi Flex) (Numbers)
                     $query = "SELECT title, question FROM {{questions}} WHERE parent_qid=:flt_0 AND language=:lang AND scale_id = 0 ORDER BY question_order";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $language, PDO::PARAM_STR)->queryAll();
                     foreach ($result as $row) {
                         $fquery = "SELECT * FROM {{questions}} WHERE parent_qid = :flt_0 AND language = :lang AND scale_id = 1 ORDER BY question_order, title";
                         $fresult = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $language, PDO::PARAM_STR)->queryAll();
                         foreach ($fresult as $frow) {
                             $myfield2 = $myfield . reset($row) . "_" . $frow['title'];
                             $allfields[] = $myfield2;
                         }
                     }
                     break;
                 case "R":
                     //RANKING
                     //get some answers
                     $query = "SELECT code, answer FROM {{answers}} WHERE qid = :flt_0 AND language = :lang ORDER BY sortorder, answer";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $language, PDO::PARAM_STR)->queryAll();
                     //get number of answers
                     $count = count($result);
                     //loop through all answers. if there are 3 items to rate there will be 3 statistics
                     for ($i = 1; $i <= $count; $i++) {
                         $myfield2 = "R" . $myfield . $i . "-" . strlen($i);
                         $allfields[] = $myfield2;
                     }
                     break;
                     //Boilerplate questions are only used to put some text between other questions -> no analysis needed
                 //Boilerplate questions are only used to put some text between other questions -> no analysis needed
                 case "X":
                     //This is a boilerplate question and it has no business in this script
                     break;
                 case "1":
                     // MULTI SCALE
                     //get answers
                     $query = "SELECT title, question FROM {{questions}} WHERE parent_qid = :flt_0 AND language = :lang ORDER BY question_order";
                     $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $language, PDO::PARAM_STR)->queryAll();
                     //loop through answers
                     foreach ($result as $row) {
                         //----------------- LABEL 1 ---------------------
                         $myfield2 = $myfield . $row['title'] . "#0";
                         $allfields[] = $myfield2;
                         //----------------- LABEL 2 ---------------------
                         $myfield2 = $myfield . $row['title'] . "#1";
                         $allfields[] = $myfield2;
                     }
                     //end WHILE -> loop through all answers
                     break;
                 case "P":
                     //P - Multiple choice with comments
                 //P - Multiple choice with comments
                 case "M":
                     //M - Multiple choice
                 //M - Multiple choice
                 case "N":
                     //N - Numerical input
                 //N - Numerical input
                 case "D":
                     //D - Date
                     $myfield2 = $flt[2] . $myfield;
                     $allfields[] = $myfield2;
                     break;
                 default:
                     //Default settings
                     $allfields[] = $myfield;
                     break;
             }
             //end switch -> check question types and create filter forms
         }
         //end foreach -> loop through all questions with "public_statistics" enabled
     }
     // end if -> for removing the error message in case there are no filters
     $summary = $allfields;
     //---------- CREATE STATISTICS ----------
     //some progress bar stuff
     // Create progress bar which is shown while creating the results
     $prb = new ProgressBar();
     $prb->pedding = 2;
     // Bar Pedding
     $prb->brd_color = "#404040 #dfdfdf #dfdfdf #404040";
     // Bar Border Color
     $prb->setFrame();
     // set ProgressBar Frame
     $prb->frame['left'] = 50;
     // Frame position from left
     $prb->frame['top'] = 80;
     // Frame position from top
     $prb->addLabel('text', 'txt1', $clang->gT("Please wait ..."));
     // add Text as Label 'txt1' and value 'Please wait'
     $prb->addLabel('percent', 'pct1');
     // add Percent as Label 'pct1'
     $prb->addButton('btn1', $clang->gT('Go back'), '?action=statistics&amp;sid=' . $iSurveyID);
     // add Button as Label 'btn1' and action '?restart=1'
     //progress bar starts with 35%
     $process_status = 35;
     $prb->show();
     // show the ProgressBar
     // 1: Get list of questions with answers chosen
     //"Getting Questions and Answers ..." is shown above the bar
     $prb->setLabelValue('txt1', $clang->gT('Getting questions and answers ...'));
     $prb->moveStep(5);
     // creates array of post variable names
     for (reset($_POST); $key = key($_POST); next($_POST)) {
         $postvars[] = $key;
     }
     $data['thisSurveyTitle'] = $thisSurveyTitle;
     $data['totalrecords'] = $totalrecords;
     $data['clang'] = $clang;
     $data['summary'] = $summary;
     //show some main data at the beginnung
     // CHANGE JSW_NZ - let's allow html formatted questions to show
     //push progress bar from 35 to 40
     $process_status = 40;
     //Show Summary results
     if (isset($summary) && $summary) {
         //"Generating Summaries ..." is shown above the progress bar
         $prb->setLabelValue('txt1', $clang->gT('Generating summaries ...'));
         $prb->moveStep($process_status);
         //let's run through the survey // Fixed bug 3053 with array_unique
         $runthrough = array_unique($summary);
         //loop through all selected questions
         foreach ($runthrough as $rt) {
             //update progress bar
             if ($process_status < 100) {
                 $process_status++;
             }
             $prb->moveStep($process_status);
         }
         // end foreach -> loop through all questions
         $statisticsoutput .= generate_statistics($iSurveyID, $summary, $summary, $publicgraphs, 'html', null, $language, false);
     }
     //end if -> show summary results
     $data['statisticsoutput'] = $statisticsoutput;
     //done! set progress bar to 100%
     if (isset($prb)) {
         $prb->setLabelValue('txt1', $clang->gT('Completed'));
         $prb->moveStep(100);
         $prb->hide();
     }
     // Get the survey inforamtion
     $thissurvey = getSurveyInfo($surveyid, $language);
     //SET THE TEMPLATE DIRECTORY
     if (!isset($thissurvey['templatedir']) || !$thissurvey['templatedir']) {
         $data['sTemplatePath'] = validateTemplateDir("default");
     } else {
         $data['sTemplatePath'] = validateTemplateDir($thissurvey['templatedir']);
     }
     header_includes('statistics_user.js');
     $this->render('/statistics_user_view', $data);
     //output footer
     echo getFooter();
     //Delete all Session Data
     Yii::app()->session['finished'] = true;
 }
Esempio n. 6
0
 /**
  * Constructor
  */
 public function run($surveyid = 0, $subaction = null)
 {
     $surveyid = sanitize_int($surveyid);
     //TODO: Convert question types to views
     $clang = $this->getController()->lang;
     $imageurl = Yii::app()->getConfig("imageurl");
     $aData = array('clang' => $clang, 'imageurl' => $imageurl);
     $aData['sql'] = '';
     /*
     * We need this later:
     *  1 - Array Dual Scale
     *  5 - 5 Point Choice
     *  A - Array (5 Point Choice)
     *  B - Array (10 Point Choice)
     *  C - Array (Yes/No/Uncertain)
     *  D - Date
     *  E - Array (Increase, Same, Decrease)
     *  F - Array (Flexible Labels)
     *  G - Gender
     *  H - Array (Flexible Labels) by Column
     *  I - Language Switch
     *  K - Multiple Numerical Input
     *  L - List (Radio)
     *  M - Multiple choice
     *  N - Numerical Input
     *  O - List With Comment
     *  P - Multiple choice with comments
     *  Q - Multiple Short Text
     *  R - Ranking
     *  S - Short Free Text
     *  T - Long Free Text
     *  U - Huge Free Text
     *  X - Boilerplate Question
     *  Y - Yes/No
     *  ! - List (Dropdown)
     *  : - Array (Flexible Labels) multiple drop down
     *  ; - Array (Flexible Labels) multiple texts
     *  | - File Upload
     
     
     Debugging help:
     echo '<script language="javascript" type="text/javascript">alert("HI");</script>';
     */
     //split up results to extend statistics -> NOT WORKING YET! DO NOT ENABLE THIS!
     $showcombinedresults = 0;
     /*
      * this variable is used in the function shortencode() which cuts off a question/answer title
      * after $maxchars and shows the rest as tooltip
      */
     $maxchars = 50;
     //we collect all the output within this variable
     $statisticsoutput = '';
     //output for chosing questions to cross query
     $cr_statisticsoutput = '';
     // This gets all the 'to be shown questions' from the POST and puts these into an array
     $summary = returnGlobal('summary');
     $statlang = returnGlobal('statlang');
     //if $summary isn't an array we create one
     if (isset($summary) && !is_array($summary)) {
         $summary = explode("+", $summary);
     }
     //no survey ID? -> come and get one
     if (!isset($surveyid)) {
         $surveyid = returnGlobal('sid');
     }
     //still no survey ID -> error
     $aData['surveyid'] = $surveyid;
     // Set language for questions and answers to base language of this survey
     $language = Survey::model()->findByPk($surveyid)->language;
     $aData['language'] = $language;
     //Call the javascript file
     $this->getController()->_js_admin_includes(Yii::app()->getConfig('adminscripts') . 'statistics.js');
     $aData['display']['menu_bars']['browse'] = $clang->gT("Quick statistics");
     //Select public language file
     $row = Survey::model()->find('sid = :sid', array(':sid' => $surveyid));
     /*
      * check if there is a datestamp available for this survey
      * yes -> $datestamp="Y"
      * no -> $datestamp="N"
      */
     $datestamp = $row->datestamp;
     // 1: Get list of questions from survey
     /*
      * We want to have the following data
      * a) "questions" -> all table namens, e.g.
      * qid
      * sid
      * gid
      * type
      * title
      * question
      * preg
      * help
      * other
      * mandatory
      * lid
      * lid1
      * question_order
      * language
      *
      * b) "groups" -> group_name + group_order *
      */
     //store all the data in $rows
     $rows = Questions::model()->getQuestionList($surveyid, $language);
     //SORT IN NATURAL ORDER!
     usort($rows, 'groupOrderThenQuestionOrder');
     //put the question information into the filter array
     $filters = array();
     foreach ($rows as $row) {
         //store some column names in $filters array
         $filters[] = array($row['qid'], $row['gid'], $row['type'], $row['title'], $row['group_name'], flattenText($row['question']));
     }
     $aData['filters'] = $filters;
     //var_dump($filters);
     // SHOW ID FIELD
     $grapherror = false;
     $error = '';
     if (!function_exists("gd_info")) {
         $grapherror = true;
         $error .= '<br />' . $clang->gT('You do not have the GD Library installed. Showing charts requires the GD library to function properly.');
         $error .= '<br />' . $clang->gT('visit http://us2.php.net/manual/en/ref.image.php for more information') . '<br />';
     } elseif (!function_exists("imageftbbox")) {
         $grapherror = true;
         $error .= '<br />' . $clang->gT('You do not have the Freetype Library installed. Showing charts requires the Freetype library to function properly.');
         $error .= '<br />' . $clang->gT('visit http://us2.php.net/manual/en/ref.image.php for more information') . '<br />';
     }
     if ($grapherror) {
         unset($_POST['usegraph']);
     }
     //pre-selection of filter forms
     if (incompleteAnsFilterState() == "filter") {
         $selecthide = "selected='selected'";
         $selectshow = "";
         $selectinc = "";
     } elseif (incompleteAnsFilterState() == "inc") {
         $selecthide = "";
         $selectshow = "";
         $selectinc = "selected='selected'";
     } else {
         $selecthide = "";
         $selectshow = "selected='selected'";
         $selectinc = "";
     }
     $aData['selecthide'] = $selecthide;
     $aData['selectshow'] = $selectshow;
     $aData['selectinc'] = $selectinc;
     $aData['error'] = $error;
     $survlangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
     $survlangs[] = Survey::model()->findByPk($surveyid)->language;
     $aData['survlangs'] = $survlangs;
     $aData['datestamp'] = $datestamp;
     //if the survey contains timestamps you can filter by timestamp, too
     //Output selector
     //second row below options -> filter settings headline
     $filterchoice_state = returnGlobal('filterchoice_state');
     $aData['filterchoice_state'] = $filterchoice_state;
     /*
     * let's go through the filter array which contains
     * 	['qid'],
     ['gid'],
     ['type'],
     ['title'],
     ['group_name'],
     ['question'],
     ['lid'],
     ['lid1']);
     */
     $currentgroup = '';
     $counter = 0;
     foreach ($filters as $key1 => $flt) {
         //is there a previous question type set?
         /*
         * remember: $flt is structured like this
         *  ['qid'],
         ['gid'],
         ['type'],
         ['title'],
         ['group_name'],
         ['question'],
         ['lid'],
         ['lid1']);
         */
         //SGQ identifier
         //full question title
         /*
         * Check question type: This question types will be used (all others are separated in the if clause)
         *  5 - 5 Point Choice
         G - Gender
         I - Language Switch
         L - List (Radio)
         M - Multiple choice
         N - Numerical Input
         | - File Upload
         O - List With Comment
         P - Multiple choice with comments
         Y - Yes/No
         ! - List (Dropdown) )
         */
         /////////////////////////////////////////////////////////////////////////////////////////////////
         //This section presents the filter list, in various different ways depending on the question type
         /////////////////////////////////////////////////////////////////////////////////////////////////
         //let's switch through the question type for each question
         switch ($flt[2]) {
             case "K":
                 // Multiple Numerical
                 //get answers
                 $result = Questions::model()->getQuestionsForStatistics('title as code, question as answer', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order');
                 $aData['result'][$key1]['key1'] = $result;
                 break;
             case "Q":
                 // Multiple Short Text
                 //get subqestions
                 $result = Questions::model()->getQuestionsForStatistics('title as code, question as answer', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order');
                 $aData['result'][$key1] = $result;
                 break;
                 //----------------------- ARRAYS --------------------------
             //----------------------- ARRAYS --------------------------
             case "A":
                 // ARRAY OF 5 POINT CHOICE QUESTIONS
                 //get answers
                 $result = Questions::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order');
                 $aData['result'][$key1] = $result;
                 break;
                 //just like above only a different loop
             //just like above only a different loop
             case "B":
                 // ARRAY OF 10 POINT CHOICE QUESTIONS
                 $result = Questions::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order');
                 $aData['result'][$key1] = $result;
                 break;
             case "C":
                 // ARRAY OF YES\No\$clang->gT("Uncertain") QUESTIONS
                 //get answers
                 $result = Questions::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order');
                 $aData['result'][$key1] = $result;
                 break;
                 //similiar to the above one
             //similiar to the above one
             case "E":
                 // ARRAY OF Increase/Same/Decrease QUESTIONS
                 $result = Questions::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order');
                 $aData['result'][$key1] = $result;
                 break;
             case ";":
                 //ARRAY (Multi Flex) (Text)
                 $result = Questions::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}' AND scale_id = 0", 'question_order');
                 $aData['result'][$key1] = $result;
                 foreach ($result as $key => $row) {
                     $fresult = Questions::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}' AND scale_id = 1", 'question_order');
                     $aData['fresults'][$key1][$key] = $fresult;
                 }
                 break;
             case ":":
                 //ARRAY (Multi Flex) (Numbers)
                 $result = Questions::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}' AND scale_id = 0", 'question_order');
                 $aData['result'][$key1] = $result;
                 foreach ($result as $row) {
                     $fresult = Questions::model()->getQuestionsForStatistics('*', "parent_qid={$flt['0']} AND language = '{$language}' AND scale_id = 1", 'question_order, title');
                     $aData['fresults'][$key1] = $fresult;
                 }
                 break;
                 /*
                  * For question type "F" and "H" you can use labels.
                  * The only difference is that the labels are applied to column heading
                  * or rows respectively
                  */
             /*
              * For question type "F" and "H" you can use labels.
              * The only difference is that the labels are applied to column heading
              * or rows respectively
              */
             case "F":
                 // FlEXIBLE ARRAY
             // FlEXIBLE ARRAY
             case "H":
                 // ARRAY (By Column)
                 //Get answers. We always use the answer code because the label might be too long elsewise
                 $result = Questions::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order');
                 $aData['result'][$key1] = $result;
                 //check all the answers
                 foreach ($result as $row) {
                     $fresult = Answers::model()->getQuestionsForStatistics('*', "qid={$flt['0']} AND language = '{$language}'", 'sortorder, code');
                     $aData['fresults'][$key1] = $fresult;
                 }
                 //$statisticsoutput .= "\t\t\t\t<td>\n";
                 $counter = 0;
                 break;
             case "R":
                 //RANKING
                 //get some answers
                 $result = Answers::model()->getQuestionsForStatistics('code, answer', "qid={$flt['0']} AND language = '{$language}'", 'sortorder, answer');
                 $aData['result'][$key1] = $result;
                 break;
             case "1":
                 // MULTI SCALE
                 //get answers
                 $result = Questions::model()->getQuestionsForStatistics('title, question', "parent_qid={$flt['0']} AND language = '{$language}'", 'question_order');
                 $aData['result'][$key1] = $result;
                 //loop through answers
                 foreach ($result as $key => $row) {
                     //check if there is a dualscale_headerA/B
                     $dshresult = Question_attributes::model()->getQuestionsForStatistics('value', "qid={$flt['0']} AND attribute = 'dualscale_headerA'", '');
                     $aData['dshresults'][$key1][$key] = $dshresult;
                     $fresult = Answers::model()->getQuestionsForStatistics('*', "qid={$flt['0']} AND language = '{$language}' AND scale_id = 0", 'sortorder, code');
                     $aData['fresults'][$key1][$key] = $fresult;
                     $dshresult2 = Question_attributes::model()->getQuestionsForStatistics('value', "qid={$flt['0']} AND attribute = 'dualscale_headerB'", '');
                     $aData['dshresults2'][$key1][$key] = $dshresult2;
                 }
                 break;
             case "P":
                 //P - Multiple choice with comments
             //P - Multiple choice with comments
             case "M":
                 //M - Multiple choice
                 //get answers
                 $result = Questions::model()->getQuestionsForStatistics('title, question', "parent_qid = {$flt['0']} AND language = '{$language}'", 'question_order');
                 $aData['result'][$key1] = $result;
                 break;
                 /*
                 * This question types use the default settings:
                 * 	L - List (Radio)
                 O - List With Comment
                 P - Multiple choice with comments
                 ! - List (Dropdown)
                 */
             /*
             * This question types use the default settings:
             * 	L - List (Radio)
             O - List With Comment
             P - Multiple choice with comments
             ! - List (Dropdown)
             */
             default:
                 //get answers
                 $result = Answers::model()->getQuestionsForStatistics('code, answer', "qid={$flt['0']} AND language = '{$language}'", 'sortorder, answer');
                 $aData['result'][$key1] = $result;
                 break;
         }
         //end switch -> check question types and create filter forms
         $currentgroup = $flt[1];
         $counter++;
         //temporary save the type of the previous question
         //used to adjust linebreaks
         $previousquestiontype = $flt[2];
     }
     // ----------------------------------- END FILTER FORM ---------------------------------------
     Yii::app()->loadHelper('admin/statistics');
     $showtextinline = isset($_POST['showtextinline']) ? 1 : 0;
     $aData['showtextinline'] = $showtextinline;
     //Show Summary results
     if (isset($summary) && $summary) {
         $usegraph = isset($_POST['usegraph']) ? 1 : 0;
         $aData['usegraph'] = $usegraph;
         $outputType = $_POST['outputtype'];
         switch ($outputType) {
             case 'html':
                 $statisticsoutput .= generate_statistics($surveyid, $summary, $summary, $usegraph, $outputType, 'DD', $statlang);
                 break;
             case 'pdf':
                 generate_statistics($surveyid, $summary, $summary, $usegraph, $outputType, 'I', $statlang);
                 exit;
                 break;
             case 'xls':
                 generate_statistics($surveyid, $summary, $summary, $usegraph, $outputType, 'DD', $statlang);
                 exit;
                 break;
             default:
                 break;
         }
     }
     //end if -> show summary results
     $aData['sStatisticsLanguage'] = $statlang;
     $aData['output'] = $statisticsoutput;
     $aData['summary'] = $summary;
     $this->_renderWrappedTemplate('export', 'statistics_view', $aData);
 }