f1f8fe54edc3a7a3952c06fbdf1a6652474bfc4c
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 if ($this->promos
== '') {
104 $promos = explode('|', $this->promos
);
105 foreach ($promos as $p) {
106 if ((preg_match('#^\d{4}$#', $p) && $p == $promo) ||
107 (preg_match('#^\d{4}-$#', $p) && intval(substr($p, 0, 4)) <= $promo) ||
108 (preg_match('#^-\d{4}$#', $p) && intval(substr($p, 1)) >= $promo) ||
109 (preg_match('#^\d{4}-\d{4}$#', $p) && intval(substr($p, 0, 4)) <= $promo && intval(substr($p, 5)) >= $promo)) {
116 public function isValid()
121 public function isEnded()
123 return (strtotime($this->end
) - time() <= 0);
126 public function getTitle()
132 // {{{ function toArray() : converts a question (or the whole survey) to array, with results if the survey is ended
133 public function toArray($i = 'all')
135 if ($i != 'all' && $i != 'root') { // if a specific question is requested, then just returns this question converted to array
137 if (array_key_exists($i, $this->questions
)) {
138 return $this->questions
[$i]->toArray();
142 } else { // else returns the root converted to array in any case
143 $a = array('title' => $this->title
,
144 'description' => $this->description
,
146 'mode' => $this->mode
,
147 'promos' => $this->promos
,
148 'valid' => $this->valid
,
150 if ($this->id
!= -1) {
151 $a['id'] = $this->id
;
153 if ($this->isEnded()) { // if the survey is ended, then adds here the number of votes
154 $sql = 'SELECT COUNT(id)
156 WHERE survey_id={?};';
157 $tot = XDB
::query($sql, $this->id
);
158 $a['votes'] = $tot->fetchOneCell();
160 if ($i == 'all' && count($this->questions
) > 0) { // if the whole survey is requested, then returns all the questions converted to array
162 for ($k = 0; $k < count($this->questions
); $k++
) {
163 $q = $this->questions
[$k]->toArray();
165 if ($this->isEnded()) { // if the survey is ended, then adds here the results of this question
166 $sql = $this->questions
[$k]->buildResultRequest();
168 $q['result'] = XDB
::iterator($sql, $this->id
, $k);
173 $a['questions'] = $qArr;
180 // {{{ function toCSV() : builds a CSV file containing all the results of the survey
181 public function toCSV($sep = ',', $enc = '"', $asep='|')
183 $nbq = count($this->questions
);
184 //require_once dirname(__FILE__) . '/../../classes/varstream.php';
188 $csv = fopen('var://csv_output', 'w');
189 $line = ($this->isMode(self
::MODE_XIDENT
))?
array('id', 'Nom', 'Prenom', 'Promo') : array('id');
190 for ($qid = 0; $qid < $nbq; $qid++
) {
191 $line[] = $this->questions
[$qid]->getCSVColumn(); // the fist line contains the questions
194 if ($this->isMode(self
::MODE_XIDENT
)) { // if the mode is non anonymous
195 $sql = 'SELECT v.id AS vid, a.nom, a.prenom, a.promo
196 FROM survey_votes AS v
197 INNER JOIN auth_user_md5 AS a
198 ON a.user_id=v.user_id
199 WHERE v.survey_id={?}
201 $res = XDB
::iterator($sql, $this->id
); // retrieves all users data
202 for ($u = $res->next(); $u != null
; $u = $res->next()) {
203 $users[$u['vid']] = array('nom' => $u['nom'], 'prenom' => $u['prenom'], 'promo' => $u['promo']);
206 $sql = 'SELECT v.id AS vid, a.question_id AS qid, a.answer
207 FROM survey_votes AS v
208 LEFT JOIN survey_answers AS a
210 WHERE v.survey_id={?}
211 ORDER BY vid ASC, qid ASC;';
212 $res = XDB
::iterator($sql, $this->id
); // retrieves all answers from database
216 $first = ($this->isMode(self
::MODE_XIDENT
))?
4 : 1;
217 while ($cur != null
) {
218 if ($vid != $cur['vid']) { // if the vote id changes, then starts a new line
219 fputcsv($csv, $line, $sep, $enc); // stores the former line into $csv_output
221 $line = array_fill(0, $first +
$nbq, ''); // creates an array full of empty string
222 $line[0] = $vid_; // the first field is a 'clean' vote id (not the one stored in database)
223 if ($this->isMode(self
::MODE_XIDENT
)) { // if the mode is non anonymous
224 if (array_key_exists($vid, $users) && is_array($users[$vid])) { // and if the user data can be found
225 $line[1] = $users[$vid]['nom']; // adds the user data (in the first fields of the line)
226 $line[2] = $users[$vid]['prenom'];
227 $line[3] = $users[$vid]['promo'];
232 $fid = $first +
$cur['qid']; // computes the field id
233 if ($line[$fid] != '') { // if this field already contains something
234 $line[$fid] .= $asep; // then adds a separator before adding the new answer
236 $line[$fid] .= $cur['answer']; // adds the current answer to the correct field
237 $cur = $res->next(); // gets next answer
239 fputcsv($csv, $line, $sep, $enc); // stores the last line into $csv_output
244 // {{{ function factory($type, $args) : builds a question according to the given type
245 public function factory($t, $args)
249 return new SurveyText($args);
251 return new SurveyTextarea($args);
253 return new SurveyNum($args);
255 return new SurveyRadio($args);
257 return new SurveyCheckbox($args);
259 return new SurveyPersonal($args);
266 // {{{ questions manipulation functions
267 public function addQuestion($i, $c)
269 if ($this->valid ||
$i > count($this->questions
)) {
272 array_splice($this->questions
, $i, 0, array($c));
277 public function delQuestion($i)
279 if ($this->valid ||
!array_key_exists($i, $this->questions
)) {
282 array_splice($this->questions
, $i, 1);
287 public function editQuestion($i, $a)
293 if ($this->valid ||
!array_key_exists($i, $this->questions
)) {
296 $this->questions
[$i]->update($a);
303 // {{{ function checkSyntax() : checks syntax of the questions (currently the root only) before storing the survey in database
304 private static $errorMessages = array(
305 "dateformat" => "la date de fin de sondage est mal formattée : elle doit respecter la syntaxe dd/mm/aaaa",
306 "datepassed" => "la date de fin de sondage est déjà dépassée : vous devez préciser une date future",
307 "promoformat" => "les restrictions à certaines promotions sont mal formattées"
310 public function checkSyntax()
313 if (!preg_match('#^\d{4}-\d{2}-\d{2}$#', $this->end
)) {
314 $rArr[] = array('question' => 'root', 'error' => self
::$errorMessages["dateformat"]);
316 // checks that the end date given is not already passed
317 // (unless the survey has already been validated : an admin can have a validated survey expired)
318 if (!$this->valid
&& $this->isEnded()) {
319 $rArr[] = array('question' => 'root', 'error' => self
::$errorMessages["datepassed"]);
322 if ($this->promos
!= '' && !preg_match('#^(\d{4}-?|(\d{4})?-\d{4})(,(\d{4}-?|(\d{4})?-\d{4}))*$#', $this->promos
)) {
323 $rArr[] = array('question' => 'root', 'error' => self
::$errorMessages["promoformat"]);
325 return (empty($rArr))? null
: $rArr;
329 // {{{ functions that manipulate surveys in database
330 // {{{ static function retrieveList() : gets the list of available survey (current, old and not validated surveys)
331 public static function retrieveList($type, $tpl = true
)
340 $where = 'valid=1 AND end > NOW()';
344 $where = 'valid=1 AND end <= NOW()';
349 $sql = 'SELECT id, title, end, mode
353 return XDB
::iterator($sql);
355 return XDB
::iterRow($sql);
360 // {{{ static function retrieveSurvey() : gets a survey in database (and unserialize the survey object structure)
361 public static function retrieveSurvey($sid)
363 $sql = 'SELECT questions, title, description, end, mode, promos, valid
366 $res = XDB
::query($sql, $sid);
367 $data = $res->fetchOneAssoc();
368 if (is_null($data) ||
!is_array($data)) {
371 $survey = new Survey($data, $sid, (boolean
) $data['valid'], unserialize($data['questions']));
376 // {{{ static function retrieveSurveyInfo() : gets information about a survey (title, description, end date, restrictions) but does not unserialize the survey object structure
377 public static function retrieveSurveyInfo($sid)
379 $sql = 'SELECT title, description, end, mode, promos, valid
382 $res = XDB
::query($sql, $sid);
383 return $res->fetchOneAssoc();
387 // {{{ function proposeSurvey() : stores a proposition of survey in database (before validation)
388 public function proposeSurvey()
390 $sql = 'INSERT INTO survey_surveys
399 return XDB
::execute($sql, serialize($this->questions
), $this->title
, $this->description
, S
::v('uid'), $this->end
, $this->mode
, $this->promos
);
403 // {{{ function updateSurvey() : updates a survey in database (before validation)
404 public function updateSurvey()
406 if ($this->id
== -1) {
409 $sql = 'UPDATE survey_surveys
417 return XDB
::execute($sql, serialize($this->questions
), $this->title
, $this->description
, $this->end
, $this->mode
, $this->promos
, $this->id
);
421 // {{{ static function validateSurvey() : validates a survey
422 public static function validateSurvey($sid)
424 $sql = 'UPDATE survey_surveys
427 return XDB
::execute($sql, $sid);
431 // {{{ functions vote() and hasVoted() : handles vote to a survey
432 public function vote($uid, $args)
434 XDB
::execute('INSERT INTO survey_votes
435 SET survey_id={?}, user_id={?};', $this->id
, $uid); // notes the user as having voted
436 $vid = XDB
::insertId();
437 for ($i = 0; $i < count($this->questions
); $i++
) {
438 $ans = $this->questions
[$i]->checkAnswer($args[$i]);
439 if (!is_null($ans) && is_array($ans)) {
440 foreach ($ans as $a) {
441 XDB
::execute('INSERT INTO survey_answers
444 answer = {?}', $vid, $i, $a);
450 public function hasVoted($uid)
452 $res = XDB
::query('SELECT id
454 WHERE survey_id={?} AND user_id={?};', $this->id
, $uid); // checks whether the user has already voted
455 return ($res->numRows() != 0);
459 // {{{ static function deleteSurvey() : deletes a survey (and all its votes)
460 public static function deleteSurvey($sid)
462 $sql = 'DELETE s.*, v.*, a.*
463 FROM survey_surveys AS s
464 LEFT JOIN survey_votes AS v
466 LEFT JOIN survey_answers AS a
469 return XDB
::execute($sql, $sid);
473 // {{{ static function purgeVotes() : clears all votes concerning a survey (I'm not sure whether it's really useful)
474 public static function purgeVotes($sid)
476 $sql = 'DELETE v.*, a.*
477 FROM survey_votes AS v
478 LEFT JOIN survey_answers AS a
480 WHERE v.survey_id={?};';
481 return XDB
::execute($sql, $sid);
489 // {{{ abstract class SurveyQuestion
490 abstract class SurveyQuestion
492 // {{{ common properties, constructor, and basic methods
496 public function __construct($args)
498 $this->update($args);
501 public function update($a)
503 $this->question
= $a['question'];
504 $this->comment
= $a['comment'];
507 abstract protected function getQuestionType();
510 // {{{ function toArray() : converts to array
511 public function toArray()
513 return array('type' => $this->getQuestionType(), 'question' => $this->question
, 'comment' => $this->comment
);
517 // {{{ function checkSyntax() : checks question elements (before storing into database), not currently needed (with new structure)
518 protected function checkSyntax()
524 // {{{ function checkAnswer : returns a correctly formatted answer (or nothing empty string if error)
525 public function checkAnswer($ans)
531 // {{{ functions regarding the results of a survey
532 public function buildResultRequest()
537 public function getCSVColumn()
539 return $this->question
;
545 // {{{ abstract class SurveySimple and its derived classes : "opended" questions
546 // {{{ abstract class SurveySimple extends SurveyQuestion
547 abstract class SurveySimple
extends SurveyQuestion
549 public function checkAnswer($ans)
554 public function buildResultRequest()
556 $sql = 'SELECT answer
558 WHERE vote_id IN (SELECT id FROM survey_votes WHERE survey_id={?})
567 // {{{ class SurveyText extends SurveySimple : simple text field, allowing a few words
568 class SurveyText
extends SurveySimple
570 public function getQuestionType()
577 // {{{ class SurveyTextarea extends SurveySimple : textarea field, allowing longer comments
578 class SurveyTextarea
extends SurveySimple
580 public function getQuestionType()
587 // {{{ class SurveyNum extends SurveySimple : allows numerical answers
588 class SurveyNum
extends SurveySimple
590 public function checkAnswer($ans)
592 return array(intval($ans));
595 protected function getQuestionType()
603 // {{{ abstract class SurveyList and its derived classes : restricted questions that allows only a list of possible answers
604 // {{{ abstract class SurveyList extends SurveyQuestion
605 abstract class SurveyList
extends SurveyQuestion
609 public function update($args)
611 parent
::update($args);
612 $this->choices
= explode('|', $args['options']);
615 public function toArray()
617 $rArr = parent
::toArray();
618 $rArr['choices'] = $this->choices
;
619 $rArr['options'] = implode('|', $this->choices
);
623 public function buildResultRequest()
625 $sql = 'SELECT answer, COUNT(id) AS count
627 WHERE vote_id IN (SELECT id FROM survey_votes WHERE survey_id={?})
629 GROUP BY answer ASC';
633 public function getCSVColumn()
635 $r = parent
::getCSVColumn();
636 if (empty($this->choices
)) {
639 $r .= ' [0 => '.$this->choices
[0];
640 for ($k = 1; $k < count($this->choices
); $k++
) {
641 $r .= ', '.$k.' => '.$this->choices
[$k];
649 // {{{ class SurveyRadio extends SurveyList : radio question, allows one answer among the list offered
650 class SurveyRadio
extends SurveyList
652 public function checkAnswer($ans)
654 return (array_key_exists($ans, $this->choices
))?
array($ans) : null
;
657 protected function getQuestionType()
664 // {{{ class SurveyCheckbox extends SurveyList : checkbox question, allows any number of answers among the list offered
665 class SurveyCheckbox
extends SurveyList
667 public function checkAnswer($ans)
670 foreach ($ans as $a) {
672 if (array_key_exists($a, $this->choices
)) {
676 return (count($rep) == 0)? null
: $rep;
679 protected function getQuestionType()
687 // {{{ class SurveyPersonal extends SurveyQuestion : allows easy and verified access to user's personal data (promotion, name...)
688 // actually this type of question should be suppressed (non anonymous surveys are possible with survey modes)
689 // and anyway it is not finished (checkAnswer implementation) : currently it does not store anything when a user votes
690 class SurveyPersonal
extends SurveyQuestion
694 public function update($args)
696 $args['question'] = "Informations personnelles";
697 parent
::update($args);
698 $this->perm
['promo'] = isset($args['promo'])?
1 : 0;
699 $this->perm
['name'] = isset($args['name'])?
1 : 0;
702 public function checkAnswer($ans)
704 if (intval($ans) == 1) {
712 protected function getQuestionType()
717 public function toArray()
719 $a = parent
::toArray();
720 $a['promo'] = $this->perm
['promo'];
721 $a['name'] = $this->perm
['name'];
727 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: