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