<?php
/***************************************************************************
- * Copyright (C) 2003-2007 Polytechnique.org *
+ * Copyright (C) 2003-2008 Polytechnique.org *
* http://opensource.polytechnique.org/ *
* *
* This program is free software; you can redistribute it and/or modify *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
***************************************************************************/
-// {{{ class Survey : static database managing functions
-class SurveyDB
+// {{{ class Survey : root of any survey, contains all questions
+class Survey
{
- // {{{ static function retrieveList() : gets the list of available survey (current, old and not validated surveys)
- public static function retrieveList($type, $tpl = true)
- {
- switch ($type) {
- case 'w':
- case 'waiting' :
- $where = 'valid=0';
- break;
- case 'c':
- case 'current':
- $where = 'valid=1 AND end > NOW()';
- break;
- case 'o':
- case 'old':
- $where = 'valid=1 AND end <= NOW()';
- break;
- default:
- return null;
- }
- $sql = 'SELECT survey_id, title, end
- FROM survey_questions
- WHERE '.$where.';';
- if ($tpl) {
- return XDB::iterator($sql);
- } else {
- return XDB::iterRow($sql);
- }
- }
- // }}}
-
- // {{{ static function proposeSurvey() : stores a proposition of survey in database (before validation)
- public static function proposeSurvey($survey)
- {
- $sql = 'INSERT INTO survey_questions
- SET questions={?},
- title={?},
- description={?},
- author_id={?},
- end={?},
- promos={?},
- valid=0;';
- $data = $survey->storeArray();
- return XDB::execute($sql, serialize($survey), $data['question'], $data['comment'], S::v('uid'), $data['end'], $data['promos']);
- }
- // }}}
-
- // {{{ static function updateSurvey() : updates a survey in database (before validation)
- public static function updateSurvey($survey, $sid)
- {
- $sql = 'UPDATE survey_questions
- SET questions={?},
- title={?},
- description={?},
- end={?},
- promos={?}
- WHERE survey_id={?};';
- $data = $survey->storeArray();
- return XDB::execute($sql, serialize($survey), $data['question'], $data['comment'], $data['end'], $data['promos'], $sid);
- }
- // }}}
-
- // {{{ static function retrieveSurvey() : gets a survey in database (and unserialize the survey object structure)
- public static function retrieveSurvey($sid)
- {
- $sql = 'SELECT questions, title, description, end, promos, valid
- FROM survey_questions
- WHERE survey_id={?}';
- $res = XDB::query($sql, $sid);
- $data = $res->fetchOneAssoc();
- if (is_null($data) || !is_array($data)) {
- return null;
- }
- $survey = unserialize($data['questions']);
- if (isset($data['end'])) {
- $data['end'] = preg_replace('#^(\d{4})-(\d{2})-(\d{2})$#', '\3/\2/\1', $data['end']);
- }
- $survey->update(array('question' => $data['title'], 'comment' => $data['description'], 'end' => $data['end'], 'promos' => $data['promos']));
- $survey->setValid($data['valid']);
- return $survey;
- }
- // }}}
-
- // {{{ static function retrieveSurveyInfo() : gets information about a survey (title, description, end date, restrictions) but does not unserialize the survey object structure
- public static function retrieveSurveyInfo($sid)
- {
- $sql = 'SELECT title, description, end, promos, valid
- FROM survey_questions
- WHERE survey_id={?}';
- $res = XDB::query($sql, $sid);
- return $res->fetchOneAssoc();
- }
- // }}}
-
- // {{{ static function validateSurvey() : validates a survey
- public static function validateSurvey($sid)
- {
- $sql = 'UPDATE survey_questions
- SET valid=1
- WHERE survey_id={?};';
- return XDB::execute($sql, $sid);
- }
- // }}}
-
- // {{{ static function deleteSurvey() : deletes a survey (and all its votes)
- public static function deleteSurvey($sid)
- {
- $sql1 = 'DELETE FROM survey_questions
- WHERE survey_id={?};';
- $sql2 = 'DELETE FROM survey_answers
- WHERE survey_id={?};';
- $sql3 = 'DELETE FROM survey_votes
- WHERE survey_id={?};';
- return (XDB::execute($sql1, $sid) && XDB::execute($sql2, $sid) && XDB::execute($sql3, $sid));
- }
- // }}}
-}
-// }}}
-
-// {{{ abstract class SurveyQuestion
-abstract class SurveyQuestion
-{
- // {{{ static properties and methods regarding question types
- private static $types = array('text' => 'texte court',
- 'textarea' => 'texte long',
- 'num' => 'numérique',
- 'radio' => 'radio',
- 'checkbox' => 'checkbox',
- 'personal' => 'informations personnelles');
+ // {{{ static properties and functions, regarding survey modes and question types
+ const MODE_ALL = 0;
+ const MODE_XANON = 1;
+ const MODE_XIDENT = 2;
+ private static $longModes = array(self::MODE_ALL => "sondage ouvert à tout le monde, anonyme",
+ self::MODE_XANON => "sondage restreint aux polytechniciens, anonyme",
+ self::MODE_XIDENT => "sondage restreint aux polytechniciens, non anonyme");
+ private static $shortModes = array(self::MODE_ALL => "tout le monde, anonyme",
+ self::MODE_XANON => "polytechniciens, anonyme",
+ self::MODE_XIDENT => "polytechniciens, non anonyme");
+
+ public static function getModes($long = true) {
+ return ($long)? self::$longModes : self::$shortModes;
+ }
+
+ private static $types = array('text' => 'Texte court',
+ 'textarea' => 'Texte long',
+ 'num' => 'Numérique',
+ 'radio' => 'Choix multiples (une réponse)',
+ 'checkbox' => 'Choix multiples (plusieurs réponses)',
+ 'radiotable' => 'Questions multiples à choix multiples (une réponse)',
+ 'checkboxtable' => 'Questions multiples à choix mutliples (plusieurs réponses)');
public static function getTypes()
{
}
// }}}
- // {{{ common properties, constructor, and basic methods
- private $survey_id;
+ // {{{ properties, constructor and basic methods
private $id;
- private $question;
- private $comment;
+ private $title;
+ private $description;
+ private $end;
+ private $mode;
+ private $promos;
+ private $valid;
+ private $questions;
- protected function __construct($i, $args)
+ public function __construct($args, $id = -1, $valid = false, $questions = null)
{
- $this->id = $i;
$this->update($args);
+ $this->id = $id;
+ $this->valid = $valid;
+ $this->questions = ($questions == null)? array() : $questions;
}
- protected function update($a)
- {
- $this->question = $a['question'];
- $this->comment = $a['comment'];
- }
-
- protected function getId()
+ public function update($args)
{
- return $this->id;
+ $this->title = $args['title'];
+ $this->description = $args['description'];
+ $this->end = $args['end'];
+ $this->mode = (isset($args['mode']))? $args['mode'] : self::MODE_ALL;
+ if ($this->mode == self::MODE_ALL) {
+ $args['promos'] = '';
+ }
+ $this->promos = ($args['promos'] == '' || preg_match('#^(\d{4}-?|(\d{4})?-\d{4})(,(\d{4}-?|(\d{4})?-\d{4}))*$#', $args['promos']))? $args['promos'] : '#';
}
-
- abstract protected function getQuestionType();
// }}}
- // {{{ tree manipulation methods : not implemented here (but definition needed)
- protected function addChildNested($i, $c)
- {
- return false;
- }
-
- protected function addChildAfter($i, $c)
- {
- return false;
- }
-
- protected function delChild($i)
+ // {{{ functions to access general information
+ public function isMode($mode)
{
- return false;
+ return ($this->mode == $mode);
}
- // }}}
- // {{{ function edit($i, $a) : searches and edits question $i
- protected function edit($i, $a)
+ public function checkPromo($promo)
{
- if ($this->id == $i) {
- $this->update($a);
+ if ($this->promos == '') {
return true;
- } else {
- return false;
}
+ $promos = explode(',', $this->promos);
+ foreach ($promos as $p) {
+ if ((preg_match('#^\d{4}$#', $p) && $p == $promo) ||
+ (preg_match('#^\d{4}-$#', $p) && intval(substr($p, 0, 4)) <= $promo) ||
+ (preg_match('#^-\d{4}$#', $p) && intval(substr($p, 1)) >= $promo) ||
+ (preg_match('#^\d{4}-\d{4}$#', $p) && intval(substr($p, 0, 4)) <= $promo && intval(substr($p, 5)) >= $promo)) {
+ return true;
+ }
+ }
+ return false;
}
- // }}}
- // {{{ functions toArray() and searchToArray($i) : (searches and) converts to array
- protected function toArray()
+ public function isValid()
{
- return $this->storeArray();
+ return $this->valid;
}
- protected function searchToArray($i)
+ public function isEnded()
{
- if ($this->id == $i) {
- return $this->storeArray();
- } else {
- return null;
- }
+ return (strtotime($this->end) - time() <= 0);
}
- protected function storeArray()
+ public function getTitle()
{
- return array('type' => $this->getQuestionType(), 'id' => $this->id, 'question' => $this->question, 'comment' => $this->comment);
+ return $this->title;
}
// }}}
- // {{{ function checkSyntax() : checks question elements (before storing into database)
- protected function checkSyntax()
+ // {{{ function toArray() : converts a question (or the whole survey) to array, with results if the survey is ended
+ public function toArray($i = 'all')
{
- return null;
+ if ($i != 'all' && $i != 'root') { // if a specific question is requested, then just returns this question converted to array
+ $i = intval($i);
+ if (array_key_exists($i, $this->questions)) {
+ return $this->questions[$i]->toArray();
+ } else {
+ return null;
+ }
+ } else { // else returns the root converted to array in any case
+ $a = array('title' => $this->title,
+ 'description' => $this->description,
+ 'end' => $this->end,
+ 'mode' => $this->mode,
+ 'promos' => $this->promos,
+ 'valid' => $this->valid,
+ 'type' => 'root');
+ if ($this->id != -1) {
+ $a['id'] = $this->id;
+ }
+ if ($this->isEnded()) { // if the survey is ended, then adds here the number of votes
+ $sql = 'SELECT COUNT(id)
+ FROM survey_votes
+ WHERE survey_id={?};';
+ $tot = XDB::query($sql, $this->id);
+ $a['votes'] = $tot->fetchOneCell();
+ }
+ if ($i == 'all' && count($this->questions) > 0) { // if the whole survey is requested, then returns all the questions converted to array
+ $qArr = array();
+ for ($k = 0; $k < count($this->questions); $k++) {
+ $q = $this->questions[$k]->toArray();
+ $q['id'] = $k;
+ if ($this->isEnded()) { // if the survey is ended, then adds here the results of this question
+ $q['result'] = $this->questions[$k]->getResultArray($this->id, $k);
+ }
+ $qArr[$k] = $q;
+ }
+ $a['questions'] = $qArr;
+ }
+ return $a;
+ }
}
// }}}
- // {{{ function vote() : handles vote
- protected function checkAnswer($ans)
- {
- return "";
- }
-
- function vote($sid, $vid, $a)
- {
- $ans = $this->checkAnswer($a[$this->getId]);
- if ($ans != "") {
- XDB::execute(
- 'INSERT INTO survey_answers
- SET survey_id = {?},
- vote_id = {?},
- question_id = {?},
- answer = "{?}"', $sid, $vid, $id, $ans);
+ // {{{ function toCSV() : builds a CSV file containing all the results of the survey
+ public function toCSV($sep = ',', $enc = '"', $asep='|')
+ {
+ $nbq = count($this->questions);
+ //require_once dirname(__FILE__) . '/../../classes/varstream.php';
+ VarStream::init();
+ global $csv_output;
+ $csv_output = '';
+ $csv = fopen('var://csv_output', 'w');
+ $line = ($this->isMode(self::MODE_XIDENT))? array('id', 'Nom', 'Prenom', 'Promo') : array('id');
+ $qids = array();
+ for ($qid = 0; $qid < $nbq; $qid++) {
+ $qids[$qid] = count($line); // stores the first id of a question (in case of questions with subquestions)
+ array_splice($line, count($line), 0, $this->questions[$qid]->getCSVColumns()); // the first line contains the questions
}
+ $nbf = count($line);
+ $users = array();
+ if ($this->isMode(self::MODE_XIDENT)) { // if the mode is non anonymous
+ $sql = 'SELECT v.id AS vid, a.nom, a.prenom, a.promo
+ FROM survey_votes AS v
+ INNER JOIN auth_user_md5 AS a
+ ON a.user_id=v.user_id
+ WHERE v.survey_id={?}
+ ORDER BY vid ASC;';
+ $res = XDB::iterator($sql, $this->id); // retrieves all users data
+ for ($u = $res->next(); $u != null; $u = $res->next()) {
+ $users[$u['vid']] = array('nom' => $u['nom'], 'prenom' => $u['prenom'], 'promo' => $u['promo']);
+ }
+ }
+ $sql = 'SELECT v.id AS vid, a.question_id AS qid, a.answer AS answer
+ FROM survey_votes AS v
+ LEFT JOIN survey_answers AS a
+ ON a.vote_id=v.id
+ WHERE v.survey_id={?}
+ ORDER BY vid ASC, qid ASC, answer ASC;';
+ $res = XDB::iterator($sql, $this->id); // retrieves all answers from database
+ $cur = $res->next();
+ $vid = -1;
+ $vid_ = 0;
+ while ($cur != null) {
+ if ($vid != $cur['vid']) { // if the vote id changes, then starts a new line
+ fputcsv($csv, $line, $sep, $enc); // stores the former line into $csv_output
+ $vid = $cur['vid'];
+ $line = array_fill(0, $nbf, ''); // creates an array full of empty string
+ $line[0] = $vid_; // the first field is a 'clean' vote id (not the one stored in database)
+ if ($this->isMode(self::MODE_XIDENT)) { // if the mode is non anonymous
+ if (array_key_exists($vid, $users) && is_array($users[$vid])) { // and if the user data can be found
+ $line[1] = $users[$vid]['nom']; // adds the user data (in the first fields of the line)
+ $line[2] = $users[$vid]['prenom'];
+ $line[3] = $users[$vid]['promo'];
+ }
+ }
+ $vid_++;
+ }
+ $ans = $this->questions[$cur['qid']]->formatAnswer($cur['answer']); // formats the current answer
+ if (!is_null($ans)) {
+ if (is_array($ans)) {
+ $fid = $qids[$cur['qid']] + $ans['id']; // computes the field id
+ $a = $ans['answer'];
+ } else {
+ $fid = $qids[$cur['qid']];
+ $a = $ans;
+ }
+ if ($line[$fid] != '') { // if this field already contains something
+ $line[$fid] .= $asep; // then adds a separator before adding the new answer
+ }
+ $line[$fid] .= $a; // adds the current answer to the correct field
+ }
+ $cur = $res->next(); // gets next answer
+ }
+ fputcsv($csv, $line, $sep, $enc); // stores the last line into $csv_output
+ return $csv_output;
}
// }}}
-}
-// }}}
-
-// {{{ abstract class SurveyTreeable extends SurveyQuestion : questions that allow nested ones
-abstract class SurveyTreeable extends SurveyQuestion
-{
- // {{{ common properties, constructor
- private $children;
- protected function __construct($i, $args)
+ // {{{ function factory($type, $args) : builds a question according to the given type
+ public function factory($t, $args)
{
- parent::__construct($i, $args);
- $this->children = array();
+ switch ($t) {
+ case 'text':
+ return new SurveyText($args);
+ case 'textarea':
+ return new SurveyTextarea($args);
+ case 'num':
+ return new SurveyNum($args);
+ case 'radio':
+ return new SurveyRadio($args);
+ case 'checkbox':
+ return new SurveyCheckbox($args);
+ case 'radiotable':
+ return new SurveyRadioTable($args);
+ case 'checkboxtable':
+ return new SurveyCheckboxTable($args);
+ default:
+ return null;
+ }
}
// }}}
- // {{{ tree manipulation functions : actual implementation
- protected function hasChild()
+ // {{{ questions manipulation functions
+ public function addQuestion($i, $c)
{
- return !is_null($this->children) && is_array($this->children);
- }
-
- protected function addChildNested($i, $c)
- {
- if ($this->getId() == $i) {
- if ($this->hasChild()) {
- array_unshift($this->children, $c);
- } else {
- $this->children = array($c);
- }
- return true;
- } else {
- foreach ($this->children as $child) {
- if ($child->addChildNested($i, $c)) {
- return true;
- }
- }
+ $i = intval($i);
+ if ($this->valid || $i > count($this->questions)) {
return false;
+ } else {
+ array_splice($this->questions, $i, 0, array($c));
+ return true;
}
}
- protected function addChildAfter($i, $c)
+ public function delQuestion($i)
{
- $found = false;
- for ($k = 0; $k < count($this->children); $k++) {
- if ($this->children[$k]->getId() == $i) {
- $found = true;
- break;
- } else {
- if ($this->children[$k]->addChildAfter($i, $c)) {
- return true;
- }
- }
- }
- if ($found) {
- array_splice($this->children, $k+1, 0, array($c));
+ $i = intval($i);
+ if ($this->valid || !array_key_exists($i, $this->questions)) {
+ return false;
+ } else {
+ array_splice($this->questions, $i, 1);
return true;
}
- return false;
}
- protected function delChild($i)
+ public function editQuestion($i, $a)
{
- $found = false;
- for ($k = 0; $k < count($this->children); $k++) {
- if ($this->children[$k]->getId() == $i) {
- $found = true;
- break;
+ if ($i == 'root') {
+ $this->update($a);
+ } else {
+ $i = intval($i);
+ if ($this->valid ||!array_key_exists($i, $this->questions)) {
+ return false;
} else {
- if ($this->children[$k]->delChild($i)) {
- return true;
- }
+ $this->questions[$i]->update($a);
}
}
- if ($found) {
- array_splice($this->children, $k, 1);
- return true;
- }
- return false;
+ return true;
}
// }}}
- // {{{ function edit() with tree support
- protected function edit($i, $a)
+ // {{{ function checkSyntax() : checks syntax of the questions (currently the root only) before storing the survey in database
+ private static $errorMessages = array(
+ "datepassed" => "la date de fin de sondage est déjà dépassée : vous devez préciser une date future",
+ "promoformat" => "les restrictions à certaines promotions sont mal formattées"
+ );
+
+ public function checkSyntax()
{
- if ($this->getId() == $i) {
- $this->update($a);
- return true;
- } else {
- foreach ($this->children as $child) {
- if ($child->edit($i, $a)) {
- return true;
- }
- }
- return false;
+ $rArr = array();
+ // checks that the end date given is not already passed
+ // (unless the survey has already been validated : an admin can have a validated survey expired)
+ if (!$this->valid && $this->isEnded()) {
+ $rArr[] = array('question' => 'root', 'error' => self::$errorMessages["datepassed"]);
}
+ if ($this->promos != '' && !preg_match('#^(\d{4}-?|(\d{4})?-\d{4})(,(\d{4}-?|(\d{4})?-\d{4}))*$#', $this->promos)) {
+ $rArr[] = array('question' => 'root', 'error' => self::$errorMessages["promoformat"]);
+ }
+ return (empty($rArr))? null : $rArr;
}
// }}}
- // {{{ functions toArray() and searchToArray() with tree support
- protected function toArray()
+ // {{{ functions that manipulate surveys in database
+ // {{{ static function retrieveList() : gets the list of available survey (current, old and not validated surveys)
+ public static function retrieveList($type, $tpl = true)
{
- if ($this->hasChild()) {
- $cArr = array();
- foreach ($this->children as $child) {
- $cArr[] = $child->toArray();
- }
- $a = $this->storeArray();
- $a['children'] = $cArr;
- return $a;
+ switch ($type) {
+ case 'c':
+ case 'current':
+ $where = 'end > NOW()';
+ break;
+ case 'o':
+ case 'old':
+ $where = 'end <= NOW()';
+ break;
+ default:
+ return null;
+ }
+ $sql = 'SELECT id, title, end, mode
+ FROM survey_surveys
+ WHERE '.$where.'
+ ORDER BY end DESC;';
+ if ($tpl) {
+ return XDB::iterator($sql);
} else {
- return $this->storeArray();
+ return XDB::iterRow($sql);
}
}
+ // }}}
- protected function searchToArray($i)
+ // {{{ static function retrieveSurvey() : gets a survey in database (and unserialize the survey object structure)
+ public static function retrieveSurvey($sid)
{
- if ($this->getId() == $i) {
- return $this->storeArray();
- } else {
- foreach ($this->children as $child) {
- $a = $child->searchToArray($i);
- if (!is_null($a) && is_array($a)) {
- return $a;
- }
- }
+ $sql = 'SELECT questions, title, description, end, mode, promos
+ FROM survey_surveys
+ WHERE id={?}';
+ $res = XDB::query($sql, $sid);
+ $data = $res->fetchOneAssoc();
+ if (is_null($data) || !is_array($data)) {
return null;
}
+ $survey = new Survey($data, $sid, true, unserialize($data['questions']));
+ return $survey;
}
// }}}
- // {{{ function checkSyntax()
- protected function checkSyntax()
+ // {{{ static function retrieveSurveyInfo() : gets information about a survey (title, description, end date, restrictions) but does not unserialize the survey object structure
+ public static function retrieveSurveyInfo($sid)
{
- $rArr = array();
- foreach ($this->children as $child) {
- $a = $child->checkSyntax();
- if ($a != null) {
- $rArr[] = $a;
- }
- }
- return (empty($rArr))? null : $rArr;
+ $sql = 'SELECT title, description, end, mode, promos
+ FROM survey_surveys
+ WHERE id={?}';
+ $res = XDB::query($sql, $sid);
+ return $res->fetchOneAssoc();
}
// }}}
- // {{{ function vote()
- function vote($sid, $vid, $a)
+ // {{{ static function retrieveSurveyReq() : gets a survey request to validate
+ public static function retrieveSurveyReq($id)
{
- parent::vote($sid, $vid, $a);
- if ($this->hasChild()) {
- foreach ($this->children as $c) {
- $c->vote($sid, $vid, $a);
- }
+ require_once 'validations.inc.php';
+ $surveyreq = Validate::get_request_by_id($id);
+ if ($surveyreq == null) {
+ return null;
}
+ $data = array('title' => $surveyreq->title,
+ 'description' => $surveyreq->description,
+ 'end' => $surveyreq->end,
+ 'mode' => $surveyreq->mode,
+ 'promos' => $surveyreq->promos);
+ $survey = new Survey($data, $id, false, $surveyreq->questions);
+ return $survey;
}
// }}}
-}
-// }}}
-
-// {{{ class SurveyRoot extends SurveyTreeable : root of any survey, actually the only entry point (no public methods outside this class)
-class SurveyRoot extends SurveyTreeable
-{
- // {{{ properties, constructor and basic methods
- private $last_id;
- private $beginning;
- private $end;
- private $promos;
- private $valid;
- public function __construct($args)
+ // {{{ function proposeSurvey() : stores a proposition of survey in database (before validation)
+ public function proposeSurvey()
{
- parent::__construct(0, $args);
- $this->last_id = 0;
+ require_once 'validations.inc.php';
+ $surveyreq = new SurveyReq($this->title, $this->description, $this->end, $this->mode, $this->promos, $this->questions, S::v('uid'));
+ return $surveyreq->submit();
}
+ // }}}
- public function update($args)
- {
- parent::update($args);
- //$this->beginning = $args['beginning_year'] . "-" . $args['beginning_month'] . "-" . $args['beginning_day'];
- //$this->end = $args['end_year'] . "-" . $args['end_year'] . "-" . $args['end_day'];
- if (preg_match('#^\d{2}/\d{2}/\d{4}$#', $args['end'])) {
- $this->end = preg_replace('#^(\d{2})/(\d{2})/(\d{4})$#', '\3-\2-\1', $args['end']);
+ // {{{ function updateSurvey() : updates a survey in database (before validation)
+ public function updateSurvey()
+ {
+ if ($this->valid) {
+ $sql = 'UPDATE survey_surveys
+ SET questions={?},
+ title={?},
+ description={?},
+ end={?},
+ mode={?},
+ promos={?}
+ WHERE id={?};';
+ return XDB::execute($sql, serialize($this->questions), $this->title, $this->description, $this->end, $this->mode, $this->promos, $this->id);
} else {
- $this->end = (preg_match('#^\d{4}-\d{2}-\d{2}$#', $args['end']))? $args['end'] : '#';
+ require_once 'validations.inc.php';
+ $surveyreq = Validate::get_request_by_id($this->id);
+ if ($surveyreq == null) {
+ return false;
+ }
+ return $surveyreq->updateReq($this->title, $this->description, $this->end, $this->mode, $this->promos, $this->questions);
}
- $this->promos = ($args['promos'] == '' || preg_match('#^(\d{4}-?|(\d{4})?-\d{4})(,(\d{4}-?|(\d{4})?-\d{4}))*$#', $args['promos']))? $args['promos'] : '#';
}
+ // }}}
- private function getNextId()
- {
- $this->last_id++;
- return $this->last_id;
+ // {{{ functions vote() and hasVoted() : handles vote to a survey
+ public function vote($uid, $args)
+ {
+ XDB::execute('INSERT INTO survey_votes
+ SET survey_id={?}, user_id={?};', $this->id, $uid); // notes the user as having voted
+ $vid = XDB::insertId();
+ for ($i = 0; $i < count($this->questions); $i++) {
+ $ans = $this->questions[$i]->checkAnswer($args[$i]);
+ if (!is_null($ans) && is_array($ans)) {
+ foreach ($ans as $a) {
+ XDB::execute('INSERT INTO survey_answers
+ SET vote_id = {?},
+ question_id = {?},
+ answer = {?}', $vid, $i, $a);
+ }
+ }
+ }
}
- public function setValid($v)
+ public function hasVoted($uid)
{
- $this->valid = (boolean) $v;
+ $res = XDB::query('SELECT id
+ FROM survey_votes
+ WHERE survey_id={?} AND user_id={?};', $this->id, $uid); // checks whether the user has already voted
+ return ($res->numRows() != 0);
}
+ // }}}
- public function isValid()
+ // {{{ static function deleteSurvey() : deletes a survey (and all its votes)
+ public static function deleteSurvey($sid)
{
- return $this->valid;
+ $sql = 'DELETE s.*, v.*, a.*
+ FROM survey_surveys AS s
+ LEFT JOIN survey_votes AS v
+ ON v.survey_id=s.id
+ LEFT JOIN survey_answers AS a
+ ON a.vote_id=v.id
+ WHERE s.id={?};';
+ return XDB::execute($sql, $sid);
}
+ // }}}
- protected function getQuestionType()
+ // {{{ static function purgeVotes() : clears all votes concerning a survey (I'm not sure whether it's really useful)
+ public static function purgeVotes($sid)
{
- return "root";
+ $sql = 'DELETE v.*, a.*
+ FROM survey_votes AS v
+ LEFT JOIN survey_answers AS a
+ ON a.vote_id=v.id
+ WHERE v.survey_id={?};';
+ return XDB::execute($sql, $sid);
}
// }}}
- // {{{ function factory($type, $args) : builds a question according to the given type
- public function factory($t, $args)
- {
- $i = $this->getNextId();
- switch ($t) {
- case 'text':
- return new SurveyText($i, $args);
- case 'textarea':
- return new SurveyTextarea($i, $args);
- case 'num':
- return new SurveyNum($i, $args);
- case 'radio':
- return new SurveyRadio($i, $args);
- case 'checkbox':
- return new SurveyCheckbox($i, $args);
- case 'personal':
- return new SurveyPersonal($i, $args);
- default:
- return null;
- }
- }
// }}}
+}
+// }}}
- // {{{ methods needing public access
- public function addChildNested($i, $c)
- {
- return !$this->isValid() && parent::addChildNested($i, $c);
- }
+// {{{ abstract class SurveyQuestion
+abstract class SurveyQuestion
+{
+ // {{{ common properties, constructor, and basic methods
+ private $question;
+ private $comment;
- public function addChildAfter($i, $c)
+ public function __construct($args)
{
- return !$this->isValid() && parent::addChildAfter($i, $c);
+ $this->update($args);
}
- public function delChild($i)
+ public function update($a)
{
- return !$this->isValid() && parent::delChild($i);
+ $this->question = $a['question'];
+ $this->comment = $a['comment'];
}
- public function edit($i, $a)
- {
- return (!$this->isValid() || $this->getId() == $i) && parent::edit($i, $a);
- }
+ abstract protected function getQuestionType();
+ // }}}
+ // {{{ function toArray() : converts to array
public function toArray()
{
- return parent::toArray();
+ return array('type' => $this->getQuestionType(), 'question' => $this->question, 'comment' => $this->comment);
}
+ // }}}
- public function searchToArray($i)
+ // {{{ function checkSyntax() : checks question elements (before storing into database), not currently needed (with new structure)
+ protected function checkSyntax()
{
- return parent::searchToArray($i);
+ return null;
}
// }}}
- // {{{ function storeArray()
- public function storeArray()
+ // {{{ function checkAnswer : returns a correct answer (or a null value if error)
+ public function checkAnswer($ans)
{
- $rArr = parent::storeArray();
- $rArr['beginning'] = $this->beginning;
- $rArr['end'] = $this->end;
- $rArr['promos'] = $this->promos;
- $rArr['valid'] = $this->valid;
- return $rArr;
+ return null;
}
// }}}
- // {{{ function checkSyntax()
- private static $errorMessages = array(
- "dateformat" => "la date de fin de sondage est mal formattée : elle doit respecter la syntaxe dd/mm/aaaa",
- "datepassed" => "la date de fin de sondage est déjà dépassée : vous devez préciser une date future",
- "promoformat" => "les restrictions à certaines promotions sont mal formattées"
- );
+ // {{{ functions regarding the results of a survey
+ abstract public function getResultArray($sid, $qid);
- public function checkSyntax()
+ public function formatAnswer($ans)
{
- $rArr = parent::checkSyntax();
- if (!preg_match('#^\d{4}-\d{2}-\d{2}$#', $this->end)) {
- $rArr[] = array('question' => $this->getId(), 'error' => self::$errorMessages["dateformat"]);
- } else {
- if (strtotime($this->end) - time() <= 0) {
- $rArr[] = array('question' => $this->getId(), 'error' => self::$errorMessages["datepassed"]);
- }
- }
- if ($this->promos != '' && !preg_match('#^(\d{4}-?|(\d{4})?-\d{4})(,(\d{4}-?|(\d{4})?-\d{4}))*$#', $this->promos)) {
- $rArr[] = array('question' => $this->getId(), 'error' => self::$errorMessages["promoformat"]);
- }
- return (empty($rArr))? null : $rArr;
+ return $ans;
+ }
+
+ public function getCSVColumns()
+ {
+ return $this->question;
}
// }}}
}
// }}}
-// {{{ abstract class SurveySimple extends SurveyQuestion : "opened" questions
+// {{{ abstract class SurveySimple and its derived classes : "open" questions
+// {{{ abstract class SurveySimple extends SurveyQuestion
abstract class SurveySimple extends SurveyQuestion
{
- protected function checkAnswer($ans)
+ public function checkAnswer($ans)
{
- return $ans;
+ return array($ans);
+ }
+
+ public function getResultArray($sid, $qid)
+ {
+ $sql = 'SELECT answer
+ FROM survey_answers
+ WHERE vote_id IN (SELECT id FROM survey_votes WHERE survey_id={?})
+ AND question_id={?}
+ ORDER BY RAND()
+ LIMIT 5;';
+ $res = XDB::query($sql, $sid, $qid);
+ return $res->fetchAllAssoc();
}
}
+// }}}
// {{{ class SurveyText extends SurveySimple : simple text field, allowing a few words
class SurveyText extends SurveySimple
{
- protected function getQuestionType()
+ public function getQuestionType()
{
return "text";
}
// {{{ class SurveyTextarea extends SurveySimple : textarea field, allowing longer comments
class SurveyTextarea extends SurveySimple
{
- protected function getQuestionType()
+ public function getQuestionType()
{
return "textarea";
}
// {{{ class SurveyNum extends SurveySimple : allows numerical answers
class SurveyNum extends SurveySimple
{
- protected function checkAnswer($ans)
+ public function checkAnswer($ans)
{
- return intval($ans);
+ return array(intval($ans));
}
protected function getQuestionType()
// }}}
// }}}
-// {{{ abstract class SurveyList extends SurveyTreeable : restricted questions that allows only a list of possible answers
-abstract class SurveyList extends SurveyTreeable
+// {{{ abstract class SurveyList and its derived classes : restricted questions that allows only a list of possible answers
+// {{{ abstract class SurveyList extends SurveyQuestion
+abstract class SurveyList extends SurveyQuestion
{
- private $choices;
+ protected $choices;
- protected function update($args)
+ public function update($args)
{
parent::update($args);
- $this->choices = explode('|', $args['options']);
+ $this->choices = array();
+ foreach ($args['choices'] as $val) {
+ if (trim($val) || trim($val) == '0') {
+ $this->choices[] = $val;
+ }
+ }
}
- protected function storeArray()
+ public function toArray()
{
- $rArr = parent::storeArray();
+ $rArr = parent::toArray();
$rArr['choices'] = $this->choices;
- $rArr['options'] = implode('|', $this->choices);
return $rArr;
}
+ public function getResultArray($sid, $qid)
+ {
+ $sql = 'SELECT answer, COUNT(id) AS count
+ FROM survey_answers
+ WHERE vote_id IN (SELECT id FROM survey_votes WHERE survey_id={?})
+ AND question_id={?}
+ GROUP BY answer ASC';
+ $res = XDB::query($sql, $sid, $qid);
+ return $res->fetchAllAssoc();
+ }
+
+ public function formatAnswer($ans)
+ {
+ if (array_key_exists($ans, $this->choices)) {
+ return $this->choices[$ans];
+ } else {
+ return null;
+ }
+ }
}
+// }}}
// {{{ class SurveyRadio extends SurveyList : radio question, allows one answer among the list offered
class SurveyRadio extends SurveyList
{
- protected function checkAnswer($ans)
+ public function checkAnswer($ans)
{
- return (in_array($ans, $this->choices)) ? $ans : "";
+ $a = intval($ans);
+ return (array_key_exists($a, $this->choices))? array($a) : null;
}
protected function getQuestionType()
// {{{ class SurveyCheckbox extends SurveyList : checkbox question, allows any number of answers among the list offered
class SurveyCheckbox extends SurveyList
{
- protected function checkAnswer($ans)
+ public function checkAnswer($ans)
{
- $rep = "";
- foreach ($this->choices as $key => $value) {
- if (array_key_exists($key,$v[$id]) && $v[$id][$key]) {
- $rep .= "|" . $key;
+ $rep = array();
+ foreach ($ans as $a) {
+ $a = intval($a);
+ if (array_key_exists($a, $this->choices)) {
+ $rep[] = $a;
}
}
- $rep = (strlen($rep) >= 4) ? substr($rep, 4) : "";
- return $rep;
+ return (count($rep) == 0)? null : $rep;
}
protected function getQuestionType()
// }}}
// }}}
-// {{{ class SurveyPersonal extends SurveyQuestion : allows easy and verified access to user's personal data (promotion, name...)
-class SurveyPersonal extends SurveyQuestion
+// {{{ abstract class SurveyTable and its derived classes : table question, each column represents a choice, each line represents a question
+// {{{ abstract class SurveyTable extends SurveyList
+abstract class SurveyTable extends SurveyList
{
- private $perm;
+ protected $subquestions;
- protected function update($args)
+ public function update($args)
{
- $args['question'] = "Informations personnelles";
parent::update($args);
- $this->perm['promo'] = isset($args['promo'])? 1 : 0;
- $this->perm['name'] = isset($args['name'])? 1 : 0;
+ $this->subquestions = array();
+ foreach ($args['subquestions'] as $val) {
+ if (trim($val) || trim($val) == '0') {
+ $this->subquestions[] = $val;
+ }
+ }
+ }
+
+ public function toArray()
+ {
+ $rArr = parent::toArray();
+ $rArr['subquestions'] = $this->subquestions;
+ return $rArr;
}
- protected function checkAnswer($ans)
+ public function getResultArray($sid, $qid)
{
- if (intval($ans) == 1) {
- // requete mysql qvb
- return "";
+ $sql = 'SELECT answer, COUNT(id) AS count
+ FROM survey_answers
+ WHERE vote_id IN (SELECT id FROM survey_votes WHERE survey_id={?})
+ AND question_id={?}
+ GROUP BY answer ASC';
+ $res = XDB::iterator($sql, $sid, $qid);
+ $result = array();
+ for ($i = 0; $i < count($this->subquestions); $i++) {
+ $result[$i] = array_fill(0, count($this->choices), 0);
+ }
+ while ($r = $res->next()) {
+ list($i, $j) = explode(':', $r['answer']);
+ $result[$i][$j] = $r['count'];
+ }
+ return $result;
+ }
+
+ public function formatAnswer($ans)
+ {
+ list($q, $c) = explode(':', $ans);
+ if (array_key_exists($q, $this->subquestions) && array_key_exists($c, $this->choices)) {
+ return array('id' => $q, 'answer' => $this->choices[$c]);
} else {
- return "";
+ return null;
}
}
+ public function getCSVColumns()
+ {
+ $q = parent::getCSVColumns();
+ if (empty($this->subquestions)) {
+ return $q;
+ }
+ $a = array();
+ for ($k = 0; $k < count($this->subquestions); $k++) {
+ $a[$k] = $q.' : '.$this->subquestions[$k];
+ }
+ return $a;
+ }
+}
+// }}}
+
+// {{{ class SurveyRadioTable extends SurveyTable : SurveyTable with radio type choices
+class SurveyRadioTable extends SurveyTable
+{
+ public function checkAnswer($ans)
+ {
+ $rep = array();
+ foreach ($ans as $k => $a) {
+ if (!array_key_exists($k, $this->subquestions)) {
+ continue;
+ }
+ $a = intval($a);
+ if (array_key_exists($a, $this->choices)) {
+ $rep[] = $k . ':' . $a;
+ }
+ }
+ return (count($rep) == 0)? null : $rep;
+ }
+
protected function getQuestionType()
{
- return "personal";
+ return "radiotable";
+ }
+
+}
+// }}}
+
+// {{{ class SurveyCheckboxTable extends SurveyTable : SurveyTable with checkbox type choices
+class SurveyCheckboxTable extends SurveyTable
+{
+ public function checkAnswer($ans)
+ {
+ $rep = array();
+ foreach ($ans as $k => $aa) {
+ if (!array_key_exists($k, $this->subquestions)) {
+ continue;
+ }
+ foreach ($aa as $a) {
+ $a = intval($a);
+ if (array_key_exists($a, $this->choices)) {
+ $rep[] = $k . ':' . $a;
+ }
+ }
+ }
+ return (count($rep) == 0)? null : $rep;
}
- protected function storeArray()
+ protected function getQuestionType()
{
- $a = parent::storeArray();
- $a['promo'] = $this->perm['promo'];
- $a['name'] = $this->perm['name'];
- return $a;
+ return "checkboxtable";
}
+
}
// }}}
+// }}}
-// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
+// vim:set et sw=4 sts=4 ts=4 foldmethod=marker enc=utf-8:
?>