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