function handlers()
{
return array(
- 'survey' => $this->make_hook('index', AUTH_COOKIE),
+ 'survey' => $this->make_hook('index', AUTH_PUBLIC),
+ 'survey/vote' => $this->make_hook('vote', AUTH_PUBLIC),
'survey/edit' => $this->make_hook('edit', AUTH_COOKIE),
'survey/ajax' => $this->make_hook('ajax', AUTH_COOKIE),
'survey/admin' => $this->make_hook('admin', AUTH_MDP, 'admin'),
{
require_once dirname(__FILE__).'/survey/survey.inc.php';
$page->changeTpl('survey/index.tpl');
- $page->assign('survey_current', SurveyDB::retrieveList('c'));
- $page->assign('survey_old', SurveyDB::retrieveList('o'));
+ $page->assign('survey_current', Survey::retrieveList('c'));
+ $page->assign('survey_old', Survey::retrieveList('o'));
+ $page->assign('survey_modes', Survey::getModes(false));
+ }
+ // }}}
+
+ // {{{ function handler_vote()
+ function handler_vote(&$page, $id = -1)
+ {
+ if (Post::has('survey_cancel')) { // if the user cancels, returns to index
+ return $this->handler_index(&$page);
+ }
+ $id = intval($id);
+ if ($id == -1) {
+ return $this->show_error($page, "Un identifiant de sondage doit être précisé.", '');
+ }
+ require_once dirname(__FILE__).'/survey/survey.inc.php';
+ $survey = Survey::retrieveSurvey($id); // retrieves the survey object structure
+ if ($survey == null || !$survey->isValid()) {
+ return $this->show_error($page, "Sondage ".$id." introuvable.", '');
+ } elseif ($survey->isEnded()) {
+ return $this->show_error($page, "Le sondage ".$survey->getTitle()." est terminé.");
+ }
+ if (!$survey->isMode(Survey::MODE_ALL)) { // if the survey is reserved to alumni
+ global $globals;
+ if (!call_user_func(array($globals->session, 'doAuth'))) { // checks authentification
+ global $platal;
+ $platal->force_login($page);
+ }
+ if ($survey->isMode(Survey::MODE_XIDENT) && !$survey->checkPromo(S::v('promo'))) { // checks promotion
+ return $this->show_error($page, "Tu n'as pas accès à ce sondage car il est réservé à d'autres promotions.");
+ }
+ }
+ if (Post::has('survey_submit')) { // checks if the survey has already been filled in
+ $uid = 0;
+ if (!$survey->isMode(Survey::MODE_ALL)) { // if survey is restriced to alumni
+ $uid = S::v('uid');
+ if ($survey->hasVoted($uid)) { // checks whether the user has already voted
+ return $this->show_error($page, "Tu as déjà voté à ce sondage.");
+ }
+ }
+ $survey->vote($uid, Post::v('survey'.$id)); // performs vote
+ $this->show_success($page, "Ta réponse a bien été prise en compte. Merci d'avoir participé à ce sondage.", '');
+ } else { // offers to fill in the survey
+ if ($survey->isMode(Survey::MODE_ALL) || !$survey->hasVoted(S::v('uid'))) {
+ $page->assign('survey_votemode', true);
+ } else {
+ $page->assign('survey_warning', "Tu as déjà voté à ce sondage.");
+ }
+ //$page->assign('survey_id', $id);
+ $this->show_survey($page, $survey);
+ }
}
// }}}
$this->clear_session();
if ($id == -1) {
$page->changeTpl('survey/admin.tpl');
- $page->assign('survey_waiting', SurveyDB::retrieveList('w'));
- $page->assign('survey_current', SurveyDB::retrieveList('c'));
- $page->assign('survey_old', SurveyDB::retrieveList('o'));
+ $page->assign('survey_waiting', Survey::retrieveList('w'));
+ $page->assign('survey_current', Survey::retrieveList('c'));
+ $page->assign('survey_old', Survey::retrieveList('o'));
+ $page->assign('survey_modes', Survey::getModes(false));
} else {
- $survey = SurveyDB::retrieveSurvey($id); // retrieves all survey object structure
+ $survey = Survey::retrieveSurvey($id); // retrieves all survey object structure
if ($survey == null) {
$this->show_error($page, "Sondage ".$id." introuvable.", 'admin');
}
- //$this->store_session($survey, $id);
$page->assign('survey_adminmode', true);
- $page->assign('survey_id', $id);
$this->show_survey($page, $survey);
}
}
return $this->show_error($page, "Un identifiant de sondage doit être précisé.", 'admin');
}
require_once dirname(__FILE__).'/survey/survey.inc.php';
- $survey = SurveyDB::retrieveSurvey($id); // retrieves the survey in database
+ $survey = Survey::retrieveSurvey($id); // retrieves the survey in database
$this->clear_session(); // cleans session (in case there would have been a problem before)
- /*if ($survey->isValid()) {
- return $this->show_error($page, "Il est impossible de modifier un sondage déjà validé", 'admin');
- }*/
$this->store_session($survey, $id);
$this->handler_edit($page, 'show'); // calls handler_edit, but in admin mode since 'survey_id' is in session
}
// {{{ function handler_adminValidate() : validates a survey (admin mode)
function handler_adminValidate(&$page, $id = -1)
{
- $id = Post::v('survey_id', $id);
+ $id = Post::i('survey_id', $id);
if (Post::has('survey_cancel')) { // if the admin cancels the validation, returns to the admin index
$this->clear_session();
return $this->handler_admin(&$page, $id);
return $this->show_error($page, "Un identifiant de sondage doit être précisé.", 'admin');
}
require_once dirname(__FILE__).'/survey/survey.inc.php';
- $surveyInfo = SurveyDB::retrieveSurveyInfo($id); // retrieves information about the survey (does not retrieve and unserialize the object structure)
+ $surveyInfo = Survey::retrieveSurveyInfo($id); // retrieves information about the survey (does not retrieve and unserialize the object structure)
if ($surveyInfo == null) {
return $this->show_error($page, "Sondage ".$id." introuvable.", 'admin');
}
if (Post::has('survey_submit')) { // needs a confirmation before validation
- if (SurveyDB::validateSurvey($id)) { // validates the survey (in the database)
+ if (Survey::validateSurvey($id)) { // validates the survey (in the database)
$this->show_success($page, "Le sondage \"".$surveyInfo['title']."\" a bien été validé, les votes sont maintenant ouverts.", 'admin');
} else {
$this->show_error($page, '', 'admin');
$this->show_confirm($page, "Êtes-vous certain de vouloir valider le sondage \"".$surveyInfo['title']."\" ? "
."Les votes seront immédiatement ouverts.", 'admin/valid', array('id' => $id));
}
- /*
- if ($id == -1 && !(S::has('survey') && S::has('survey_id'))) {
- return $this->show_error($page, "Un identifiant de sondage doit être précisé.", 'admin');
- }
- require_once dirname(__FILE__).'/survey/survey.inc.php';
- if ($id == -1) { // the survey and survey_id are in session, performs the validation
- $survey = unserialize(S::v('survey'));
- $surveyInfo = $survey->storeArray();
- if (Post::has('survey_submit')) { // needs a confirmation before validation
- if (SurveyDB::validateSurvey(S::v('survey_id'))) { // validates the survey (in the database)
- $this->show_success($page, "Le sondage \"".$surveyInfo['question']."\" a bien été validé, les votes sont maintenant ouverts.", 'admin');
- } else {
- $this->show_error($page, '', 'admin');
- }
- } else { // asks for a confirmation
- $this->show_confirm($page, "Êtes-vous certain de vouloir valider le sondage \"".$surveyInfo['question']."\" ? "
- ."Les votes seront immédiatement ouverts.", 'admin/valid');
- }
- } else { // a survey id is given, loads this survey for validation
- $this->clear_session();
- $survey = SurveyDB::retrieveSurvey($id); // retrieves all survey object structure
- if ($survey == null) {
- $this->show_error($page, "Sondage ".$id." introuvable.", 'admin');
- }
- $this->store_session($survey, $id);
- $page->assign('survey_validmode', true);
- $this->show_survey($page, $survey);
- }
- */
}
// }}}
// {{{ function handler_adminDelete() : deletes a survey (admin mode)
function handler_adminDelete(&$page, $id = -1)
{
- $id = Post::v('survey_id', $id);
+ $id = Post::i('survey_id', $id);
if (Post::has('survey_cancel')) { // if the admin cancels the suppression, returns to the admin index
return $this->handler_admin(&$page, $id);
}
return $this->show_error($page, "Un identifiant de sondage doit être précisé.", 'admin');
}
require_once dirname(__FILE__).'/survey/survey.inc.php';
- $surveyInfo = SurveyDB::retrieveSurveyInfo($id); // retrieves information about the survey (does not retrieve and unserialize the object structure)
+ $surveyInfo = Survey::retrieveSurveyInfo($id); // retrieves information about the survey (does not retrieve and unserialize the object structure)
if ($surveyInfo == null) {
return $this->show_error($page, "Sondage ".$id." introuvable.", 'admin');
}
if (Post::has('survey_submit')) { // needs a confirmation before suppression
- if (SurveyDB::deleteSurvey($id)) { // deletes survey in database
+ if (Survey::deleteSurvey($id)) { // deletes survey in database
$this->show_success($page, "Le sondage \"".$surveyInfo['title']."\" a bien été supprimé, ainsi que tous les votes le concernant.", 'admin');
} else {
$this->show_error($page, '', 'admin');
// }}}
// {{{ function handler_edit() : edits a survey (in normal mode unless called by handler_adminEdit() )
- function handler_edit(&$page, $action = 'show', $qid = 0)
+ function handler_edit(&$page, $action = 'show', $qid = 'root')
{
require_once dirname(__FILE__).'/survey/survey.inc.php';
$action = Post::v('survey_action', $action);
if (Post::has('survey_submit')) { // if the form has been submitted, makes the modifications
$survey = unserialize(S::v('survey'));
$args = Post::v('survey_question');
- if (!$survey->edit($qid, $args)) { // update the survey object structure
+ if (!$survey->editQuestion($qid, $args)) { // update the survey object structure
return $this->show_error($page, '', 'edit');
}
$this->show_survey($page, $survey);
$this->store_session($survey);
} else { // if a form has not been submitted, shows modification form
$survey = unserialize(S::v('survey'));
- $current = $survey->searchToArray($qid); // gets the current parameters of the question
+ $current = $survey->toArray($qid); // gets the current parameters of the question
if ($current == null) {
return $this->show_error($page, '', 'edit');
}
} elseif ($action == 'new') { // {{{ create a new survey : actually store the root question
if (Post::has('survey_submit')) { // if the form has been submitted, creates the survey
$this->clear_session();
- $survey = new SurveyRoot(Post::v('survey_question')); // creates the object structure
+ $survey = new Survey(Post::v('survey_question')); // creates the object structure
$this->show_survey($page, $survey);
$this->store_session($survey);
} else {
$this->clear_session();
- $this->show_form($page, $action, 0, 'root');
+ $this->show_form($page, $action, 'root', 'root');
} // }}}
- } elseif ($action == 'nested' || $action == 'after') { // {{{ adds a new question, nested in the current node, or on the same level after it
+ } elseif ($action == 'add') { // {{{ adds a new question
if (Post::has('survey_submit')) { // if the form has been submitted, adds the question
$survey = unserialize(S::v('survey'));
- $question = $survey->factory(Post::v('survey_type'), Post::v('survey_question')); // creates the question object, with a sort of 'factory' method
- if ($action == 'nested') {
- if (!$survey->addChildNested($qid, $question)) {
- return $this->show_error($page, '', 'edit');
- }
- } else {
- if (!$survey->addChildAfter($qid, $question)) {
- return $this->show_error($page, '', 'edit');
- }
+ if (!$survey->addQuestion($qid, $survey->factory(Post::v('survey_type'), Post::v('survey_question')))) {
+ return $this->show_error($page, '', 'edit');
}
$this->show_survey($page, $survey);
$this->store_session($survey);
} elseif ($action == 'del') { // {{{ deletes a question
if (Post::has('survey_submit')) { // if a confirmation has been sent, deletes the question
$survey = unserialize(S::v('survey'));
- if (!$survey->delChild(Post::v('survey_qid'))) { // deletes the node in the survey object structure
+ if (!$survey->delQuestion(Post::v('survey_qid'))) { // deletes the node in the survey object structure
return $this->show_error($page, '', 'edit');
}
$this->show_survey($page, $survey);
$this->store_session($survey);
} else { // if user has not confirmed, shows a confirmation form
$survey = unserialize(S::v('survey'));
- $current = $survey->searchToArray($qid); // needed to get the title of the question to delete (more user-friendly than an id)
+ $current = $survey->toArray($qid); // needed to get the title of the question to delete (more user-friendly than an id)
if ($current == null) {
return $this->show_error($page, '', 'edit');
}
if (Post::has('survey_submit')) { // needs a confirmation before storing the proposition
$survey = unserialize(S::v('survey'));
if (S::has('survey_id')) { // if 'survey_id' is in session, we are modifying an existing survey (in admin mode) instead of proposing a new one
- if (SurveyDB::updateSurvey($survey, S::v('survey_id'))) { // updates the database according the new survey object structure
+ if ($survey->updateSurvey()) { // updates the database according the new survey object structure
$this->show_success($page, "Les modifications sur le sondage ont bien été enregistrées.", 'admin');
} else {
$this->show_error($page, '', 'admin');
}
} else { // if no 'survey_id' is in session, we are indeed proposing a new survey
- if (SurveyDB::proposeSurvey($survey)) { // stores the survey object structure in database
+ if ($survey->proposeSurvey()) { // stores the survey object structure in database
$this->show_success($page, "Votre proposition de sondage a bien été enregistrée,
elle est en attent de validation par un administrateur du site.", '');
} else {
{
require_once dirname(__FILE__).'/survey/survey.inc.php';
header('Content-Type: text/html; charset="UTF-8"');
- if (SurveyQuestion::isType($type)) { // when type has been chosen, the form is updated to fit exactly the type of question chosen
+ if (Survey::isType($type)) { // when type has been chosen, the form is updated to fit exactly the type of question chosen
$page->changeTpl('survey/edit_new.tpl', NO_SKIN);
- $page->assign('survey_types', SurveyQuestion::getTypes());
+ $page->assign('survey_types', Survey::getTypes());
$page->assign('survey_type', $type);
}
}
{
$page->changeTpl('survey/show_root.tpl');
$page->assign('survey', $survey->toArray());
+ $page->assign('survey_modes', Survey::getModes());
}
// }}}
$page->assign('survey_current', $current);
} elseif ($type == 'new') {
$page->addJsLink('ajax.js');
- $page->assign('survey_types', SurveyQuestion::getTypes());
+ $page->assign('survey_types', Survey::getTypes());
+ }
+ if ($type == 'root') {
+ $page->assign('survey_modes', Survey::getModes());
}
}
// }}}
* 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 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");
- // {{{ 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;
+ public static function getModes($long = true) {
+ return ($long)? self::$longModes : self::$shortModes;
}
- // }}}
- // {{{ 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',
}
// }}}
- // {{{ 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()
- {
- return $this->id;
- }
-
- 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)
- {
- return false;
- }
- // }}}
-
- // {{{ function edit($i, $a) : searches and edits question $i
- protected function edit($i, $a)
+ public function update($args)
{
- if ($this->id == $i) {
- $this->update($a);
- return true;
+ $this->title = $args['title'];
+ $this->description = $args['description'];
+ 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']);
} else {
- return false;
+ $this->end = (preg_match('#^\d{4}-\d{2}-\d{2}$#', $args['end']))? $args['end'] : '#';
+ }
+ $this->mode = $args['mode'];
+ if ($args['mode'] == 0) {
+ $args['promos'] = '';
}
+ $this->promos = ($args['promos'] == '' || preg_match('#^(\d{4}-?|(\d{4})?-\d{4})(,(\d{4}-?|(\d{4})?-\d{4}))*$#', $args['promos']))? $args['promos'] : '#';
}
// }}}
- // {{{ functions toArray() and searchToArray($i) : (searches and) converts to array
- protected function toArray()
+ // {{{ functions to access general information
+ public function isMode($mode)
{
- return $this->storeArray();
+ return ($this->mode == $mode);
}
- protected function searchToArray($i)
+ public function checkPromo($promo)
{
- if ($this->id == $i) {
- return $this->storeArray();
- } else {
- return null;
+ $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;
}
- protected function storeArray()
- {
- return array('type' => $this->getQuestionType(), 'id' => $this->id, 'question' => $this->question, 'comment' => $this->comment);
- }
- // }}}
-
- // {{{ function checkSyntax() : checks question elements (before storing into database)
- protected function checkSyntax()
- {
- return null;
- }
- // }}}
-
- // {{{ function vote() : handles vote
- protected function checkAnswer($ans)
+ public function isValid()
{
- return "";
+ return $this->valid;
}
- function vote($sid, $vid, $a)
+ public function isEnded()
{
- $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);
- }
+ return (strtotime($this->end) - time() <= 0);
}
- // }}}
-}
-// }}}
-
-// {{{ 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)
+ public function getTitle()
{
- parent::__construct($i, $args);
- $this->children = array();
+ return $this->title;
}
// }}}
- // {{{ tree manipulation functions : actual implementation
- protected function hasChild()
- {
- return !is_null($this->children) && is_array($this->children);
- }
-
- protected function addChildNested($i, $c)
+ // {{{ function toArray() : converts a question (or the whole survey) to array
+ public function toArray($i = 'all')
{
- if ($this->getId() == $i) {
- if ($this->hasChild()) {
- array_unshift($this->children, $c);
+ if ($i != 'all' && $i != 'root') {
+ $i = intval($i);
+ if (array_key_exists($i, $this->questions)) {
+ return $this->questions[$i]->toArray();
} else {
- $this->children = array($c);
+ return null;
}
- return true;
} else {
- foreach ($this->children as $child) {
- if ($child->addChildNested($i, $c)) {
- return true;
+ $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 ($i == 'all' && count($this->questions) > 0) {
+ $qArr = array();
+ for ($k = 0; $k < count($this->questions); $k++) {
+ $q = $this->questions[$k]->toArray();
+ $q['id'] = $k;
+ $qArr[$k] = $q;
}
+ $a['questions'] = $qArr;
}
- return false;
+ return $a;
}
}
+ // }}}
- protected function addChildAfter($i, $c)
+ // {{{ function factory($type, $args) : builds a question according to the given type
+ public function factory($t, $args)
{
- $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;
- }
- }
+ 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 'personal':
+ return new SurveyPersonal($args);
+ default:
+ return null;
}
- if ($found) {
- array_splice($this->children, $k+1, 0, array($c));
+ }
+ // }}}
+
+ // {{{ questions manipulation functions
+ public function addQuestion($i, $c)
+ {
+ if ($this->valid || $i > count($this->questions)) {
+ return false;
+ } else {
+ array_splice($this->questions, $i, 0, array($c));
return true;
}
- return false;
}
- protected function delChild($i)
+ 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]->delChild($i)) {
- return true;
- }
- }
- }
- if ($found) {
- array_splice($this->children, $k, 1);
+ if ($this->valid || !array_key_exists($i, $this->questions)) {
+ return false;
+ } else {
+ array_splice($this->questions, $i, 1);
return true;
}
- return false;
}
- // }}}
- // {{{ function edit() with tree support
- protected function edit($i, $a)
+ public function editQuestion($i, $a)
{
- if ($this->getId() == $i) {
+ if ($i == 'root') {
$this->update($a);
- return true;
} else {
- foreach ($this->children as $child) {
- if ($child->edit($i, $a)) {
- return true;
- }
+ $i = intval($i);
+ if ($this->valid ||!array_key_exists($i, $this->questions)) {
+ return false;
+ } else {
+ $this->questions[$i]->update($a);
}
- return false;
}
+ return true;
}
// }}}
- // {{{ functions toArray() and searchToArray() with tree support
- protected function toArray()
+ // {{{ function checkSyntax() : checks syntax of the questions (currently the root only) before storing the survey in database
+ 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"
+ );
+
+ public function checkSyntax()
{
- if ($this->hasChild()) {
- $cArr = array();
- foreach ($this->children as $child) {
- $cArr[] = $child->toArray();
- }
- $a = $this->storeArray();
- $a['children'] = $cArr;
- return $a;
+ $rArr = array();
+ if (!preg_match('#^\d{4}-\d{2}-\d{2}$#', $this->end)) {
+ $rArr[] = array('question' => 'root', 'error' => self::$errorMessages["dateformat"]);
} else {
- return $this->storeArray();
+ // 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;
}
+ // }}}
- protected function searchToArray($i)
+ // {{{ functions that manipulates 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->getId() == $i) {
- return $this->storeArray();
- } else {
- foreach ($this->children as $child) {
- $a = $child->searchToArray($i);
- if (!is_null($a) && is_array($a)) {
- return $a;
- }
- }
+ 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 id, title, end, mode
+ FROM survey_surveys
+ WHERE '.$where.';';
+ if ($tpl) {
+ return XDB::iterator($sql);
+ } else {
+ return XDB::iterRow($sql);
+ }
}
// }}}
- // {{{ function checkSyntax()
- protected function checkSyntax()
+ // {{{ static function retrieveSurvey() : gets a survey in database (and unserialize the survey object structure)
+ public static function retrieveSurvey($sid)
{
- $rArr = array();
- foreach ($this->children as $child) {
- $a = $child->checkSyntax();
- if ($a != null) {
- $rArr[] = $a;
- }
+ $sql = 'SELECT questions, title, description, end, mode, promos, valid
+ FROM survey_surveys
+ WHERE id={?}';
+ $res = XDB::query($sql, $sid);
+ $data = $res->fetchOneAssoc();
+ if (is_null($data) || !is_array($data)) {
+ return null;
}
- return (empty($rArr))? null : $rArr;
+ $survey = new Survey($data, $sid, (boolean) $data['valid'], unserialize($data['questions']));
+ return $survey;
}
// }}}
- // {{{ function vote()
- function vote($sid, $vid, $a)
+ // {{{ 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)
{
- parent::vote($sid, $vid, $a);
- if ($this->hasChild()) {
- foreach ($this->children as $c) {
- $c->vote($sid, $vid, $a);
- }
- }
+ $sql = 'SELECT title, description, end, mode, promos, valid
+ FROM survey_surveys
+ WHERE id={?}';
+ $res = XDB::query($sql, $sid);
+ return $res->fetchOneAssoc();
}
// }}}
-}
-// }}}
-
-// {{{ 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;
+ $sql = 'INSERT INTO survey_surveys
+ SET questions={?},
+ title={?},
+ description={?},
+ author_id={?},
+ end={?},
+ mode={?},
+ promos={?},
+ valid=0;';
+ return XDB::execute($sql, serialize($this->questions), $this->title, $this->description, S::v('uid'), $this->end, $this->mode, $this->promos);
}
+ // }}}
- public function update($args)
+ // {{{ function updateSurvey() : updates a survey in database (before validation)
+ public function updateSurvey()
{
- 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']);
- } else {
- $this->end = (preg_match('#^\d{4}-\d{2}-\d{2}$#', $args['end']))? $args['end'] : '#';
+ if ($this->id == -1) {
+ return false;
}
- $this->promos = ($args['promos'] == '' || preg_match('#^(\d{4}-?|(\d{4})?-\d{4})(,(\d{4}-?|(\d{4})?-\d{4}))*$#', $args['promos']))? $args['promos'] : '#';
+ $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);
}
+ // }}}
- private function getNextId()
+ // {{{ static function validateSurvey() : validates a survey
+ public static function validateSurvey($sid)
{
- $this->last_id++;
- return $this->last_id;
+ $sql = 'UPDATE survey_surveys
+ SET valid=1
+ WHERE id={?};';
+ return XDB::execute($sql, $sid);
}
+ // }}}
- public function setValid($v)
- {
- $this->valid = (boolean) $v;
+ // {{{ 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 ($ans != "") {
+ XDB::execute('INSERT INTO survey_answers
+ SET vote_id = {?},
+ question_id = {?},
+ answer = {?}', $vid, $i, $ans);
+ }
+ }
}
- public function isValid()
+ public function hasVoted($uid)
{
- return $this->valid;
+ $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);
}
+ // }}}
- protected function getQuestionType()
+ // {{{ static function deleteSurvey() : deletes a survey (and all its votes)
+ public static function deleteSurvey($sid)
{
- return "root";
+ $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);
}
// }}}
- // {{{ function factory($type, $args) : builds a question according to the given type
- public function factory($t, $args)
+ // {{{ static function purgeVotes() : clears all votes concerning a survey (I'm not sure whether it's really useful)
+ public static function purgeVotes($sid)
{
- $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;
- }
+ $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);
}
// }}}
- // {{{ methods needing public access
- public function addChildNested($i, $c)
- {
- return !$this->isValid() && parent::addChildNested($i, $c);
- }
+ // }}}
+}
+// }}}
- public function addChildAfter($i, $c)
- {
- return !$this->isValid() && parent::addChildAfter($i, $c);
- }
+// {{{ abstract class SurveyQuestion
+abstract class SurveyQuestion
+{
+ // {{{ common properties, constructor, and basic methods
+ private $question;
+ private $comment;
- public function delChild($i)
+ public function __construct($args)
{
- return !$this->isValid() && parent::delChild($i);
+ $this->update($args);
}
- public function edit($i, $a)
+ public function update($a)
{
- return (!$this->isValid() || $this->getId() == $i) && parent::edit($i, $a);
+ $this->question = $a['question'];
+ $this->comment = $a['comment'];
}
+ 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 correctly formatted answer (or nothing empty string 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 "";
}
// }}}
- // {{{ 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"
- );
-
- public function checkSyntax()
- {
- $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;
- }
+ // {{{ function resultArray() : statistics on the results of the survey
+ //abstract protected function resultArray($sid, $where);
// }}}
}
// }}}
// {{{ abstract class SurveySimple extends SurveyQuestion : "opened" questions
abstract class SurveySimple extends SurveyQuestion
{
- protected function checkAnswer($ans)
+ public function checkAnswer($ans)
{
return $ans;
}
// {{{ 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);
}
// }}}
// {{{ abstract class SurveyList extends SurveyTreeable : restricted questions that allows only a list of possible answers
-abstract class SurveyList extends SurveyTreeable
+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']);
}
- protected function storeArray()
+ public function toArray()
{
- $rArr = parent::storeArray();
+ $rArr = parent::toArray();
$rArr['choices'] = $this->choices;
$rArr['options'] = implode('|', $this->choices);
return $rArr;
// {{{ 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 : "";
+ return (array_key_exists($ans, $this->choices)) ? $ans : "";
}
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 = "|";
+ foreach ($ans as $a) {
+ if (array_key_exists($a,$this->choices)) {
+ $rep .= $a . "|";
}
}
- $rep = (strlen($rep) >= 4) ? substr($rep, 4) : "";
return $rep;
}
// }}}
// {{{ class SurveyPersonal extends SurveyQuestion : allows easy and verified access to user's personal data (promotion, name...)
+// actually this type of question should be suppressed (non anonymous surveys are possible with survey modes)
+// and anyway it is not finished (checkAnswer implementation) : currently it does not store anything when a user votes
class SurveyPersonal extends SurveyQuestion
{
private $perm;
- protected function update($args)
+ public function update($args)
{
$args['question'] = "Informations personnelles";
parent::update($args);
$this->perm['name'] = isset($args['name'])? 1 : 0;
}
- protected function checkAnswer($ans)
+ public function checkAnswer($ans)
{
if (intval($ans) == 1) {
// requete mysql qvb
return "personal";
}
- protected function storeArray()
+ public function toArray()
{
- $a = parent::storeArray();
+ $a = parent::toArray();
$a['promo'] = $this->perm['promo'];
$a['name'] = $this->perm['name'];
return $a;