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