02ccef64108d5fbb256640881c7b771b117cfc82
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',
43 'radio' => 'Choix multiples (une réponse)',
44 'checkbox' => 'Choix multiples (plusieurs réponses)');
46 public static function getTypes()
51 public static function isType($t)
53 return array_key_exists($t, self
::$types);
57 // {{{ properties, constructor and basic methods
67 public function __construct($args, $id = -1, $valid = false
, $questions = null
)
71 $this->valid
= $valid;
72 $this->questions
= ($questions == null
)?
array() : $questions;
75 public function update($args)
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
) {
84 $this->promos
= ($args['promos'] == '' ||
preg_match('#^(\d{4}-?|(\d{4})?-\d{4})(,(\d{4}-?|(\d{4})?-\d{4}))*$#', $args['promos']))?
$args['promos'] : '#';
88 // {{{ functions to access general information
89 public function isMode($mode)
91 return ($this->mode
== $mode);
94 public function checkPromo($promo)
96 if ($this->promos
== '') {
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)) {
111 public function isValid()
116 public function isEnded()
118 return (strtotime($this->end
) - time() <= 0);
121 public function getTitle()
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')
130 if ($i != 'all' && $i != 'root') { // if a specific question is requested, then just returns this question converted to array
132 if (array_key_exists($i, $this->questions
)) {
133 return $this->questions
[$i]->toArray();
137 } else { // else returns the root converted to array in any case
138 $a = array('title' => $this->title
,
139 'description' => $this->description
,
141 'mode' => $this->mode
,
142 'promos' => $this->promos
,
143 'valid' => $this->valid
,
145 if ($this->id
!= -1) {
146 $a['id'] = $this->id
;
148 if ($this->isEnded()) { // if the survey is ended, then adds here the number of votes
149 $sql = 'SELECT COUNT(id)
151 WHERE survey_id={?};';
152 $tot = XDB
::query($sql, $this->id
);
153 $a['votes'] = $tot->fetchOneCell();
155 if ($i == 'all' && count($this->questions
) > 0) { // if the whole survey is requested, then returns all the questions converted to array
157 for ($k = 0; $k < count($this->questions
); $k++
) {
158 $q = $this->questions
[$k]->toArray();
160 if ($this->isEnded()) { // if the survey is ended, then adds here the results of this question
161 $sql = $this->questions
[$k]->buildResultRequest();
163 $q['result'] = XDB
::iterator($sql, $this->id
, $k);
168 $a['questions'] = $qArr;
175 // {{{ function toCSV() : builds a CSV file containing all the results of the survey
176 public function toCSV($sep = ',', $enc = '"', $asep='|')
178 $nbq = count($this->questions
);
179 //require_once dirname(__FILE__) . '/../../classes/varstream.php';
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
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={?}
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']);
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
205 WHERE v.survey_id={?}
206 ORDER BY vid ASC, qid ASC;';
207 $res = XDB
::iterator($sql, $this->id
); // retrieves all answers from database
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
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'];
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
231 $line[$fid] .= $cur['answer']; // adds the current answer to the correct field
232 $cur = $res->next(); // gets next answer
234 fputcsv($csv, $line, $sep, $enc); // stores the last line into $csv_output
239 // {{{ function factory($type, $args) : builds a question according to the given type
240 public function factory($t, $args)
244 return new SurveyText($args);
246 return new SurveyTextarea($args);
248 return new SurveyNum($args);
250 return new SurveyRadio($args);
252 return new SurveyCheckbox($args);
254 return new SurveyPersonal($args);
261 // {{{ questions manipulation functions
262 public function addQuestion($i, $c)
265 if ($this->valid ||
$i > count($this->questions
)) {
268 array_splice($this->questions
, $i, 0, array($c));
273 public function delQuestion($i)
276 if ($this->valid ||
!array_key_exists($i, $this->questions
)) {
279 array_splice($this->questions
, $i, 1);
284 public function editQuestion($i, $a)
290 if ($this->valid ||
!array_key_exists($i, $this->questions
)) {
293 $this->questions
[$i]->update($a);
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éjà dépassée : vous devez préciser une date future",
303 "promoformat" => "les restrictions à certaines promotions sont mal formattées"
306 public function checkSyntax()
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"]);
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"]);
317 return (empty($rArr))? null
: $rArr;
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
)
328 $where = 'end > NOW()';
332 $where = 'end <= NOW()';
337 $sql = 'SELECT id, title, end, mode
341 return XDB
::iterator($sql);
343 return XDB
::iterRow($sql);
348 // {{{ static function retrieveSurvey() : gets a survey in database (and unserialize the survey object structure)
349 public static function retrieveSurvey($sid)
351 $sql = 'SELECT questions, title, description, end, mode, promos
354 $res = XDB
::query($sql, $sid);
355 $data = $res->fetchOneAssoc();
356 if (is_null($data) ||
!is_array($data)) {
359 $survey = new Survey($data, $sid, true
, unserialize($data['questions']));
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)
367 $sql = 'SELECT title, description, end, mode, promos
370 $res = XDB
::query($sql, $sid);
371 return $res->fetchOneAssoc();
375 // {{{ static function retrieveSurveyReq() : gets a survey request to validate
376 public static function retrieveSurveyReq($id)
378 require_once 'validations.inc.php';
379 $surveyreq = Validate
::get_request_by_id($id);
380 if ($surveyreq == null
) {
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
);
393 // {{{ function proposeSurvey() : stores a proposition of survey in database (before validation)
394 public function proposeSurvey()
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();
402 // {{{ function updateSurvey() : updates a survey in database (before validation)
403 public function updateSurvey()
406 $sql = 'UPDATE survey_surveys
414 return XDB
::execute($sql, serialize($this->questions
), $this->title
, $this->description
, $this->end
, $this->mode
, $this->promos
, $this->id
);
416 require_once 'validations.inc.php';
417 $surveyreq = Validate
::get_request_by_id($this->id
);
418 if ($surveyreq == null
) {
421 return $surveyreq->updateReq($this->title
, $this->description
, $this->end
, $this->mode
, $this->promos
, $this->questions
);
426 // {{{ functions vote() and hasVoted() : handles vote to a survey
427 public function vote($uid, $args)
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
439 answer = {?}', $vid, $i, $a);
445 public function hasVoted($uid)
447 $res = XDB
::query('SELECT id
449 WHERE survey_id={?} AND user_id={?};', $this->id
, $uid); // checks whether the user has already voted
450 return ($res->numRows() != 0);
454 // {{{ static function deleteSurvey() : deletes a survey (and all its votes)
455 public static function deleteSurvey($sid)
457 $sql = 'DELETE s.*, v.*, a.*
458 FROM survey_surveys AS s
459 LEFT JOIN survey_votes AS v
461 LEFT JOIN survey_answers AS a
464 return XDB
::execute($sql, $sid);
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)
471 $sql = 'DELETE v.*, a.*
472 FROM survey_votes AS v
473 LEFT JOIN survey_answers AS a
475 WHERE v.survey_id={?};';
476 return XDB
::execute($sql, $sid);
484 // {{{ abstract class SurveyQuestion
485 abstract class SurveyQuestion
487 // {{{ common properties, constructor, and basic methods
491 public function __construct($args)
493 $this->update($args);
496 public function update($a)
498 $this->question
= $a['question'];
499 $this->comment
= $a['comment'];
502 abstract protected function getQuestionType();
505 // {{{ function toArray() : converts to array
506 public function toArray()
508 return array('type' => $this->getQuestionType(), 'question' => $this->question
, 'comment' => $this->comment
);
512 // {{{ function checkSyntax() : checks question elements (before storing into database), not currently needed (with new structure)
513 protected function checkSyntax()
519 // {{{ function checkAnswer : returns a correctly formatted answer (or nothing empty string if error)
520 public function checkAnswer($ans)
526 // {{{ functions regarding the results of a survey
527 public function buildResultRequest()
532 public function getCSVColumn()
534 return $this->question
;
540 // {{{ abstract class SurveySimple and its derived classes : "open" questions
541 // {{{ abstract class SurveySimple extends SurveyQuestion
542 abstract class SurveySimple
extends SurveyQuestion
544 public function checkAnswer($ans)
549 public function buildResultRequest()
551 $sql = 'SELECT answer
553 WHERE vote_id IN (SELECT id FROM survey_votes WHERE survey_id={?})
562 // {{{ class SurveyText extends SurveySimple : simple text field, allowing a few words
563 class SurveyText
extends SurveySimple
565 public function getQuestionType()
572 // {{{ class SurveyTextarea extends SurveySimple : textarea field, allowing longer comments
573 class SurveyTextarea
extends SurveySimple
575 public function getQuestionType()
582 // {{{ class SurveyNum extends SurveySimple : allows numerical answers
583 class SurveyNum
extends SurveySimple
585 public function checkAnswer($ans)
587 return array(intval($ans));
590 protected function getQuestionType()
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
604 public function update($args)
606 parent
::update($args);
607 $this->choices
= array();
608 foreach ($args['options'] as $val) {
610 $this->choices
[] = $val;
615 public function toArray()
617 $rArr = parent
::toArray();
618 $rArr['choices'] = $this->choices
;
622 public function buildResultRequest()
624 $sql = 'SELECT answer, COUNT(id) AS count
626 WHERE vote_id IN (SELECT id FROM survey_votes WHERE survey_id={?})
628 GROUP BY answer ASC';
632 public function getCSVColumn()
634 $r = parent
::getCSVColumn();
635 if (empty($this->choices
)) {
638 $r .= ' [0 => '.$this->choices
[0];
639 for ($k = 1; $k < count($this->choices
); $k++
) {
640 $r .= ', '.$k.' => '.$this->choices
[$k];
648 // {{{ class SurveyRadio extends SurveyList : radio question, allows one answer among the list offered
649 class SurveyRadio
extends SurveyList
651 public function checkAnswer($ans)
653 return (array_key_exists($ans, $this->choices
))?
array($ans) : null
;
656 protected function getQuestionType()
663 // {{{ class SurveyCheckbox extends SurveyList : checkbox question, allows any number of answers among the list offered
664 class SurveyCheckbox
extends SurveyList
666 public function checkAnswer($ans)
669 foreach ($ans as $a) {
671 if (array_key_exists($a, $this->choices
)) {
675 return (count($rep) == 0)? null
: $rep;
678 protected function getQuestionType()
686 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: