PageRenderTime 62ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 0ms

/application/controllers/Statistics_userController.php

https://bitbucket.org/sammousa/valuematchbv-ls2
PHP | 465 lines | 273 code | 75 blank | 117 comment | 30 complexity | 03b376a50cc8459787714b8a8a972972 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, BSD-3-Clause, GPL-3.0, LGPL-3.0
  1. <?php
  2. /*
  3. * LimeSurvey
  4. * Copyright (C) 2007-2011 The LimeSurvey Project Team / Carsten Schmitz
  5. * All rights reserved.
  6. * License: GNU/GPL License v2 or later, see LICENSE.php
  7. * LimeSurvey is free software. This version may have been modified pursuant
  8. * to the GNU General Public License, and as distributed it includes or
  9. * is derivative of works licensed under the GNU General Public License or
  10. * other free or open source software licenses.
  11. * See COPYRIGHT.php for copyright notices and details.
  12. *
  13. * $Id$
  14. */
  15. /*
  16. * Created 12-2008 by Maziminke (maziminke@web.de)
  17. *
  18. * This file handles the "Show results to users" option:
  19. * Survey Settings -> Presentation & navigation -> "Public statistics?"
  20. *
  21. * The admin can set a question attribute "public_statistics" for each question
  22. * to determine whether the results of a certain question should be shown to the user
  23. * after he/she has submitted the survey.
  24. *
  25. * See http://docs.limesurvey.org/tiki-index.php?page=Question+attributes#public_statistics
  26. */
  27. class Statistics_userController extends LSYii_Controller {
  28. public function _remap($method, $params = array())
  29. {
  30. array_unshift($params, $method);
  31. return call_user_func_array(array($this, "action"), $params);
  32. }
  33. function actionAction($surveyid,$language)
  34. {
  35. $iSurveyID=(int)$surveyid;
  36. //$postlang = returnglobal('lang');
  37. Yii::import('application.libraries.admin.progressbar',true);
  38. Yii::app()->loadHelper("admin/statistics");
  39. Yii::app()->loadHelper('database');
  40. Yii::app()->loadHelper('surveytranslator');
  41. $data = array();
  42. //XXX enable/disable this for testing
  43. //$publicgraphs = 1;
  44. //$showaggregateddata = 1;
  45. /*
  46. * List of important settings:
  47. * - publicstatistics: General survey setting which determines if public statistics for this survey
  48. * should be shown at all.
  49. *
  50. * - publicgraphs: General survey setting which determines if public statistics for this survey
  51. * should include graphs or only show a tabular overview.
  52. *
  53. * - public_statistics: Question attribute which has to be applied to each question so that
  54. * its statistics will be shown to the user. If not set no statistics for this question will be shown.
  55. *
  56. * - filterout_incomplete_answers: Setting taken from config-defaults.php which determines if
  57. * not completed answers will be filtered.
  58. */
  59. if(!isset($iSurveyID))
  60. {
  61. $iSurveyID=returnGlobal('sid');
  62. }
  63. else
  64. {
  65. $iSurveyID = (int) $iSurveyID;
  66. }
  67. if (!$iSurveyID)
  68. {
  69. //This next line ensures that the $iSurveyID value is never anything but a number.
  70. safeDie('You have to provide a valid survey ID.');
  71. }
  72. if ($iSurveyID)
  73. {
  74. $actresult = Survey::model()->findAll('sid = :sid AND active = :active', array(':sid' => $iSurveyID, ':active' => 'Y')); //Checked
  75. if (count($actresult) == 0)
  76. {
  77. safeDie('You have to provide a valid survey ID.');
  78. }
  79. else
  80. {
  81. $surveyinfo = getSurveyInfo($iSurveyID);
  82. // CHANGE JSW_NZ - let's get the survey title for display
  83. $thisSurveyTitle = $surveyinfo["name"];
  84. // CHANGE JSW_NZ - let's get css from individual template.css - so define path
  85. $thisSurveyCssPath = getTemplateURL($surveyinfo["template"]);
  86. if ($surveyinfo['publicstatistics']!='Y')
  87. {
  88. safeDie('The public statistics for this survey are deactivated.');
  89. }
  90. //check if graphs should be shown for this survey
  91. if ($surveyinfo['publicgraphs']=='Y')
  92. {
  93. $publicgraphs = 1;
  94. }
  95. else
  96. {
  97. $publicgraphs = 0;
  98. }
  99. }
  100. }
  101. //we collect all the output within this variable
  102. $statisticsoutput ='';
  103. //for creating graphs we need some more scripts which are included here
  104. //True -> include
  105. //False -> forget about charts
  106. if (isset($publicgraphs) && $publicgraphs == 1)
  107. {
  108. require_once(APPPATH.'third_party/pchart/pchart/pChart.class');
  109. require_once(APPPATH.'third_party/pchart/pchart/pData.class');
  110. require_once(APPPATH.'third_party/pchart/pchart/pCache.class');
  111. $MyCache = new pCache(Yii::app()->getConfig("tempdir").DIRECTORY_SEPARATOR);
  112. //$currentuser is created as prefix for pchart files
  113. if (isset($_SERVER['REDIRECT_REMOTE_USER']))
  114. {
  115. $currentuser=$_SERVER['REDIRECT_REMOTE_USER'];
  116. }
  117. else if (session_id())
  118. {
  119. $currentuser=substr(session_id(), 0, 15);
  120. }
  121. else
  122. {
  123. $currentuser="standard";
  124. }
  125. }
  126. // Set language for questions and labels to base language of this survey
  127. if (isset($postlang) && $postlang != null )
  128. $language = $postlang;
  129. else
  130. $language = Survey::model()->findByPk($iSurveyID)->language;
  131. //set survey language for translations
  132. $clang = SetSurveyLanguage($iSurveyID, $language);
  133. //Create header (fixes bug #3097)
  134. $surveylanguage= $language;
  135. sendCacheHeaders();
  136. $condition = false;
  137. $sitename = Yii::app()->getConfig("sitename");
  138. $data['surveylanguage'] = $surveylanguage;
  139. $data['sitename'] = $sitename;
  140. $data['condition'] = $condition;
  141. $data['thisSurveyCssPath'] = $thisSurveyCssPath;
  142. /*
  143. * only show questions where question attribute "public_statistics" is set to "1"
  144. */
  145. $query = "SELECT q.* , group_name, group_order FROM {{questions}} q, {{groups}} g, {{question_attributes}} qa
  146. WHERE g.gid = q.gid AND g.language = :lang1 AND q.language = :lang2 AND q.sid = :surveyid AND q.qid = qa.qid AND q.parent_qid = 0 AND qa.attribute = 'public_statistics'";
  147. $databasetype = Yii::app()->db->getDriverName();
  148. if ($databasetype=='mssql' || $databasetype=="sqlsrv")
  149. {
  150. $query .=" AND CAST(CAST(qa.value as varchar) as int)='1'\n";
  151. }
  152. else
  153. {
  154. $query .=" AND qa.value='1'\n";
  155. }
  156. //execute query
  157. $result = Yii::app()->db->createCommand($query)->bindParam(":lang1", $language, PDO::PARAM_STR)->bindParam(":lang2", $language, PDO::PARAM_STR)->bindParam(":surveyid", $iSurveyID, PDO::PARAM_INT)->queryAll();
  158. //store all the data in $rows
  159. $rows = $result;
  160. //SORT IN NATURAL ORDER!
  161. usort($rows, 'groupOrderThenQuestionOrder');
  162. //put the question information into the filter array
  163. foreach ($rows as $row)
  164. {
  165. //store some column names in $filters array
  166. $filters[]=array($row['qid'],
  167. $row['gid'],
  168. $row['type'],
  169. $row['title'],
  170. $row['group_name'],
  171. flattenText($row['question']));
  172. }
  173. //number of records for this survey
  174. $totalrecords = 0;
  175. //count number of answers
  176. $query = "SELECT count(*) FROM {{survey_".intval($iSurveyID)."}}";
  177. //if incompleted answers should be filtert submitdate has to be not null
  178. //this setting is taken from config-defaults.php
  179. if (Yii::app()->getConfig("filterout_incomplete_answers") == true)
  180. {
  181. $query .= " WHERE {{survey_".intval($iSurveyID)."}}.submitdate is not null";
  182. }
  183. $result = Yii::app()->db->createCommand($query)->queryAll();
  184. //$totalrecords = total number of answers
  185. foreach($result as $row)
  186. {
  187. $totalrecords = reset($row);
  188. }
  189. //this is the array which we need later...
  190. $summary = array();
  191. //...while this is the array from copy/paste which we don't want to replace because this is a nasty source of error
  192. $allfields = array();
  193. //---------- CREATE SGQA OF ALL QUESTIONS WHICH USE "PUBLIC_STATISTICS" ----------
  194. /*
  195. * let's go through the filter array which contains
  196. * ['qid'],
  197. ['gid'],
  198. ['type'],
  199. ['title'],
  200. ['group_name'],
  201. ['question'];
  202. */
  203. $currentgroup='';
  204. // use to check if there are any question with public statistics
  205. if(isset($filters)){
  206. foreach ($filters as $flt)
  207. {
  208. //SGQ identifier
  209. $myfield = "{$iSurveyID}X{$flt[1]}X{$flt[0]}";
  210. //let's switch through the question type for each question
  211. switch ($flt[2])
  212. {
  213. case "K": // Multiple Numerical
  214. case "Q": // Multiple Short Text
  215. //get answers
  216. $query = "SELECT title as code, question as answer FROM {{questions}} WHERE parent_qid=:flt_0 AND language = :lang ORDER BY question_order";
  217. $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $language, PDO::PARAM_STR)->queryAll();
  218. //go through all the (multiple) answers
  219. foreach($result as $row)
  220. {
  221. $myfield2=$flt[2].$myfield.reset($row);
  222. $allfields[] = $myfield2;
  223. }
  224. break;
  225. case "A": // ARRAY OF 5 POINT CHOICE QUESTIONS
  226. case "B": // ARRAY OF 10 POINT CHOICE QUESTIONS
  227. case "C": // ARRAY OF YES\No\$clang->gT("Uncertain") QUESTIONS
  228. case "E": // ARRAY OF Increase/Same/Decrease QUESTIONS
  229. case "F": // FlEXIBLE ARRAY
  230. case "H": // ARRAY (By Column)
  231. //get answers
  232. $query = "SELECT title as code, question as answer FROM {{questions}} WHERE parent_qid=:flt_0 AND language = :lang ORDER BY question_order";
  233. $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $language, PDO::PARAM_STR)->queryAll();
  234. //go through all the (multiple) answers
  235. foreach($result as $row)
  236. {
  237. $myfield2 = $myfield.reset($row);
  238. $allfields[]=$myfield2;
  239. }
  240. break;
  241. // all "free text" types (T, U, S) get the same prefix ("T")
  242. case "T": // Long free text
  243. case "U": // Huge free text
  244. case "S": // Short free text
  245. $myfield="T$myfield";
  246. $allfields[] = $myfield;
  247. break;
  248. case ";": //ARRAY (Multi Flex) (Text)
  249. case ":": //ARRAY (Multi Flex) (Numbers)
  250. $query = "SELECT title, question FROM {{questions}} WHERE parent_qid=:flt_0 AND language=:lang AND scale_id = 0 ORDER BY question_order";
  251. $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $language, PDO::PARAM_STR)->queryAll();
  252. foreach($result as $row)
  253. {
  254. $fquery = "SELECT * FROM {{questions}} WHERE parent_qid = :flt_0 AND language = :lang AND scale_id = 1 ORDER BY question_order, title";
  255. $fresult = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $language, PDO::PARAM_STR)->queryAll();
  256. foreach($fresult as $frow)
  257. {
  258. $myfield2 = $myfield . reset($row) . "_" . $frow['title'];
  259. $allfields[]=$myfield2;
  260. }
  261. }
  262. break;
  263. case "R": //RANKING
  264. //get some answers
  265. $query = "SELECT code, answer FROM {{answers}} WHERE qid = :flt_0 AND language = :lang ORDER BY sortorder, answer";
  266. $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $language, PDO::PARAM_STR)->queryAll();
  267. //get number of answers
  268. $count = count($result);
  269. //loop through all answers. if there are 3 items to rate there will be 3 statistics
  270. for ($i=1; $i<=$count; $i++)
  271. {
  272. $myfield2 = "R" . $myfield . $i . "-" . strlen($i);
  273. $allfields[]=$myfield2;
  274. }
  275. break;
  276. //Boilerplate questions are only used to put some text between other questions -> no analysis needed
  277. case "X": //This is a boilerplate question and it has no business in this script
  278. break;
  279. case "1": // MULTI SCALE
  280. //get answers
  281. $query = "SELECT title, question FROM {{questions}} WHERE parent_qid = :flt_0 AND language = :lang ORDER BY question_order";
  282. $result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $language, PDO::PARAM_STR)->queryAll();
  283. //loop through answers
  284. foreach($result as $row)
  285. {
  286. //----------------- LABEL 1 ---------------------
  287. $myfield2 = $myfield . $row['title']."#0";
  288. $allfields[]=$myfield2;
  289. //----------------- LABEL 2 ---------------------
  290. $myfield2 = $myfield . $row['title']."#1";
  291. $allfields[]=$myfield2;
  292. } //end WHILE -> loop through all answers
  293. break;
  294. case "P": //P - Multiple choice with comments
  295. case "M": //M - Multiple choice
  296. case "N": //N - Numerical input
  297. case "D": //D - Date
  298. $myfield2 = $flt[2].$myfield;
  299. $allfields[]=$myfield2;
  300. break;
  301. default: //Default settings
  302. $allfields[] = $myfield;
  303. break;
  304. } //end switch -> check question types and create filter forms
  305. }
  306. //end foreach -> loop through all questions with "public_statistics" enabled
  307. }// end if -> for removing the error message in case there are no filters
  308. $summary = $allfields;
  309. // Get the survey inforamtion
  310. $thissurvey = getSurveyInfo($surveyid,$language);
  311. //SET THE TEMPLATE DIRECTORY
  312. if (!isset($thissurvey['templatedir']) || !$thissurvey['templatedir'])
  313. {
  314. $data['sTemplatePath'] = validateTemplateDir("default");
  315. }
  316. else
  317. {
  318. $data['sTemplatePath'] = validateTemplateDir($thissurvey['templatedir']);
  319. }
  320. //---------- CREATE STATISTICS ----------
  321. $redata = compact(array_keys(get_defined_vars()));
  322. doHeader();
  323. echo templatereplace(file_get_contents(getTemplatePath(validateTemplateDir($data['sTemplatePath'])).DIRECTORY_SEPARATOR."startpage.pstpl"),array(), $redata);
  324. //some progress bar stuff
  325. // Create progress bar which is shown while creating the results
  326. $prb = new ProgressBar();
  327. $prb->pedding = 2; // Bar Pedding
  328. $prb->brd_color = "#404040 #dfdfdf #dfdfdf #404040"; // Bar Border Color
  329. $prb->setFrame(); // set ProgressBar Frame
  330. $prb->frame['left'] = 50; // Frame position from left
  331. $prb->frame['top'] = 80; // Frame position from top
  332. $prb->addLabel('text','txt1',$clang->gT("Please wait ...")); // add Text as Label 'txt1' and value 'Please wait'
  333. $prb->addLabel('percent','pct1'); // add Percent as Label 'pct1'
  334. $prb->addButton('btn1',$clang->gT('Go back'),'?action=statistics&amp;sid='.$iSurveyID); // add Button as Label 'btn1' and action '?restart=1'
  335. //progress bar starts with 35%
  336. $process_status = 35;
  337. $prb->show(); // show the ProgressBar
  338. // 1: Get list of questions with answers chosen
  339. //"Getting Questions and Answers ..." is shown above the bar
  340. $prb->setLabelValue('txt1',$clang->gT('Getting questions and answers ...'));
  341. $prb->moveStep(5);
  342. // creates array of post variable names
  343. for (reset($_POST); $key=key($_POST); next($_POST))
  344. {
  345. $postvars[]=$key;
  346. }
  347. $data['thisSurveyTitle'] = $thisSurveyTitle;
  348. $data['totalrecords'] = $totalrecords;
  349. $data['clang'] = $clang;
  350. $data['summary'] = $summary;
  351. //show some main data at the beginnung
  352. // CHANGE JSW_NZ - let's allow html formatted questions to show
  353. //push progress bar from 35 to 40
  354. $process_status = 40;
  355. //Show Summary results
  356. if (isset($summary) && $summary)
  357. {
  358. //"Generating Summaries ..." is shown above the progress bar
  359. $prb->setLabelValue('txt1',$clang->gT('Generating summaries ...'));
  360. $prb->moveStep($process_status);
  361. //let's run through the survey // Fixed bug 3053 with array_unique
  362. $runthrough=array_unique($summary);
  363. //loop through all selected questions
  364. foreach ($runthrough as $rt)
  365. {
  366. //update progress bar
  367. if ($process_status < 100) $process_status++;
  368. $prb->moveStep($process_status);
  369. } // end foreach -> loop through all questions
  370. $helper = new statistics_helper();
  371. $statisticsoutput .= $helper->generate_statistics($iSurveyID, $summary, $summary, $publicgraphs, 'html', null,$language,false);
  372. } //end if -> show summary results
  373. $data['statisticsoutput']=$statisticsoutput;
  374. //done! set progress bar to 100%
  375. if (isset($prb))
  376. {
  377. $prb->setLabelValue('txt1',$clang->gT('Completed'));
  378. $prb->moveStep(100);
  379. $prb->hide();
  380. }
  381. $redata = compact(array_keys(get_defined_vars()));
  382. $data['redata'] = $redata;
  383. header_includes('statistics_user.js');
  384. $this->render('/statistics_user_view',$data);
  385. //output footer
  386. echo getFooter();
  387. //Delete all Session Data
  388. Yii::app()->session['finished'] = true;
  389. }
  390. }