Can disable email redirection
[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' => 'radio',
44 'checkbox' => 'checkbox',
45 'personal' => 'informations personnelles');
46
47 public static function getTypes()
48 {
49 return self::$types;
50 }
51
52 public static function isType($t)
53 {
54 return array_key_exists($t, self::$types);
55 }
56 // }}}
57
58 // {{{ properties, constructor and basic methods
59 private $id;
60 private $title;
61 private $description;
62 private $end;
63 private $mode;
64 private $promos;
65 private $valid;
66 private $questions;
67
68 public function __construct($args, $id = -1, $valid = false, $questions = null)
69 {
70 $this->update($args);
71 $this->id = $id;
72 $this->valid = $valid;
73 $this->questions = ($questions == null)? array() : $questions;
74 }
75
76 public function update($args)
77 {
78 $this->title = $args['title'];
79 $this->description = $args['description'];
80 if (preg_match('#^\d{2}/\d{2}/\d{4}$#', $args['end'])) {
81 $this->end = preg_replace('#^(\d{2})/(\d{2})/(\d{4})$#', '\3-\2-\1', $args['end']);
82 } else {
83 $this->end = (preg_match('#^\d{4}-\d{2}-\d{2}$#', $args['end']))? $args['end'] : '#';
84 }
85 $this->mode = $args['mode'];
86 if ($args['mode'] == 0) {
87 $args['promos'] = '';
88 }
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
93 // {{{ functions to access general information
94 public function isMode($mode)
95 {
96 return ($this->mode == $mode);
97 }
98
99 public function checkPromo($promo)
100 {
101 $promos = explode('|', $this->promos);
102 foreach ($promos as $p) {
103 if ((preg_match('#^\d{4}$#', $p) && $p == $promo) ||
104 (preg_match('#^\d{4}-$#', $p) && intval(substr($p, 0, 4)) <= $promo) ||
105 (preg_match('#^-\d{4}$#', $p) && intval(substr($p, 1)) >= $promo) ||
106 (preg_match('#^\d{4}-\d{4}$#', $p) && intval(substr($p, 0, 4)) <= $promo && intval(substr($p, 5)) >= $promo)) {
107 return true;
108 }
109 }
110 return false;
111 }
112
113 public function isValid()
114 {
115 return $this->valid;
116 }
117
118 public function isEnded()
119 {
120 return (strtotime($this->end) - time() <= 0);
121 }
122
123 public function getTitle()
124 {
125 return $this->title;
126 }
127 // }}}
128
129 // {{{ function toArray() : converts a question (or the whole survey) to array
130 public function toArray($i = 'all')
131 {
132 if ($i != 'all' && $i != 'root') {
133 $i = intval($i);
134 if (array_key_exists($i, $this->questions)) {
135 return $this->questions[$i]->toArray();
136 } else {
137 return null;
138 }
139 } else {
140 $a = array('title' => $this->title,
141 'description' => $this->description,
142 'end' => $this->end,
143 'mode' => $this->mode,
144 'promos' => $this->promos,
145 'valid' => $this->valid,
146 'type' => 'root');
147 if ($this->id != -1) {
148 $a['id'] = $this->id;
149 }
150 if ($i == 'all' && count($this->questions) > 0) {
151 $qArr = array();
152 for ($k = 0; $k < count($this->questions); $k++) {
153 $q = $this->questions[$k]->toArray();
154 $q['id'] = $k;
155 $qArr[$k] = $q;
156 }
157 $a['questions'] = $qArr;
158 }
159 return $a;
160 }
161 }
162 // }}}
163
164 // {{{ function factory($type, $args) : builds a question according to the given type
165 public function factory($t, $args)
166 {
167 switch ($t) {
168 case 'text':
169 return new SurveyText($args);
170 case 'textarea':
171 return new SurveyTextarea($args);
172 case 'num':
173 return new SurveyNum($args);
174 case 'radio':
175 return new SurveyRadio($args);
176 case 'checkbox':
177 return new SurveyCheckbox($args);
178 case 'personal':
179 return new SurveyPersonal($args);
180 default:
181 return null;
182 }
183 }
184 // }}}
185
186 // {{{ questions manipulation functions
187 public function addQuestion($i, $c)
188 {
189 if ($this->valid || $i > count($this->questions)) {
190 return false;
191 } else {
192 array_splice($this->questions, $i, 0, array($c));
193 return true;
194 }
195 }
196
197 public function delQuestion($i)
198 {
199 if ($this->valid || !array_key_exists($i, $this->questions)) {
200 return false;
201 } else {
202 array_splice($this->questions, $i, 1);
203 return true;
204 }
205 }
206
207 public function editQuestion($i, $a)
208 {
209 if ($i == 'root') {
210 $this->update($a);
211 } else {
212 $i = intval($i);
213 if ($this->valid ||!array_key_exists($i, $this->questions)) {
214 return false;
215 } else {
216 $this->questions[$i]->update($a);
217 }
218 }
219 return true;
220 }
221 // }}}
222
223 // {{{ function checkSyntax() : checks syntax of the questions (currently the root only) before storing the survey in database
224 private static $errorMessages = array(
225 "dateformat" => "la date de fin de sondage est mal formatt&#233;e : elle doit respecter la syntaxe dd/mm/aaaa",
226 "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",
227 "promoformat" => "les restrictions &#224; certaines promotions sont mal formatt&#233;es"
228 );
229
230 public function checkSyntax()
231 {
232 $rArr = array();
233 if (!preg_match('#^\d{4}-\d{2}-\d{2}$#', $this->end)) {
234 $rArr[] = array('question' => 'root', 'error' => self::$errorMessages["dateformat"]);
235 } else {
236 // checks that the end date given is not already passed
237 // (unless the survey has already been validated : an admin can have a validated survey expired)
238 if (!$this->valid && $this->isEnded()) {
239 $rArr[] = array('question' => 'root', 'error' => self::$errorMessages["datepassed"]);
240 }
241 }
242 if ($this->promos != '' && !preg_match('#^(\d{4}-?|(\d{4})?-\d{4})(,(\d{4}-?|(\d{4})?-\d{4}))*$#', $this->promos)) {
243 $rArr[] = array('question' => 'root', 'error' => self::$errorMessages["promoformat"]);
244 }
245 return (empty($rArr))? null : $rArr;
246 }
247 // }}}
248
249 // {{{ functions that manipulates surveys in database
250 // {{{ static function retrieveList() : gets the list of available survey (current, old and not validated surveys)
251 public static function retrieveList($type, $tpl = true)
252 {
253 switch ($type) {
254 case 'w':
255 case 'waiting' :
256 $where = 'valid=0';
257 break;
258 case 'c':
259 case 'current':
260 $where = 'valid=1 AND end > NOW()';
261 break;
262 case 'o':
263 case 'old':
264 $where = 'valid=1 AND end <= NOW()';
265 break;
266 default:
267 return null;
268 }
269 $sql = 'SELECT id, title, end, mode
270 FROM survey_surveys
271 WHERE '.$where.';';
272 if ($tpl) {
273 return XDB::iterator($sql);
274 } else {
275 return XDB::iterRow($sql);
276 }
277 }
278 // }}}
279
280 // {{{ static function retrieveSurvey() : gets a survey in database (and unserialize the survey object structure)
281 public static function retrieveSurvey($sid)
282 {
283 $sql = 'SELECT questions, title, description, end, mode, promos, valid
284 FROM survey_surveys
285 WHERE id={?}';
286 $res = XDB::query($sql, $sid);
287 $data = $res->fetchOneAssoc();
288 if (is_null($data) || !is_array($data)) {
289 return null;
290 }
291 $survey = new Survey($data, $sid, (boolean) $data['valid'], unserialize($data['questions']));
292 return $survey;
293 }
294 // }}}
295
296 // {{{ static function retrieveSurveyInfo() : gets information about a survey (title, description, end date, restrictions) but does not unserialize the survey object structure
297 public static function retrieveSurveyInfo($sid)
298 {
299 $sql = 'SELECT title, description, end, mode, promos, valid
300 FROM survey_surveys
301 WHERE id={?}';
302 $res = XDB::query($sql, $sid);
303 return $res->fetchOneAssoc();
304 }
305 // }}}
306
307 // {{{ function proposeSurvey() : stores a proposition of survey in database (before validation)
308 public function proposeSurvey()
309 {
310 $sql = 'INSERT INTO survey_surveys
311 SET questions={?},
312 title={?},
313 description={?},
314 author_id={?},
315 end={?},
316 mode={?},
317 promos={?},
318 valid=0;';
319 return XDB::execute($sql, serialize($this->questions), $this->title, $this->description, S::v('uid'), $this->end, $this->mode, $this->promos);
320 }
321 // }}}
322
323 // {{{ function updateSurvey() : updates a survey in database (before validation)
324 public function updateSurvey()
325 {
326 if ($this->id == -1) {
327 return false;
328 }
329 $sql = 'UPDATE survey_surveys
330 SET questions={?},
331 title={?},
332 description={?},
333 end={?},
334 mode={?},
335 promos={?}
336 WHERE id={?};';
337 return XDB::execute($sql, serialize($this->questions), $this->title, $this->description, $this->end, $this->mode, $this->promos, $this->id);
338 }
339 // }}}
340
341 // {{{ static function validateSurvey() : validates a survey
342 public static function validateSurvey($sid)
343 {
344 $sql = 'UPDATE survey_surveys
345 SET valid=1
346 WHERE id={?};';
347 return XDB::execute($sql, $sid);
348 }
349 // }}}
350
351 // {{{ functions vote() and hasVoted() : handles vote to a survey
352 public function vote($uid, $args)
353 {
354 XDB::execute('INSERT INTO survey_votes
355 SET survey_id={?}, user_id={?};', $this->id, $uid); // notes the user as having voted
356 $vid = XDB::insertId();
357 for ($i = 0; $i < count($this->questions); $i++) {
358 $ans = $this->questions[$i]->checkAnswer($args[$i]);
359 if ($ans != "") {
360 XDB::execute('INSERT INTO survey_answers
361 SET vote_id = {?},
362 question_id = {?},
363 answer = {?}', $vid, $i, $ans);
364 }
365 }
366 }
367
368 public function hasVoted($uid)
369 {
370 $res = XDB::query('SELECT id
371 FROM survey_votes
372 WHERE survey_id={?} AND user_id={?};', $this->id, $uid); // checks whether the user has already voted
373 return ($res->numRows() != 0);
374 }
375 // }}}
376
377 // {{{ static function deleteSurvey() : deletes a survey (and all its votes)
378 public static function deleteSurvey($sid)
379 {
380 $sql = 'DELETE s.*, v.*, a.*
381 FROM survey_surveys AS s
382 LEFT JOIN survey_votes AS v
383 ON v.survey_id=s.id
384 LEFT JOIN survey_answers AS a
385 ON a.vote_id=v.id
386 WHERE s.id={?};';
387 return XDB::execute($sql, $sid);
388 }
389 // }}}
390
391 // {{{ static function purgeVotes() : clears all votes concerning a survey (I'm not sure whether it's really useful)
392 public static function purgeVotes($sid)
393 {
394 $sql = 'DELETE v.*, a.*
395 FROM survey_votes AS v
396 LEFT JOIN survey_answers AS a
397 ON a.vote_id=v.id
398 WHERE v.survey_id={?};';
399 return XDB::execute($sql, $sid);
400 }
401 // }}}
402
403 // }}}
404 }
405 // }}}
406
407 // {{{ abstract class SurveyQuestion
408 abstract class SurveyQuestion
409 {
410 // {{{ common properties, constructor, and basic methods
411 private $question;
412 private $comment;
413
414 public function __construct($args)
415 {
416 $this->update($args);
417 }
418
419 public function update($a)
420 {
421 $this->question = $a['question'];
422 $this->comment = $a['comment'];
423 }
424
425 abstract protected function getQuestionType();
426 // }}}
427
428 // {{{ function toArray() : converts to array
429 public function toArray()
430 {
431 return array('type' => $this->getQuestionType(), 'question' => $this->question, 'comment' => $this->comment);
432 }
433 // }}}
434
435 // {{{ function checkSyntax() : checks question elements (before storing into database), not currently needed (with new structure)
436 protected function checkSyntax()
437 {
438 return null;
439 }
440 // }}}
441
442 // {{{ function checkAnswer : returns a correctly formatted answer (or nothing empty string if error)
443 public function checkAnswer($ans)
444 {
445 return "";
446 }
447 // }}}
448
449 // {{{ function resultArray() : statistics on the results of the survey
450 //abstract protected function resultArray($sid, $where);
451 // }}}
452 }
453 // }}}
454
455 // {{{ abstract class SurveySimple extends SurveyQuestion : "opened" questions
456 abstract class SurveySimple extends SurveyQuestion
457 {
458 public function checkAnswer($ans)
459 {
460 return $ans;
461 }
462 }
463
464 // {{{ class SurveyText extends SurveySimple : simple text field, allowing a few words
465 class SurveyText extends SurveySimple
466 {
467 public function getQuestionType()
468 {
469 return "text";
470 }
471 }
472 // }}}
473
474 // {{{ class SurveyTextarea extends SurveySimple : textarea field, allowing longer comments
475 class SurveyTextarea extends SurveySimple
476 {
477 public function getQuestionType()
478 {
479 return "textarea";
480 }
481 }
482 // }}}
483
484 // {{{ class SurveyNum extends SurveySimple : allows numerical answers
485 class SurveyNum extends SurveySimple
486 {
487 public function checkAnswer($ans)
488 {
489 return intval($ans);
490 }
491
492 protected function getQuestionType()
493 {
494 return "num";
495 }
496 }
497 // }}}
498 // }}}
499
500 // {{{ abstract class SurveyList extends SurveyTreeable : restricted questions that allows only a list of possible answers
501 abstract class SurveyList extends SurveyQuestion
502 {
503 protected $choices;
504
505 public function update($args)
506 {
507 parent::update($args);
508 $this->choices = explode('|', $args['options']);
509 }
510
511 public function toArray()
512 {
513 $rArr = parent::toArray();
514 $rArr['choices'] = $this->choices;
515 $rArr['options'] = implode('|', $this->choices);
516 return $rArr;
517 }
518
519 }
520
521 // {{{ class SurveyRadio extends SurveyList : radio question, allows one answer among the list offered
522 class SurveyRadio extends SurveyList
523 {
524 public function checkAnswer($ans)
525 {
526 return (array_key_exists($ans, $this->choices)) ? $ans : "";
527 }
528
529 protected function getQuestionType()
530 {
531 return "radio";
532 }
533 }
534 // }}}
535
536 // {{{ class SurveyCheckbox extends SurveyList : checkbox question, allows any number of answers among the list offered
537 class SurveyCheckbox extends SurveyList
538 {
539 public function checkAnswer($ans)
540 {
541 $rep = "|";
542 foreach ($ans as $a) {
543 if (array_key_exists($a,$this->choices)) {
544 $rep .= $a . "|";
545 }
546 }
547 return $rep;
548 }
549
550 protected function getQuestionType()
551 {
552 return "checkbox";
553 }
554 }
555 // }}}
556 // }}}
557
558 // {{{ class SurveyPersonal extends SurveyQuestion : allows easy and verified access to user's personal data (promotion, name...)
559 // actually this type of question should be suppressed (non anonymous surveys are possible with survey modes)
560 // and anyway it is not finished (checkAnswer implementation) : currently it does not store anything when a user votes
561 class SurveyPersonal extends SurveyQuestion
562 {
563 private $perm;
564
565 public function update($args)
566 {
567 $args['question'] = "Informations personnelles";
568 parent::update($args);
569 $this->perm['promo'] = isset($args['promo'])? 1 : 0;
570 $this->perm['name'] = isset($args['name'])? 1 : 0;
571 }
572
573 public function checkAnswer($ans)
574 {
575 if (intval($ans) == 1) {
576 // requete mysql qvb
577 return "";
578 } else {
579 return "";
580 }
581 }
582
583 protected function getQuestionType()
584 {
585 return "personal";
586 }
587
588 public function toArray()
589 {
590 $a = parent::toArray();
591 $a['promo'] = $this->perm['promo'];
592 $a['name'] = $this->perm['name'];
593 return $a;
594 }
595 }
596 // }}}
597
598 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
599 ?>