9b923604f41fcd502869ed4b8c3d5e3f2497ad28
2 /***************************************************************************
3 * Copyright (C) 2003-2007 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
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. *
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. *
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 *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
22 // {{{ class Survey : root of any survey, contains all questions
25 // {{{ static properties and functions, regarding survey modes and question types
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");
36 public static function getModes($long = true
) {
37 return ($long)? self
::$longModes : self
::$shortModes;
40 private static $types = array('text' => 'texte court',
41 'textarea' => 'texte long',
42 'num' => 'numérique',
44 'checkbox' => 'checkbox',
45 'personal' => 'informations personnelles');
47 public static function getTypes()
52 public static function isType($t)
54 return array_key_exists($t, self
::$types);
58 // {{{ properties, constructor and basic methods
68 public function __construct($args, $id = -1, $valid = false
, $questions = null
)
72 $this->valid
= $valid;
73 $this->questions
= ($questions == null
)?
array() : $questions;
76 public function update($args)
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']);
83 $this->end
= (preg_match('#^\d{4}-\d{2}-\d{2}$#', $args['end']))?
$args['end'] : '#';
85 $this->mode
= $args['mode'];
86 if ($args['mode'] == 0) {
89 $this->promos
= ($args['promos'] == '' ||
preg_match('#^(\d{4}-?|(\d{4})?-\d{4})(,(\d{4}-?|(\d{4})?-\d{4}))*$#', $args['promos']))?
$args['promos'] : '#';
93 // {{{ functions to access general information
94 public function isMode($mode)
96 return ($this->mode
== $mode);
99 public function checkPromo($promo)
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)) {
113 public function isValid()
118 public function isEnded()
120 return (strtotime($this->end
) - time() <= 0);
123 public function getTitle()
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')
132 if ($i != 'all' && $i != 'root') { // if a specific question is requested, then just returns this question converted to array
134 if (array_key_exists($i, $this->questions
)) {
135 return $this->questions
[$i]->toArray();
139 } else { // else returns the root converted to array in any case
140 $a = array('title' => $this->title
,
141 'description' => $this->description
,
143 'mode' => $this->mode
,
144 'promos' => $this->promos
,
145 'valid' => $this->valid
,
147 if ($this->id
!= -1) {
148 $a['id'] = $this->id
;
150 if ($this->isEnded()) { // if the survey is ended, then adds here the number of votes
151 $sql = 'SELECT COUNT(id)
153 WHERE survey_id={?};';
154 $tot = XDB
::query($sql, $this->id
);
155 $a['votes'] = $tot->fetchOneCell();
157 if ($i == 'all' && count($this->questions
) > 0) { // if the whole survey is requested, then returns all the questions converted to array
159 for ($k = 0; $k < count($this->questions
); $k++
) {
160 $q = $this->questions
[$k]->toArray();
162 if ($this->isEnded()) { // if the survey is ended, then adds here the results of this question
163 $sql = $this->questions
[$k]->buildResultRequest();
165 $q['result'] = XDB
::iterator($sql, $this->id
, $k);
170 $a['questions'] = $qArr;
177 // {{{ function factory($type, $args) : builds a question according to the given type
178 public function factory($t, $args)
182 return new SurveyText($args);
184 return new SurveyTextarea($args);
186 return new SurveyNum($args);
188 return new SurveyRadio($args);
190 return new SurveyCheckbox($args);
192 return new SurveyPersonal($args);
199 // {{{ questions manipulation functions
200 public function addQuestion($i, $c)
202 if ($this->valid ||
$i > count($this->questions
)) {
205 array_splice($this->questions
, $i, 0, array($c));
210 public function delQuestion($i)
212 if ($this->valid ||
!array_key_exists($i, $this->questions
)) {
215 array_splice($this->questions
, $i, 1);
220 public function editQuestion($i, $a)
226 if ($this->valid ||
!array_key_exists($i, $this->questions
)) {
229 $this->questions
[$i]->update($a);
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ée : elle doit respecter la syntaxe dd/mm/aaaa",
239 "datepassed" => "la date de fin de sondage est déjà dépassée : vous devez préciser une date future",
240 "promoformat" => "les restrictions à certaines promotions sont mal formattées"
243 public function checkSyntax()
246 if (!preg_match('#^\d{4}-\d{2}-\d{2}$#', $this->end
)) {
247 $rArr[] = array('question' => 'root', 'error' => self
::$errorMessages["dateformat"]);
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"]);
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"]);
258 return (empty($rArr))? null
: $rArr;
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
)
273 $where = 'valid=1 AND end > NOW()';
277 $where = 'valid=1 AND end <= NOW()';
282 $sql = 'SELECT id, title, end, mode
286 return XDB
::iterator($sql);
288 return XDB
::iterRow($sql);
293 // {{{ static function retrieveSurvey() : gets a survey in database (and unserialize the survey object structure)
294 public static function retrieveSurvey($sid)
296 $sql = 'SELECT questions, title, description, end, mode, promos, valid
299 $res = XDB
::query($sql, $sid);
300 $data = $res->fetchOneAssoc();
301 if (is_null($data) ||
!is_array($data)) {
304 $survey = new Survey($data, $sid, (boolean
) $data['valid'], unserialize($data['questions']));
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)
312 $sql = 'SELECT title, description, end, mode, promos, valid
315 $res = XDB
::query($sql, $sid);
316 return $res->fetchOneAssoc();
320 // {{{ function proposeSurvey() : stores a proposition of survey in database (before validation)
321 public function proposeSurvey()
323 $sql = 'INSERT INTO survey_surveys
332 return XDB
::execute($sql, serialize($this->questions
), $this->title
, $this->description
, S
::v('uid'), $this->end
, $this->mode
, $this->promos
);
336 // {{{ function updateSurvey() : updates a survey in database (before validation)
337 public function updateSurvey()
339 if ($this->id
== -1) {
342 $sql = 'UPDATE survey_surveys
350 return XDB
::execute($sql, serialize($this->questions
), $this->title
, $this->description
, $this->end
, $this->mode
, $this->promos
, $this->id
);
354 // {{{ static function validateSurvey() : validates a survey
355 public static function validateSurvey($sid)
357 $sql = 'UPDATE survey_surveys
360 return XDB
::execute($sql, $sid);
364 // {{{ functions vote() and hasVoted() : handles vote to a survey
365 public function vote($uid, $args)
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
377 answer = {?}', $vid, $i, $a);
383 public function hasVoted($uid)
385 $res = XDB
::query('SELECT id
387 WHERE survey_id={?} AND user_id={?};', $this->id
, $uid); // checks whether the user has already voted
388 return ($res->numRows() != 0);
392 // {{{ static function deleteSurvey() : deletes a survey (and all its votes)
393 public static function deleteSurvey($sid)
395 $sql = 'DELETE s.*, v.*, a.*
396 FROM survey_surveys AS s
397 LEFT JOIN survey_votes AS v
399 LEFT JOIN survey_answers AS a
402 return XDB
::execute($sql, $sid);
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)
409 $sql = 'DELETE v.*, a.*
410 FROM survey_votes AS v
411 LEFT JOIN survey_answers AS a
413 WHERE v.survey_id={?};';
414 return XDB
::execute($sql, $sid);
422 // {{{ abstract class SurveyQuestion
423 abstract class SurveyQuestion
425 // {{{ common properties, constructor, and basic methods
429 public function __construct($args)
431 $this->update($args);
434 public function update($a)
436 $this->question
= $a['question'];
437 $this->comment
= $a['comment'];
440 abstract protected function getQuestionType();
443 // {{{ function toArray() : converts to array
444 public function toArray()
446 return array('type' => $this->getQuestionType(), 'question' => $this->question
, 'comment' => $this->comment
);
450 // {{{ function checkSyntax() : checks question elements (before storing into database), not currently needed (with new structure)
451 protected function checkSyntax()
457 // {{{ function checkAnswer : returns a correctly formatted answer (or nothing empty string if error)
458 public function checkAnswer($ans)
464 // {{{ function buildResultRequest() : statistics on the results of the survey
465 public function buildResultRequest()
473 // {{{ abstract class SurveySimple and its derived classes : "opended" questions
474 // {{{ abstract class SurveySimple extends SurveyQuestion
475 abstract class SurveySimple
extends SurveyQuestion
477 public function checkAnswer($ans)
482 public function buildResultRequest()
484 $sql = 'SELECT answer
486 WHERE vote_id IN (SELECT id FROM survey_votes WHERE survey_id={?})
495 // {{{ class SurveyText extends SurveySimple : simple text field, allowing a few words
496 class SurveyText
extends SurveySimple
498 public function getQuestionType()
505 // {{{ class SurveyTextarea extends SurveySimple : textarea field, allowing longer comments
506 class SurveyTextarea
extends SurveySimple
508 public function getQuestionType()
515 // {{{ class SurveyNum extends SurveySimple : allows numerical answers
516 class SurveyNum
extends SurveySimple
518 public function checkAnswer($ans)
520 return array(intval($ans));
523 protected function getQuestionType()
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
537 public function update($args)
539 parent
::update($args);
540 $this->choices
= explode('|', $args['options']);
543 public function toArray()
545 $rArr = parent
::toArray();
546 $rArr['choices'] = $this->choices
;
547 $rArr['options'] = implode('|', $this->choices
);
551 public function buildResultRequest()
553 $sql = 'SELECT answer, COUNT(id) AS count
555 WHERE vote_id IN (SELECT id FROM survey_votes WHERE survey_id={?})
557 GROUP BY answer ASC';
563 // {{{ class SurveyRadio extends SurveyList : radio question, allows one answer among the list offered
564 class SurveyRadio
extends SurveyList
566 public function checkAnswer($ans)
568 return (array_key_exists($ans, $this->choices
))?
array($ans) : null
;
571 protected function getQuestionType()
578 // {{{ class SurveyCheckbox extends SurveyList : checkbox question, allows any number of answers among the list offered
579 class SurveyCheckbox
extends SurveyList
581 public function checkAnswer($ans)
584 foreach ($ans as $a) {
586 if (array_key_exists($a, $this->choices
)) {
590 return (count($rep) == 0)? null
: $rep;
593 protected function getQuestionType()
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
608 public function update($args)
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;
616 public function checkAnswer($ans)
618 if (intval($ans) == 1) {
626 protected function getQuestionType()
631 public function toArray()
633 $a = parent
::toArray();
634 $a['promo'] = $this->perm
['promo'];
635 $a['name'] = $this->perm
['name'];
641 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: