changes in surveys validation handling
[platal.git] / modules / survey / survey.inc.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2007 Polytechnique.org *
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
22 // {{{ class Survey : root of any survey, contains all questions
23 class Survey
24 {
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 &#224; 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&#233;rique',
43 'radio' => 'Choix multiples (une réponse)',
44 'checkbox' => 'Choix multiples (plusieurs réponses)');
45
46 public static function getTypes()
47 {
48 return self::$types;
49 }
50
51 public static function isType($t)
52 {
53 return array_key_exists($t, self::$types);
54 }
55 // }}}
56
57 // {{{ properties, constructor and basic methods
58 private $id;
59 private $title;
60 private $description;
61 private $end;
62 private $mode;
63 private $promos;
64 private $valid;
65 private $questions;
66
67 public function __construct($args, $id = -1, $valid = false, $questions = null)
68 {
69 $this->update($args);
70 $this->id = $id;
71 $this->valid = $valid;
72 $this->questions = ($questions == null)? array() : $questions;
73 }
74
75 public function update($args)
76 {
77 $this->title = $args['title'];
78 $this->description = $args['description'];
79 $this->end = $args['end'];
80 $this->mode = (isset($args['mode']))? $args['mode'] : self::MODE_ALL;
81 if ($this->mode == self::MODE_ALL) {
82 $args['promos'] = '';
83 }
84 $this->promos = ($args['promos'] == '' || preg_match('#^(\d{4}-?|(\d{4})?-\d{4})(,(\d{4}-?|(\d{4})?-\d{4}))*$#', $args['promos']))? $args['promos'] : '#';
85 }
86 // }}}
87
88 // {{{ functions to access general information
89 public function isMode($mode)
90 {
91 return ($this->mode == $mode);
92 }
93
94 public function checkPromo($promo)
95 {
96 if ($this->promos == '') {
97 return true;
98 }
99 $promos = explode(',', $this->promos);
100 foreach ($promos as $p) {
101 if ((preg_match('#^\d{4}$#', $p) && $p == $promo) ||
102 (preg_match('#^\d{4}-$#', $p) && intval(substr($p, 0, 4)) <= $promo) ||
103 (preg_match('#^-\d{4}$#', $p) && intval(substr($p, 1)) >= $promo) ||
104 (preg_match('#^\d{4}-\d{4}$#', $p) && intval(substr($p, 0, 4)) <= $promo && intval(substr($p, 5)) >= $promo)) {
105 return true;
106 }
107 }
108 return false;
109 }
110
111 public function isValid()
112 {
113 return $this->valid;
114 }
115
116 public function isEnded()
117 {
118 return (strtotime($this->end) - time() <= 0);
119 }
120
121 public function getTitle()
122 {
123 return $this->title;
124 }
125 // }}}
126
127 // {{{ function toArray() : converts a question (or the whole survey) to array, with results if the survey is ended
128 public function toArray($i = 'all')
129 {
130 if ($i != 'all' && $i != 'root') { // if a specific question is requested, then just returns this question converted to array
131 $i = intval($i);
132 if (array_key_exists($i, $this->questions)) {
133 return $this->questions[$i]->toArray();
134 } else {
135 return null;
136 }
137 } else { // else returns the root converted to array in any case
138 $a = array('title' => $this->title,
139 'description' => $this->description,
140 'end' => $this->end,
141 'mode' => $this->mode,
142 'promos' => $this->promos,
143 'valid' => $this->valid,
144 'type' => 'root');
145 if ($this->id != -1) {
146 $a['id'] = $this->id;
147 }
148 if ($this->isEnded()) { // if the survey is ended, then adds here the number of votes
149 $sql = 'SELECT COUNT(id)
150 FROM survey_votes
151 WHERE survey_id={?};';
152 $tot = XDB::query($sql, $this->id);
153 $a['votes'] = $tot->fetchOneCell();
154 }
155 if ($i == 'all' && count($this->questions) > 0) { // if the whole survey is requested, then returns all the questions converted to array
156 $qArr = array();
157 for ($k = 0; $k < count($this->questions); $k++) {
158 $q = $this->questions[$k]->toArray();
159 $q['id'] = $k;
160 if ($this->isEnded()) { // if the survey is ended, then adds here the results of this question
161 $sql = $this->questions[$k]->buildResultRequest();
162 if ($sql != '') {
163 $q['result'] = XDB::iterator($sql, $this->id, $k);
164 }
165 }
166 $qArr[$k] = $q;
167 }
168 $a['questions'] = $qArr;
169 }
170 return $a;
171 }
172 }
173 // }}}
174
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');
185 for ($qid = 0; $qid < $nbq; $qid++) {
186 $line[] = $this->questions[$qid]->getCSVColumn(); // the fist line contains the questions
187 }
188 $users = array();
189 if ($this->isMode(self::MODE_XIDENT)) { // if the mode is non anonymous
190 $sql = 'SELECT v.id AS vid, a.nom, a.prenom, a.promo
191 FROM survey_votes AS v
192 INNER JOIN auth_user_md5 AS a
193 ON a.user_id=v.user_id
194 WHERE v.survey_id={?}
195 ORDER BY vid ASC;';
196 $res = XDB::iterator($sql, $this->id); // retrieves all users data
197 for ($u = $res->next(); $u != null; $u = $res->next()) {
198 $users[$u['vid']] = array('nom' => $u['nom'], 'prenom' => $u['prenom'], 'promo' => $u['promo']);
199 }
200 }
201 $sql = 'SELECT v.id AS vid, a.question_id AS qid, a.answer
202 FROM survey_votes AS v
203 LEFT JOIN survey_answers AS a
204 ON a.vote_id=v.id
205 WHERE v.survey_id={?}
206 ORDER BY vid ASC, qid ASC;';
207 $res = XDB::iterator($sql, $this->id); // retrieves all answers from database
208 $cur = $res->next();
209 $vid = -1;
210 $vid_ = 0;
211 $first = ($this->isMode(self::MODE_XIDENT))? 4 : 1;
212 while ($cur != null) {
213 if ($vid != $cur['vid']) { // if the vote id changes, then starts a new line
214 fputcsv($csv, $line, $sep, $enc); // stores the former line into $csv_output
215 $vid = $cur['vid'];
216 $line = array_fill(0, $first + $nbq, ''); // creates an array full of empty string
217 $line[0] = $vid_; // the first field is a 'clean' vote id (not the one stored in database)
218 if ($this->isMode(self::MODE_XIDENT)) { // if the mode is non anonymous
219 if (array_key_exists($vid, $users) && is_array($users[$vid])) { // and if the user data can be found
220 $line[1] = $users[$vid]['nom']; // adds the user data (in the first fields of the line)
221 $line[2] = $users[$vid]['prenom'];
222 $line[3] = $users[$vid]['promo'];
223 }
224 }
225 $vid_++;
226 }
227 $fid = $first + $cur['qid']; // computes the field id
228 if ($line[$fid] != '') { // if this field already contains something
229 $line[$fid] .= $asep; // then adds a separator before adding the new answer
230 }
231 $line[$fid] .= $cur['answer']; // adds the current answer to the correct field
232 $cur = $res->next(); // gets next answer
233 }
234 fputcsv($csv, $line, $sep, $enc); // stores the last line into $csv_output
235 return $csv_output;
236 }
237 // }}}
238
239 // {{{ function factory($type, $args) : builds a question according to the given type
240 public function factory($t, $args)
241 {
242 switch ($t) {
243 case 'text':
244 return new SurveyText($args);
245 case 'textarea':
246 return new SurveyTextarea($args);
247 case 'num':
248 return new SurveyNum($args);
249 case 'radio':
250 return new SurveyRadio($args);
251 case 'checkbox':
252 return new SurveyCheckbox($args);
253 case 'personal':
254 return new SurveyPersonal($args);
255 default:
256 return null;
257 }
258 }
259 // }}}
260
261 // {{{ questions manipulation functions
262 public function addQuestion($i, $c)
263 {
264 $i = intval($i);
265 if ($this->valid || $i > count($this->questions)) {
266 return false;
267 } else {
268 array_splice($this->questions, $i, 0, array($c));
269 return true;
270 }
271 }
272
273 public function delQuestion($i)
274 {
275 $i = intval($i);
276 if ($this->valid || !array_key_exists($i, $this->questions)) {
277 return false;
278 } else {
279 array_splice($this->questions, $i, 1);
280 return true;
281 }
282 }
283
284 public function editQuestion($i, $a)
285 {
286 if ($i == 'root') {
287 $this->update($a);
288 } else {
289 $i = intval($i);
290 if ($this->valid ||!array_key_exists($i, $this->questions)) {
291 return false;
292 } else {
293 $this->questions[$i]->update($a);
294 }
295 }
296 return true;
297 }
298 // }}}
299
300 // {{{ function checkSyntax() : checks syntax of the questions (currently the root only) before storing the survey in database
301 private static $errorMessages = array(
302 "datepassed" => "la date de fin de sondage est d&#233;j&#224; d&#233;pass&#233;e : vous devez pr&#233;ciser une date future",
303 "promoformat" => "les restrictions &#224; certaines promotions sont mal formatt&#233;es"
304 );
305
306 public function checkSyntax()
307 {
308 $rArr = array();
309 // checks that the end date given is not already passed
310 // (unless the survey has already been validated : an admin can have a validated survey expired)
311 if (!$this->valid && $this->isEnded()) {
312 $rArr[] = array('question' => 'root', 'error' => self::$errorMessages["datepassed"]);
313 }
314 if ($this->promos != '' && !preg_match('#^(\d{4}-?|(\d{4})?-\d{4})(,(\d{4}-?|(\d{4})?-\d{4}))*$#', $this->promos)) {
315 $rArr[] = array('question' => 'root', 'error' => self::$errorMessages["promoformat"]);
316 }
317 return (empty($rArr))? null : $rArr;
318 }
319 // }}}
320
321 // {{{ functions that manipulate surveys in database
322 // {{{ static function retrieveList() : gets the list of available survey (current, old and not validated surveys)
323 public static function retrieveList($type, $tpl = true)
324 {
325 switch ($type) {
326 case 'c':
327 case 'current':
328 $where = 'end > NOW()';
329 break;
330 case 'o':
331 case 'old':
332 $where = 'end <= NOW()';
333 break;
334 default:
335 return null;
336 }
337 $sql = 'SELECT id, title, end, mode
338 FROM survey_surveys
339 WHERE '.$where.';';
340 if ($tpl) {
341 return XDB::iterator($sql);
342 } else {
343 return XDB::iterRow($sql);
344 }
345 }
346 // }}}
347
348 // {{{ static function retrieveSurvey() : gets a survey in database (and unserialize the survey object structure)
349 public static function retrieveSurvey($sid)
350 {
351 $sql = 'SELECT questions, title, description, end, mode, promos
352 FROM survey_surveys
353 WHERE id={?}';
354 $res = XDB::query($sql, $sid);
355 $data = $res->fetchOneAssoc();
356 if (is_null($data) || !is_array($data)) {
357 return null;
358 }
359 $survey = new Survey($data, $sid, true, unserialize($data['questions']));
360 return $survey;
361 }
362 // }}}
363
364 // {{{ static function retrieveSurveyInfo() : gets information about a survey (title, description, end date, restrictions) but does not unserialize the survey object structure
365 public static function retrieveSurveyInfo($sid)
366 {
367 $sql = 'SELECT title, description, end, mode, promos
368 FROM survey_surveys
369 WHERE id={?}';
370 $res = XDB::query($sql, $sid);
371 return $res->fetchOneAssoc();
372 }
373 // }}}
374
375 // {{{ static function retrieveSurveyReq() : gets a survey request to validate
376 public static function retrieveSurveyReq($id)
377 {
378 require_once 'validations.inc.php';
379 $surveyreq = Validate::get_request_by_id($id);
380 if ($surveyreq == null) {
381 return null;
382 }
383 $data = array('title' => $surveyreq->title,
384 'description' => $surveyreq->description,
385 'end' => $surveyreq->end,
386 'mode' => $surveyreq->mode,
387 'promos' => $surveyreq->promos);
388 $survey = new Survey($data, $id, false, $surveyreq->questions);
389 return $survey;
390 }
391 // }}}
392
393 // {{{ function proposeSurvey() : stores a proposition of survey in database (before validation)
394 public function proposeSurvey()
395 {
396 require_once 'validations.inc.php';
397 $surveyreq = new SurveyReq($this->title, $this->description, $this->end, $this->mode, $this->promos, $this->questions, S::v('uid'));
398 return $surveyreq->submit();
399 }
400 // }}}
401
402 // {{{ function updateSurvey() : updates a survey in database (before validation)
403 public function updateSurvey()
404 {
405 if ($this->valid) {
406 $sql = 'UPDATE survey_surveys
407 SET questions={?},
408 title={?},
409 description={?},
410 end={?},
411 mode={?},
412 promos={?}
413 WHERE id={?};';
414 return XDB::execute($sql, serialize($this->questions), $this->title, $this->description, $this->end, $this->mode, $this->promos, $this->id);
415 } else {
416 require_once 'validations.inc.php';
417 $surveyreq = Validate::get_request_by_id($this->id);
418 if ($surveyreq == null) {
419 return false;
420 }
421 return $surveyreq->updateReq($this->title, $this->description, $this->end, $this->mode, $this->promos, $this->questions);
422 }
423 }
424 // }}}
425
426 // {{{ functions vote() and hasVoted() : handles vote to a survey
427 public function vote($uid, $args)
428 {
429 XDB::execute('INSERT INTO survey_votes
430 SET survey_id={?}, user_id={?};', $this->id, $uid); // notes the user as having voted
431 $vid = XDB::insertId();
432 for ($i = 0; $i < count($this->questions); $i++) {
433 $ans = $this->questions[$i]->checkAnswer($args[$i]);
434 if (!is_null($ans) && is_array($ans)) {
435 foreach ($ans as $a) {
436 XDB::execute('INSERT INTO survey_answers
437 SET vote_id = {?},
438 question_id = {?},
439 answer = {?}', $vid, $i, $a);
440 }
441 }
442 }
443 }
444
445 public function hasVoted($uid)
446 {
447 $res = XDB::query('SELECT id
448 FROM survey_votes
449 WHERE survey_id={?} AND user_id={?};', $this->id, $uid); // checks whether the user has already voted
450 return ($res->numRows() != 0);
451 }
452 // }}}
453
454 // {{{ static function deleteSurvey() : deletes a survey (and all its votes)
455 public static function deleteSurvey($sid)
456 {
457 $sql = 'DELETE s.*, v.*, a.*
458 FROM survey_surveys AS s
459 LEFT JOIN survey_votes AS v
460 ON v.survey_id=s.id
461 LEFT JOIN survey_answers AS a
462 ON a.vote_id=v.id
463 WHERE s.id={?};';
464 return XDB::execute($sql, $sid);
465 }
466 // }}}
467
468 // {{{ static function purgeVotes() : clears all votes concerning a survey (I'm not sure whether it's really useful)
469 public static function purgeVotes($sid)
470 {
471 $sql = 'DELETE v.*, a.*
472 FROM survey_votes AS v
473 LEFT JOIN survey_answers AS a
474 ON a.vote_id=v.id
475 WHERE v.survey_id={?};';
476 return XDB::execute($sql, $sid);
477 }
478 // }}}
479
480 // }}}
481 }
482 // }}}
483
484 // {{{ abstract class SurveyQuestion
485 abstract class SurveyQuestion
486 {
487 // {{{ common properties, constructor, and basic methods
488 private $question;
489 private $comment;
490
491 public function __construct($args)
492 {
493 $this->update($args);
494 }
495
496 public function update($a)
497 {
498 $this->question = $a['question'];
499 $this->comment = $a['comment'];
500 }
501
502 abstract protected function getQuestionType();
503 // }}}
504
505 // {{{ function toArray() : converts to array
506 public function toArray()
507 {
508 return array('type' => $this->getQuestionType(), 'question' => $this->question, 'comment' => $this->comment);
509 }
510 // }}}
511
512 // {{{ function checkSyntax() : checks question elements (before storing into database), not currently needed (with new structure)
513 protected function checkSyntax()
514 {
515 return null;
516 }
517 // }}}
518
519 // {{{ function checkAnswer : returns a correctly formatted answer (or nothing empty string if error)
520 public function checkAnswer($ans)
521 {
522 return null;
523 }
524 // }}}
525
526 // {{{ functions regarding the results of a survey
527 public function buildResultRequest()
528 {
529 return '';
530 }
531
532 public function getCSVColumn()
533 {
534 return $this->question;
535 }
536 // }}}
537 }
538 // }}}
539
540 // {{{ abstract class SurveySimple and its derived classes : "open" questions
541 // {{{ abstract class SurveySimple extends SurveyQuestion
542 abstract class SurveySimple extends SurveyQuestion
543 {
544 public function checkAnswer($ans)
545 {
546 return array($ans);
547 }
548
549 public function buildResultRequest()
550 {
551 $sql = 'SELECT answer
552 FROM survey_answers
553 WHERE vote_id IN (SELECT id FROM survey_votes WHERE survey_id={?})
554 AND question_id={?}
555 ORDER BY RAND()
556 LIMIT 5;';
557 return $sql;
558 }
559 }
560 // }}}
561
562 // {{{ class SurveyText extends SurveySimple : simple text field, allowing a few words
563 class SurveyText extends SurveySimple
564 {
565 public function getQuestionType()
566 {
567 return "text";
568 }
569 }
570 // }}}
571
572 // {{{ class SurveyTextarea extends SurveySimple : textarea field, allowing longer comments
573 class SurveyTextarea extends SurveySimple
574 {
575 public function getQuestionType()
576 {
577 return "textarea";
578 }
579 }
580 // }}}
581
582 // {{{ class SurveyNum extends SurveySimple : allows numerical answers
583 class SurveyNum extends SurveySimple
584 {
585 public function checkAnswer($ans)
586 {
587 return array(intval($ans));
588 }
589
590 protected function getQuestionType()
591 {
592 return "num";
593 }
594 }
595 // }}}
596 // }}}
597
598 // {{{ abstract class SurveyList and its derived classes : restricted questions that allows only a list of possible answers
599 // {{{ abstract class SurveyList extends SurveyQuestion
600 abstract class SurveyList extends SurveyQuestion
601 {
602 protected $choices;
603
604 public function update($args)
605 {
606 parent::update($args);
607 $this->choices = array();
608 foreach ($args['options'] as $val) {
609 if (trim($val)) {
610 $this->choices[] = $val;
611 }
612 }
613 }
614
615 public function toArray()
616 {
617 $rArr = parent::toArray();
618 $rArr['choices'] = $this->choices;
619 return $rArr;
620 }
621
622 public function buildResultRequest()
623 {
624 $sql = 'SELECT answer, COUNT(id) AS count
625 FROM survey_answers
626 WHERE vote_id IN (SELECT id FROM survey_votes WHERE survey_id={?})
627 AND question_id={?}
628 GROUP BY answer ASC';
629 return $sql;
630 }
631
632 public function getCSVColumn()
633 {
634 $r = parent::getCSVColumn();
635 if (empty($this->choices)) {
636 return $r;
637 }
638 $r .= ' [0 => '.$this->choices[0];
639 for ($k = 1; $k < count($this->choices); $k++) {
640 $r .= ', '.$k.' => '.$this->choices[$k];
641 }
642 $r .= ']';
643 return $r;
644 }
645 }
646 // }}}
647
648 // {{{ class SurveyRadio extends SurveyList : radio question, allows one answer among the list offered
649 class SurveyRadio extends SurveyList
650 {
651 public function checkAnswer($ans)
652 {
653 return (array_key_exists($ans, $this->choices))? array($ans) : null;
654 }
655
656 protected function getQuestionType()
657 {
658 return "radio";
659 }
660 }
661 // }}}
662
663 // {{{ class SurveyCheckbox extends SurveyList : checkbox question, allows any number of answers among the list offered
664 class SurveyCheckbox extends SurveyList
665 {
666 public function checkAnswer($ans)
667 {
668 $rep = array();
669 foreach ($ans as $a) {
670 $a = intval($a);
671 if (array_key_exists($a, $this->choices)) {
672 $rep[] = $a;
673 }
674 }
675 return (count($rep) == 0)? null : $rep;
676 }
677
678 protected function getQuestionType()
679 {
680 return "checkbox";
681 }
682 }
683 // }}}
684 // }}}
685
686 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
687 ?>