Merge commit 'origin/fusionax' into account
[platal.git] / modules / survey / survey.inc.php
CommitLineData
8fe81c50 1<?php
2/***************************************************************************
8d84c630 3 * Copyright (C) 2003-2009 Polytechnique.org *
8fe81c50 4 * http://opensource.polytechnique.org/ *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
5c6e38d7 22// {{{ class Survey : root of any survey, contains all questions
23class Survey
8fe81c50 24{
5c6e38d7 25 // {{{ static properties and functions, regarding survey modes and question types
26 const MODE_ALL = 0;
27 const MODE_XANON = 1;
28 const MODE_XIDENT = 2;
cd723c19 29 private static $longModes = array(self::MODE_ALL => "sondage ouvert à tout le monde, anonyme",
5c6e38d7 30 self::MODE_XANON => "sondage restreint aux polytechniciens, anonyme",
31 self::MODE_XIDENT => "sondage restreint aux polytechniciens, non anonyme");
32 private static $shortModes = array(self::MODE_ALL => "tout le monde, anonyme",
33 self::MODE_XANON => "polytechniciens, anonyme",
34 self::MODE_XIDENT => "polytechniciens, non anonyme");
8fe81c50 35
5c6e38d7 36 public static function getModes($long = true) {
37 return ($long)? self::$longModes : self::$shortModes;
8fe81c50 38 }
8fe81c50 39
02d94468 40 private static $types = array('text' => 'Texte court',
41 'textarea' => 'Texte long',
cd723c19 42 'num' => 'Numérique',
43 'radio' => 'Choix multiples (une réponse)',
44 'checkbox' => 'Choix multiples (plusieurs réponses)',
45 'radiotable' => 'Questions multiples à choix multiples (une réponse)',
46 'checkboxtable' => 'Questions multiples à choix mutliples (plusieurs réponses)');
8fe81c50 47
48 public static function getTypes()
49 {
50 return self::$types;
51 }
52
53 public static function isType($t)
54 {
55 return array_key_exists($t, self::$types);
56 }
57 // }}}
58
5c6e38d7 59 // {{{ properties, constructor and basic methods
8fe81c50 60 private $id;
5c6e38d7 61 private $title;
62 private $description;
63 private $end;
64 private $mode;
65 private $promos;
66 private $valid;
67 private $questions;
8fe81c50 68
5c6e38d7 69 public function __construct($args, $id = -1, $valid = false, $questions = null)
8fe81c50 70 {
8fe81c50 71 $this->update($args);
5c6e38d7 72 $this->id = $id;
73 $this->valid = $valid;
74 $this->questions = ($questions == null)? array() : $questions;
8fe81c50 75 }
76
5c6e38d7 77 public function update($args)
8fe81c50 78 {
5c6e38d7 79 $this->title = $args['title'];
80 $this->description = $args['description'];
0f396347 81 $this->end = $args['end'];
0b78af47 82 $this->mode = (isset($args['mode']))? $args['mode'] : self::MODE_ALL;
83 if ($this->mode == self::MODE_ALL) {
5c6e38d7 84 $args['promos'] = '';
8fe81c50 85 }
0dc8c5a4 86 $args['promos'] = str_replace(' ', '', $args['promos']);
5c6e38d7 87 $this->promos = ($args['promos'] == '' || preg_match('#^(\d{4}-?|(\d{4})?-\d{4})(,(\d{4}-?|(\d{4})?-\d{4}))*$#', $args['promos']))? $args['promos'] : '#';
8fe81c50 88 }
89 // }}}
90
5c6e38d7 91 // {{{ functions to access general information
92 public function isMode($mode)
8fe81c50 93 {
5c6e38d7 94 return ($this->mode == $mode);
8fe81c50 95 }
96
5c6e38d7 97 public function checkPromo($promo)
8fe81c50 98 {
4b8c8634 99 if ($this->promos == '') {
100 return true;
101 }
fd0084aa 102 $promos = explode(',', $this->promos);
5c6e38d7 103 foreach ($promos as $p) {
104 if ((preg_match('#^\d{4}$#', $p) && $p == $promo) ||
105 (preg_match('#^\d{4}-$#', $p) && intval(substr($p, 0, 4)) <= $promo) ||
106 (preg_match('#^-\d{4}$#', $p) && intval(substr($p, 1)) >= $promo) ||
107 (preg_match('#^\d{4}-\d{4}$#', $p) && intval(substr($p, 0, 4)) <= $promo && intval(substr($p, 5)) >= $promo)) {
108 return true;
109 }
8fe81c50 110 }
5c6e38d7 111 return false;
8fe81c50 112 }
113
5c6e38d7 114 public function isValid()
8fe81c50 115 {
5c6e38d7 116 return $this->valid;
8fe81c50 117 }
118
5c6e38d7 119 public function isEnded()
8fe81c50 120 {
5c6e38d7 121 return (strtotime($this->end) - time() <= 0);
8fe81c50 122 }
8fe81c50 123
5c6e38d7 124 public function getTitle()
8fe81c50 125 {
5c6e38d7 126 return $this->title;
8fe81c50 127 }
128 // }}}
129
9f01f40b 130 // {{{ function toArray() : converts a question (or the whole survey) to array, with results if the survey is ended
5c6e38d7 131 public function toArray($i = 'all')
8fe81c50 132 {
9f01f40b 133 if ($i != 'all' && $i != 'root') { // if a specific question is requested, then just returns this question converted to array
5c6e38d7 134 $i = intval($i);
135 if (array_key_exists($i, $this->questions)) {
136 return $this->questions[$i]->toArray();
8fe81c50 137 } else {
5c6e38d7 138 return null;
8fe81c50 139 }
9f01f40b 140 } else { // else returns the root converted to array in any case
5c6e38d7 141 $a = array('title' => $this->title,
142 'description' => $this->description,
143 'end' => $this->end,
144 'mode' => $this->mode,
145 'promos' => $this->promos,
146 'valid' => $this->valid,
147 'type' => 'root');
148 if ($this->id != -1) {
149 $a['id'] = $this->id;
150 }
9f01f40b 151 if ($this->isEnded()) { // if the survey is ended, then adds here the number of votes
152 $sql = 'SELECT COUNT(id)
153 FROM survey_votes
154 WHERE survey_id={?};';
155 $tot = XDB::query($sql, $this->id);
156 $a['votes'] = $tot->fetchOneCell();
157 }
158 if ($i == 'all' && count($this->questions) > 0) { // if the whole survey is requested, then returns all the questions converted to array
5c6e38d7 159 $qArr = array();
160 for ($k = 0; $k < count($this->questions); $k++) {
161 $q = $this->questions[$k]->toArray();
162 $q['id'] = $k;
9f01f40b 163 if ($this->isEnded()) { // if the survey is ended, then adds here the results of this question
02d94468 164 $q['result'] = $this->questions[$k]->getResultArray($this->id, $k);
9f01f40b 165 }
5c6e38d7 166 $qArr[$k] = $q;
8fe81c50 167 }
5c6e38d7 168 $a['questions'] = $qArr;
8fe81c50 169 }
5c6e38d7 170 return $a;
8fe81c50 171 }
172 }
5c6e38d7 173 // }}}
8fe81c50 174
4b8c8634 175 // {{{ function toCSV() : builds a CSV file containing all the results of the survey
176 public function toCSV($sep = ',', $enc = '"', $asep='|')
177 {
178 $nbq = count($this->questions);
179 //require_once dirname(__FILE__) . '/../../classes/varstream.php';
180 VarStream::init();
181 global $csv_output;
182 $csv_output = '';
183 $csv = fopen('var://csv_output', 'w');
184 $line = ($this->isMode(self::MODE_XIDENT))? array('id', 'Nom', 'Prenom', 'Promo') : array('id');
8e9f416e 185 $qids = array();
4b8c8634 186 for ($qid = 0; $qid < $nbq; $qid++) {
8e9f416e 187 $qids[$qid] = count($line); // stores the first id of a question (in case of questions with subquestions)
188 array_splice($line, count($line), 0, $this->questions[$qid]->getCSVColumns()); // the first line contains the questions
4b8c8634 189 }
8e9f416e 190 $nbf = count($line);
4b8c8634 191 $users = array();
192 if ($this->isMode(self::MODE_XIDENT)) { // if the mode is non anonymous
ee682285
FB
193 $users = User::getBulkUsersWithUIDs(XDB::fetchAllAssoc('vid', 'SELECT v.id AS vid, v.user_id
194 FROM survey_votes AS v
195 WHERE v.survey_id = {?}
196 ORDER BY vid ASC',
197 $this->id));
4b8c8634 198 }
8e9f416e 199 $sql = 'SELECT v.id AS vid, a.question_id AS qid, a.answer AS answer
4b8c8634 200 FROM survey_votes AS v
201 LEFT JOIN survey_answers AS a
202 ON a.vote_id=v.id
203 WHERE v.survey_id={?}
8e9f416e 204 ORDER BY vid ASC, qid ASC, answer ASC;';
4b8c8634 205 $res = XDB::iterator($sql, $this->id); // retrieves all answers from database
4b8c8634 206 $vid = -1;
207 $vid_ = 0;
ee682285 208 while (($cur = $res->next()) != null) {
4b8c8634 209 if ($vid != $cur['vid']) { // if the vote id changes, then starts a new line
210 fputcsv($csv, $line, $sep, $enc); // stores the former line into $csv_output
211 $vid = $cur['vid'];
8e9f416e 212 $line = array_fill(0, $nbf, ''); // creates an array full of empty string
4b8c8634 213 $line[0] = $vid_; // the first field is a 'clean' vote id (not the one stored in database)
214 if ($this->isMode(self::MODE_XIDENT)) { // if the mode is non anonymous
ee682285
FB
215 if (array_key_exists($vid, $users)) { // and if the user data can be found
216 $line[1] = $users[$vid]->lastName(); // adds the user data (in the first fields of the line)
217 $line[2] = $users[$vid]->firstName();;
218 $line[3] = $users[$vid]->promo();
4b8c8634 219 }
220 }
221 $vid_++;
222 }
8e9f416e 223 $ans = $this->questions[$cur['qid']]->formatAnswer($cur['answer']); // formats the current answer
224 if (!is_null($ans)) {
225 if (is_array($ans)) {
226 $fid = $qids[$cur['qid']] + $ans['id']; // computes the field id
227 $a = $ans['answer'];
228 } else {
229 $fid = $qids[$cur['qid']];
230 $a = $ans;
231 }
232 if ($line[$fid] != '') { // if this field already contains something
233 $line[$fid] .= $asep; // then adds a separator before adding the new answer
234 }
235 $line[$fid] .= $a; // adds the current answer to the correct field
4b8c8634 236 }
4b8c8634 237 }
238 fputcsv($csv, $line, $sep, $enc); // stores the last line into $csv_output
239 return $csv_output;
240 }
241 // }}}
242
5c6e38d7 243 // {{{ function factory($type, $args) : builds a question according to the given type
244 public function factory($t, $args)
8fe81c50 245 {
5c6e38d7 246 switch ($t) {
247 case 'text':
248 return new SurveyText($args);
249 case 'textarea':
250 return new SurveyTextarea($args);
251 case 'num':
252 return new SurveyNum($args);
253 case 'radio':
254 return new SurveyRadio($args);
255 case 'checkbox':
256 return new SurveyCheckbox($args);
02d94468 257 case 'radiotable':
258 return new SurveyRadioTable($args);
259 case 'checkboxtable':
260 return new SurveyCheckboxTable($args);
5c6e38d7 261 default:
262 return null;
8fe81c50 263 }
5c6e38d7 264 }
265 // }}}
266
267 // {{{ questions manipulation functions
268 public function addQuestion($i, $c)
269 {
cd129064 270 $i = intval($i);
5c6e38d7 271 if ($this->valid || $i > count($this->questions)) {
272 return false;
273 } else {
274 array_splice($this->questions, $i, 0, array($c));
8fe81c50 275 return true;
276 }
8fe81c50 277 }
278
5c6e38d7 279 public function delQuestion($i)
8fe81c50 280 {
cd129064 281 $i = intval($i);
5c6e38d7 282 if ($this->valid || !array_key_exists($i, $this->questions)) {
283 return false;
284 } else {
285 array_splice($this->questions, $i, 1);
8fe81c50 286 return true;
287 }
8fe81c50 288 }
8fe81c50 289
5c6e38d7 290 public function editQuestion($i, $a)
8fe81c50 291 {
5c6e38d7 292 if ($i == 'root') {
8fe81c50 293 $this->update($a);
8fe81c50 294 } else {
5c6e38d7 295 $i = intval($i);
296 if ($this->valid ||!array_key_exists($i, $this->questions)) {
297 return false;
298 } else {
299 $this->questions[$i]->update($a);
8fe81c50 300 }
8fe81c50 301 }
5c6e38d7 302 return true;
8fe81c50 303 }
304 // }}}
305
5c6e38d7 306 // {{{ function checkSyntax() : checks syntax of the questions (currently the root only) before storing the survey in database
307 private static $errorMessages = array(
cd723c19 308 "datepassed" => "la date de fin de sondage est déjà dépassée : vous devez préciser une date future",
309 "promoformat" => "les restrictions à certaines promotions sont mal formattées"
5c6e38d7 310 );
311
312 public function checkSyntax()
8fe81c50 313 {
5c6e38d7 314 $rArr = array();
0f396347 315 // checks that the end date given is not already passed
316 // (unless the survey has already been validated : an admin can have a validated survey expired)
317 if (!$this->valid && $this->isEnded()) {
318 $rArr[] = array('question' => 'root', 'error' => self::$errorMessages["datepassed"]);
5c6e38d7 319 }
320 if ($this->promos != '' && !preg_match('#^(\d{4}-?|(\d{4})?-\d{4})(,(\d{4}-?|(\d{4})?-\d{4}))*$#', $this->promos)) {
321 $rArr[] = array('question' => 'root', 'error' => self::$errorMessages["promoformat"]);
8fe81c50 322 }
5c6e38d7 323 return (empty($rArr))? null : $rArr;
8fe81c50 324 }
5c6e38d7 325 // }}}
8fe81c50 326
9f01f40b 327 // {{{ functions that manipulate surveys in database
5c6e38d7 328 // {{{ static function retrieveList() : gets the list of available survey (current, old and not validated surveys)
329 public static function retrieveList($type, $tpl = true)
8fe81c50 330 {
5c6e38d7 331 switch ($type) {
5c6e38d7 332 case 'c':
333 case 'current':
797d27db 334 $where = 'end > NOW()';
5c6e38d7 335 break;
336 case 'o':
337 case 'old':
797d27db 338 $where = 'end <= NOW()';
5c6e38d7 339 break;
340 default:
8fe81c50 341 return null;
342 }
5c6e38d7 343 $sql = 'SELECT id, title, end, mode
344 FROM survey_surveys
8e9f416e 345 WHERE '.$where.'
346 ORDER BY end DESC;';
5c6e38d7 347 if ($tpl) {
348 return XDB::iterator($sql);
349 } else {
350 return XDB::iterRow($sql);
351 }
8fe81c50 352 }
353 // }}}
354
5c6e38d7 355 // {{{ static function retrieveSurvey() : gets a survey in database (and unserialize the survey object structure)
356 public static function retrieveSurvey($sid)
8fe81c50 357 {
797d27db 358 $sql = 'SELECT questions, title, description, end, mode, promos
5c6e38d7 359 FROM survey_surveys
360 WHERE id={?}';
361 $res = XDB::query($sql, $sid);
362 $data = $res->fetchOneAssoc();
363 if (is_null($data) || !is_array($data)) {
364 return null;
8fe81c50 365 }
797d27db 366 $survey = new Survey($data, $sid, true, unserialize($data['questions']));
5c6e38d7 367 return $survey;
8fe81c50 368 }
369 // }}}
370
5c6e38d7 371 // {{{ static function retrieveSurveyInfo() : gets information about a survey (title, description, end date, restrictions) but does not unserialize the survey object structure
372 public static function retrieveSurveyInfo($sid)
8fe81c50 373 {
797d27db 374 $sql = 'SELECT title, description, end, mode, promos
5c6e38d7 375 FROM survey_surveys
376 WHERE id={?}';
377 $res = XDB::query($sql, $sid);
378 return $res->fetchOneAssoc();
8fe81c50 379 }
380 // }}}
8fe81c50 381
797d27db 382 // {{{ static function retrieveSurveyReq() : gets a survey request to validate
383 public static function retrieveSurveyReq($id)
384 {
385 require_once 'validations.inc.php';
386 $surveyreq = Validate::get_request_by_id($id);
387 if ($surveyreq == null) {
388 return null;
389 }
390 $data = array('title' => $surveyreq->title,
391 'description' => $surveyreq->description,
392 'end' => $surveyreq->end,
393 'mode' => $surveyreq->mode,
394 'promos' => $surveyreq->promos);
395 $survey = new Survey($data, $id, false, $surveyreq->questions);
396 return $survey;
397 }
398 // }}}
399
5c6e38d7 400 // {{{ function proposeSurvey() : stores a proposition of survey in database (before validation)
401 public function proposeSurvey()
8fe81c50 402 {
797d27db 403 require_once 'validations.inc.php';
5daf68f6 404 $surveyreq = new SurveyReq($this->title, $this->description, $this->end, $this->mode, $this->promos, $this->questions, S::user());
797d27db 405 return $surveyreq->submit();
8fe81c50 406 }
5c6e38d7 407 // }}}
8fe81c50 408
5c6e38d7 409 // {{{ function updateSurvey() : updates a survey in database (before validation)
410 public function updateSurvey()
8fe81c50 411 {
797d27db 412 if ($this->valid) {
413 $sql = 'UPDATE survey_surveys
414 SET questions={?},
415 title={?},
416 description={?},
417 end={?},
418 mode={?},
419 promos={?}
420 WHERE id={?};';
421 return XDB::execute($sql, serialize($this->questions), $this->title, $this->description, $this->end, $this->mode, $this->promos, $this->id);
422 } else {
423 require_once 'validations.inc.php';
424 $surveyreq = Validate::get_request_by_id($this->id);
425 if ($surveyreq == null) {
426 return false;
427 }
428 return $surveyreq->updateReq($this->title, $this->description, $this->end, $this->mode, $this->promos, $this->questions);
8fe81c50 429 }
8fe81c50 430 }
5c6e38d7 431 // }}}
8fe81c50 432
5c6e38d7 433 // {{{ functions vote() and hasVoted() : handles vote to a survey
434 public function vote($uid, $args)
435 {
436 XDB::execute('INSERT INTO survey_votes
437 SET survey_id={?}, user_id={?};', $this->id, $uid); // notes the user as having voted
438 $vid = XDB::insertId();
439 for ($i = 0; $i < count($this->questions); $i++) {
440 $ans = $this->questions[$i]->checkAnswer($args[$i]);
9f01f40b 441 if (!is_null($ans) && is_array($ans)) {
442 foreach ($ans as $a) {
443 XDB::execute('INSERT INTO survey_answers
444 SET vote_id = {?},
445 question_id = {?},
446 answer = {?}', $vid, $i, $a);
447 }
5c6e38d7 448 }
449 }
8fe81c50 450 }
451
5c6e38d7 452 public function hasVoted($uid)
8fe81c50 453 {
5c6e38d7 454 $res = XDB::query('SELECT id
455 FROM survey_votes
456 WHERE survey_id={?} AND user_id={?};', $this->id, $uid); // checks whether the user has already voted
457 return ($res->numRows() != 0);
8fe81c50 458 }
5c6e38d7 459 // }}}
8fe81c50 460
5c6e38d7 461 // {{{ static function deleteSurvey() : deletes a survey (and all its votes)
462 public static function deleteSurvey($sid)
8fe81c50 463 {
5c6e38d7 464 $sql = 'DELETE s.*, v.*, a.*
465 FROM survey_surveys AS s
466 LEFT JOIN survey_votes AS v
467 ON v.survey_id=s.id
468 LEFT JOIN survey_answers AS a
469 ON a.vote_id=v.id
470 WHERE s.id={?};';
471 return XDB::execute($sql, $sid);
8fe81c50 472 }
473 // }}}
474
5c6e38d7 475 // {{{ static function purgeVotes() : clears all votes concerning a survey (I'm not sure whether it's really useful)
476 public static function purgeVotes($sid)
8fe81c50 477 {
5c6e38d7 478 $sql = 'DELETE v.*, a.*
479 FROM survey_votes AS v
480 LEFT JOIN survey_answers AS a
481 ON a.vote_id=v.id
482 WHERE v.survey_id={?};';
483 return XDB::execute($sql, $sid);
8fe81c50 484 }
485 // }}}
486
5c6e38d7 487 // }}}
488}
489// }}}
8fe81c50 490
5c6e38d7 491// {{{ abstract class SurveyQuestion
492abstract class SurveyQuestion
493{
494 // {{{ common properties, constructor, and basic methods
495 private $question;
496 private $comment;
8fe81c50 497
5c6e38d7 498 public function __construct($args)
8fe81c50 499 {
5c6e38d7 500 $this->update($args);
8fe81c50 501 }
502
5c6e38d7 503 public function update($a)
8fe81c50 504 {
5c6e38d7 505 $this->question = $a['question'];
506 $this->comment = $a['comment'];
8fe81c50 507 }
508
5c6e38d7 509 abstract protected function getQuestionType();
510 // }}}
511
512 // {{{ function toArray() : converts to array
8fe81c50 513 public function toArray()
514 {
5c6e38d7 515 return array('type' => $this->getQuestionType(), 'question' => $this->question, 'comment' => $this->comment);
8fe81c50 516 }
5c6e38d7 517 // }}}
8fe81c50 518
5c6e38d7 519 // {{{ function checkSyntax() : checks question elements (before storing into database), not currently needed (with new structure)
520 protected function checkSyntax()
8fe81c50 521 {
5c6e38d7 522 return null;
8fe81c50 523 }
524 // }}}
525
02d94468 526 // {{{ function checkAnswer : returns a correct answer (or a null value if error)
5c6e38d7 527 public function checkAnswer($ans)
8fe81c50 528 {
9f01f40b 529 return null;
8fe81c50 530 }
531 // }}}
532
4b8c8634 533 // {{{ functions regarding the results of a survey
02d94468 534 abstract public function getResultArray($sid, $qid);
4b8c8634 535
8e9f416e 536 public function formatAnswer($ans)
537 {
538 return $ans;
539 }
540
541 public function getCSVColumns()
4b8c8634 542 {
543 return $this->question;
544 }
8fe81c50 545 // }}}
546}
547// }}}
548
fd0084aa 549// {{{ abstract class SurveySimple and its derived classes : "open" questions
9f01f40b 550// {{{ abstract class SurveySimple extends SurveyQuestion
8fe81c50 551abstract class SurveySimple extends SurveyQuestion
552{
5c6e38d7 553 public function checkAnswer($ans)
8fe81c50 554 {
9f01f40b 555 return array($ans);
556 }
557
02d94468 558 public function getResultArray($sid, $qid)
9f01f40b 559 {
560 $sql = 'SELECT answer
561 FROM survey_answers
562 WHERE vote_id IN (SELECT id FROM survey_votes WHERE survey_id={?})
563 AND question_id={?}
564 ORDER BY RAND()
565 LIMIT 5;';
02d94468 566 $res = XDB::query($sql, $sid, $qid);
567 return $res->fetchAllAssoc();
8fe81c50 568 }
569}
9f01f40b 570// }}}
8fe81c50 571
572// {{{ class SurveyText extends SurveySimple : simple text field, allowing a few words
573class SurveyText extends SurveySimple
574{
5c6e38d7 575 public function getQuestionType()
8fe81c50 576 {
577 return "text";
578 }
579}
580// }}}
581
582// {{{ class SurveyTextarea extends SurveySimple : textarea field, allowing longer comments
583class SurveyTextarea extends SurveySimple
584{
5c6e38d7 585 public function getQuestionType()
8fe81c50 586 {
587 return "textarea";
588 }
589}
590// }}}
591
592// {{{ class SurveyNum extends SurveySimple : allows numerical answers
593class SurveyNum extends SurveySimple
594{
5c6e38d7 595 public function checkAnswer($ans)
8fe81c50 596 {
9f01f40b 597 return array(intval($ans));
8fe81c50 598 }
599
600 protected function getQuestionType()
601 {
602 return "num";
603 }
604}
605// }}}
606// }}}
607
9f01f40b 608// {{{ abstract class SurveyList and its derived classes : restricted questions that allows only a list of possible answers
609// {{{ abstract class SurveyList extends SurveyQuestion
5c6e38d7 610abstract class SurveyList extends SurveyQuestion
8fe81c50 611{
5c6e38d7 612 protected $choices;
8fe81c50 613
5c6e38d7 614 public function update($args)
8fe81c50 615 {
616 parent::update($args);
0f396347 617 $this->choices = array();
02d94468 618 foreach ($args['choices'] as $val) {
eadfa7ba 619 if (trim($val) || trim($val) == '0') {
0f396347 620 $this->choices[] = $val;
621 }
622 }
8fe81c50 623 }
624
5c6e38d7 625 public function toArray()
8fe81c50 626 {
5c6e38d7 627 $rArr = parent::toArray();
8fe81c50 628 $rArr['choices'] = $this->choices;
8fe81c50 629 return $rArr;
630 }
631
02d94468 632 public function getResultArray($sid, $qid)
9f01f40b 633 {
634 $sql = 'SELECT answer, COUNT(id) AS count
635 FROM survey_answers
636 WHERE vote_id IN (SELECT id FROM survey_votes WHERE survey_id={?})
637 AND question_id={?}
638 GROUP BY answer ASC';
02d94468 639 $res = XDB::query($sql, $sid, $qid);
640 return $res->fetchAllAssoc();
9f01f40b 641 }
4b8c8634 642
8e9f416e 643 public function formatAnswer($ans)
4b8c8634 644 {
8e9f416e 645 if (array_key_exists($ans, $this->choices)) {
646 return $this->choices[$ans];
647 } else {
648 return null;
4b8c8634 649 }
4b8c8634 650 }
8fe81c50 651}
9f01f40b 652// }}}
8fe81c50 653
654// {{{ class SurveyRadio extends SurveyList : radio question, allows one answer among the list offered
655class SurveyRadio extends SurveyList
656{
5c6e38d7 657 public function checkAnswer($ans)
8fe81c50 658 {
02d94468 659 $a = intval($ans);
660 return (array_key_exists($a, $this->choices))? array($a) : null;
8fe81c50 661 }
662
663 protected function getQuestionType()
664 {
665 return "radio";
666 }
667}
668// }}}
669
670// {{{ class SurveyCheckbox extends SurveyList : checkbox question, allows any number of answers among the list offered
671class SurveyCheckbox extends SurveyList
672{
5c6e38d7 673 public function checkAnswer($ans)
8fe81c50 674 {
9f01f40b 675 $rep = array();
5c6e38d7 676 foreach ($ans as $a) {
9f01f40b 677 $a = intval($a);
678 if (array_key_exists($a, $this->choices)) {
679 $rep[] = $a;
8fe81c50 680 }
681 }
9f01f40b 682 return (count($rep) == 0)? null : $rep;
8fe81c50 683 }
684
685 protected function getQuestionType()
686 {
687 return "checkbox";
688 }
689}
690// }}}
691// }}}
692
02d94468 693// {{{ abstract class SurveyTable and its derived classes : table question, each column represents a choice, each line represents a question
694// {{{ abstract class SurveyTable extends SurveyList
695abstract class SurveyTable extends SurveyList
696{
697 protected $subquestions;
698
699 public function update($args)
700 {
701 parent::update($args);
702 $this->subquestions = array();
703 foreach ($args['subquestions'] as $val) {
704 if (trim($val) || trim($val) == '0') {
705 $this->subquestions[] = $val;
706 }
707 }
708 }
709
710 public function toArray()
711 {
712 $rArr = parent::toArray();
713 $rArr['subquestions'] = $this->subquestions;
714 return $rArr;
715 }
716
717 public function getResultArray($sid, $qid)
718 {
719 $sql = 'SELECT answer, COUNT(id) AS count
720 FROM survey_answers
721 WHERE vote_id IN (SELECT id FROM survey_votes WHERE survey_id={?})
722 AND question_id={?}
723 GROUP BY answer ASC';
724 $res = XDB::iterator($sql, $sid, $qid);
725 $result = array();
726 for ($i = 0; $i < count($this->subquestions); $i++) {
727 $result[$i] = array_fill(0, count($this->choices), 0);
728 }
729 while ($r = $res->next()) {
730 list($i, $j) = explode(':', $r['answer']);
731 $result[$i][$j] = $r['count'];
732 }
733 return $result;
734 }
735
8e9f416e 736 public function formatAnswer($ans)
02d94468 737 {
8e9f416e 738 list($q, $c) = explode(':', $ans);
739 if (array_key_exists($q, $this->subquestions) && array_key_exists($c, $this->choices)) {
740 return array('id' => $q, 'answer' => $this->choices[$c]);
741 } else {
742 return null;
02d94468 743 }
8e9f416e 744 }
745
746 public function getCSVColumns()
747 {
748 $q = parent::getCSVColumns();
749 if (empty($this->subquestions)) {
750 return $q;
751 }
752 $a = array();
753 for ($k = 0; $k < count($this->subquestions); $k++) {
754 $a[$k] = $q.' : '.$this->subquestions[$k];
02d94468 755 }
8e9f416e 756 return $a;
02d94468 757 }
758}
759// }}}
760
761// {{{ class SurveyRadioTable extends SurveyTable : SurveyTable with radio type choices
762class SurveyRadioTable extends SurveyTable
763{
764 public function checkAnswer($ans)
765 {
766 $rep = array();
767 foreach ($ans as $k => $a) {
768 if (!array_key_exists($k, $this->subquestions)) {
769 continue;
770 }
771 $a = intval($a);
772 if (array_key_exists($a, $this->choices)) {
773 $rep[] = $k . ':' . $a;
774 }
775 }
776 return (count($rep) == 0)? null : $rep;
777 }
778
779 protected function getQuestionType()
780 {
781 return "radiotable";
782 }
783
784}
785// }}}
786
787// {{{ class SurveyCheckboxTable extends SurveyTable : SurveyTable with checkbox type choices
788class SurveyCheckboxTable extends SurveyTable
789{
790 public function checkAnswer($ans)
791 {
792 $rep = array();
793 foreach ($ans as $k => $aa) {
794 if (!array_key_exists($k, $this->subquestions)) {
795 continue;
796 }
797 foreach ($aa as $a) {
798 $a = intval($a);
799 if (array_key_exists($a, $this->choices)) {
800 $rep[] = $k . ':' . $a;
801 }
802 }
803 }
804 return (count($rep) == 0)? null : $rep;
805 }
806
807 protected function getQuestionType()
808 {
809 return "checkboxtable";
810 }
811
812}
813// }}}
814// }}}
815
8602c852 816// vim:set et sw=4 sts=4 ts=4 foldmethod=marker enc=utf-8:
8fe81c50 817?>