From 2f4b93beb55b35a978d3a9520bdf67ac3abf43fb Mon Sep 17 00:00:00 2001 From: Florent Bruneau Date: Sat, 30 Oct 2010 23:03:45 +0200 Subject: [PATCH] Stub of the new surveys. Signed-off-by: Florent Bruneau --- modules/survey.php | 485 ++-------------- modules/survey/section.inc.php | 33 ++ modules/survey/survey.inc.php | 838 +++++---------------------- modules/survey/text.inc.php | 32 + templates/survey/admin.tpl | 75 --- templates/survey/confirm.tpl | 40 -- templates/survey/edit_checkbox.tpl | 25 - templates/survey/edit_checkboxtable.tpl | 25 - templates/survey/edit_new.tpl | 38 -- templates/survey/edit_newsurvey.tpl | 31 - templates/survey/edit_num.tpl | 25 - templates/survey/edit_question.tpl | 61 -- templates/survey/edit_radio.tpl | 39 -- templates/survey/edit_radiotable.tpl | 39 -- templates/survey/edit_root.tpl | 85 --- templates/survey/edit_survey.tpl | 43 -- templates/survey/edit_textarea.tpl | 25 - templates/survey/error.tpl | 44 -- templates/survey/index.tpl | 62 +- templates/survey/show_checkbox.tpl | 39 -- templates/survey/show_checkboxtable.tpl | 52 -- templates/survey/show_num.tpl | 25 - templates/survey/show_question.tpl | 30 - templates/survey/show_radio.tpl | 39 -- templates/survey/show_radiotable.tpl | 52 -- templates/survey/show_root.tpl | 117 ---- templates/survey/show_text.tpl | 47 -- templates/survey/show_textarea.tpl | 47 -- templates/survey/success.tpl | 32 - templates/survey/{edit_text.tpl => vote.tpl} | 4 +- upgrade/1.1.0/10_surveys.sql | 86 +++ upgrade/1.1.0/old_surveys.inc.php | 823 ++++++++++++++++++++++++++ upgrade/1.1.0/update.sh | 10 + 33 files changed, 1166 insertions(+), 2282 deletions(-) create mode 100644 modules/survey/section.inc.php create mode 100644 modules/survey/text.inc.php delete mode 100644 templates/survey/admin.tpl delete mode 100644 templates/survey/confirm.tpl delete mode 100644 templates/survey/edit_checkbox.tpl delete mode 100644 templates/survey/edit_checkboxtable.tpl delete mode 100644 templates/survey/edit_new.tpl delete mode 100644 templates/survey/edit_newsurvey.tpl delete mode 100644 templates/survey/edit_num.tpl delete mode 100644 templates/survey/edit_question.tpl delete mode 100644 templates/survey/edit_radio.tpl delete mode 100644 templates/survey/edit_radiotable.tpl delete mode 100644 templates/survey/edit_root.tpl delete mode 100644 templates/survey/edit_survey.tpl delete mode 100644 templates/survey/edit_textarea.tpl delete mode 100644 templates/survey/error.tpl delete mode 100644 templates/survey/show_checkbox.tpl delete mode 100644 templates/survey/show_checkboxtable.tpl delete mode 100644 templates/survey/show_num.tpl delete mode 100644 templates/survey/show_question.tpl delete mode 100644 templates/survey/show_radio.tpl delete mode 100644 templates/survey/show_radiotable.tpl delete mode 100644 templates/survey/show_root.tpl delete mode 100644 templates/survey/show_text.tpl delete mode 100644 templates/survey/show_textarea.tpl delete mode 100644 templates/survey/success.tpl rename templates/survey/{edit_text.tpl => vote.tpl} (96%) create mode 100644 upgrade/1.1.0/10_surveys.sql create mode 100644 upgrade/1.1.0/old_surveys.inc.php create mode 100755 upgrade/1.1.0/update.sh diff --git a/modules/survey.php b/modules/survey.php index fa2b5bc..1c451bc 100644 --- a/modules/survey.php +++ b/modules/survey.php @@ -21,483 +21,72 @@ class SurveyModule extends PLModule { - // {{{ function handlers() : registers the different handlers function handlers() { return array( - 'survey' => $this->make_hook('index', AUTH_PUBLIC), - 'survey/vote' => $this->make_hook('vote', AUTH_PUBLIC), - 'survey/result' => $this->make_hook('result', AUTH_PUBLIC), + 'survey' => $this->make_hook('index', AUTH_COOKIE), + 'survey/vote' => $this->make_hook('vote', AUTH_COOKIE), + /* 'survey/result' => $this->make_hook('result', AUTH_COOKIE), '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'), 'survey/admin/edit' => $this->make_hook('adminEdit', AUTH_MDP, 'admin'), 'survey/admin/valid' => $this->make_hook('adminValidate', AUTH_MDP, 'admin'), 'survey/admin/del' => $this->make_hook('adminDelete', AUTH_MDP, 'admin'), - ); + */ ); } - // }}} - // {{{ function handler_index() : lists all available surveys function handler_index(&$page, $action = null) { $this->load('survey.inc.php'); - $page->changeTpl('survey/index.tpl'); - $page->assign('survey_current', Survey::retrieveList('c')); - $page->assign('survey_old', Survey::retrieveList('o')); - $page->assign('survey_modes', Survey::getModes(false)); - } - // }}} - // {{{ function handler_vote() : handles the vote to a survey - 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é.", 'survey'); - } - $this->load('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.", 'survey'); - } elseif ($survey->isEnded()) { - return $this->show_error($page, "Le sondage ".$survey->getTitle()." est terminé.", 'survey'); - } - if (!$this->check_surveyPerms($page, $survey)) { - return PL_DO_AUTH; - } - if (Post::has('survey_submit')) { // checks if the survey has already been filled in - // admins can see the survey but not vote - if (!$this->check_surveyPerms($page, $survey, false, false)) { - return PL_DO_AUTH; - } - $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'); - } - } - $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.", 'survey'); - } 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); - } - } - // }}} + XDB::execute("DELETE FROM surveys"); - // {{{ function handler_result() : show the results of the votes to a survey - function handler_result($page, $id = -1, $show = 'all') - { - $id = intval($id); - if ($id == -1) { - return $this->show_error($page, "Un identifiant de sondage doit être précisé.", 'survey'); - } - $this->load('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.", 'survey'); - } elseif (!$survey->isEnded() && !$survey->canSeeEarlyResults(S::user())) { - return $this->show_error($page, "Le sondage ".$survey->getTitle()." n'est pas encore terminé.", 'survey'); - } - if (!$survey->canSeeEarlyResults(S::user()) && !$this->check_surveyPerms($page, $survey)) { - return PL_DO_AUTH; - } - if ($show == 'csv') { - pl_content_headers("text/csv"); - header('Content-Disposition: attachment; filename="'.addslashes($survey->getTitle()).'.csv"'); - echo $survey->toCSV(); - exit; - } else { - $page->assign('survey_resultmode', true); - $this->show_survey($page, $survey); - } - } - // }}} + $survey = new Survey(); + $survey->id = null; + $survey->shortname = "blah"; + $survey->title = "Blah"; + $survey->description = "Blih blih blih blih"; + $survey->uid = S::user()->id(); + $survey->begin = "09/09/2010"; + $survey->end = "30/12/2011"; - // {{{ function handler_admin() : index of admin mode - function handler_admin(&$page, $id = -1) - { - $this->load('survey.inc.php'); - $this->clear_session(); - if ($id == -1) { - $page->changeTpl('survey/admin.tpl'); - $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 { - $id = intval($id); - $survey = Survey::retrieveSurvey($id); // retrieves all survey object structure - if ($survey == null) { - $this->show_error($page, "Sondage ".$id." introuvable.", 'survey/admin'); - } - $page->assign('survey_adminmode', true); - $this->show_survey($page, $survey); - } - } - // }}} + $qpage = $survey->newQuestion("section"); + $qpage->parameters = array('type' => 'page'); + $qpage->label = 'Première page'; - // {{{ function handler_adminEdit() : edits a survey in admin mode - function handler_adminEdit(&$page, $id = -1, $req = -1) - { - if ($id == -1 || ($id == 'req' && $req == -1)) { - return $this->show_error($page, "Un identifiant de sondage doit être précisé.", 'survey/admin'); - } - $this->load('survey.inc.php'); - $this->clear_session(); // cleans session (in case there would have been a problem before) - if ($id == 'req') { - $survey = Survey::retrieveSurveyReq($req); - if ($survey == null) { - return $this->show_error($page, "Sondage introuvable.", 'survey/admin'); - } - $this->store_session($survey, $req, true); - } else { - $id = intval($id); - $survey = Survey::retrieveSurvey($id); // retrieves the survey in database - if ($survey == null) { - return $this->show_error($page, "Sondage ".$id." introuvable.", 'survey/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::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); - } - if ($id == -1) { - return $this->show_error($page, "Un identifiant de sondage doit être précisé.", 'survey/admin'); - } - $id = intval($id); - $this->load('survey.inc.php'); - $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.", 'survey/admin'); - } - if (Post::has('survey_submit')) { // needs a confirmation before validation - 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.", 'survey/admin'); - } else { - $this->show_error($page, '', 'survey/admin'); - } - } else { // asks for a confirmation - $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)); - } - } - // }}} - - // {{{ function handler_adminDelete() : deletes a survey (admin mode) - function handler_adminDelete(&$page, $id = -1) - { - $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); - } - if ($id == -1) { - return $this->show_error($page, "Un identifiant de sondage doit être précisé.", 'survey/admin'); - } - $id = intval($id); - $this->load('survey.inc.php'); - $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.", 'survey/admin'); - } - if (Post::has('survey_submit')) { // needs a confirmation before suppression - 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.", 'survey/admin'); - } else { - $this->show_error($page, '', 'survey/admin'); - } - } else { // asks for a confirmation - $this->show_confirm($page, "Êtes-vous certain de vouloir supprimer le sondage \"".$surveyInfo['title']."\" ?", 'admin/del', array('id' => $id)); - } - } - // }}} + $question = $qpage->newQuestion("text"); + $question->label = "Super question"; + $question->flags = "mandatory"; + $question->parameters = array("type" => "text", "limit" => 256); - // {{{ function handler_edit() : edits a survey (in normal mode unless called by handler_adminEdit() ) - function handler_edit(&$page, $action = 'show', $qid = 'root') - { - $this->load('survey.inc.php'); - $action = Post::v('survey_action', $action); - $qid = Post::v('survey_qid', $qid); - if (Post::has('survey_cancel')) { // after cancelling changes, shows the survey - if (S::has('survey')) { - $action = 'show'; - } else { // unless no editing has been done at all (shows to the surveys index page) - return $this->handler_index($page); - } - } - $page->assign('survey_editmode', true); - if (S::has('survey_id')) { // if 'survey_id' is in session, it means we are modifying a survey in admin mode - $page->assign('survey_updatemode', true); - } - if ($action == 'show' && !S::has('survey')) { - $action = 'new'; - } - if ($action == 'question') { // {{{ modifies an existing question - 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->editQuestion($qid, $args)) { // update the survey object structure - return $this->show_error($page, '', 'survey/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->toArray($qid); // gets the current parameters of the question - if ($current == null) { - return $this->show_error($page, '', 'survey/edit'); - } - $this->show_form($page, $action, $qid, $current['type'], $current); - } // }}} - } 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 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, 'root', 'newsurvey'); - } // }}} - } 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')); - if (!$survey->addQuestion($qid, $survey->factory(Post::v('survey_type'), Post::v('survey_question')))) { - return $this->show_error($page, '', 'survey/edit'); - } - $this->show_survey($page, $survey); - $this->store_session($survey); - } else { - $this->show_form($page, $action, $qid); - } // }}} - } 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->delQuestion(Post::v('survey_qid'))) { // deletes the node in the survey object structure - return $this->show_error($page, '', 'survey/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->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, '', 'survey/edit'); - } - $this->show_confirm($page, 'Êtes-vous certain de vouloir supprimer la question intitulé "'.$current['question'].'" ? ' - .'Attention, cela supprimera en même temps toutes les questions qui dépendent de celle-ci.', - 'edit', array('action' => 'del', 'qid' => $qid)); - } // }}} - } elseif ($action == 'show') { // {{{ simply shows the survey in its current state - $this->show_survey($page, unserialize(S::v('survey'))); // }}} - } elseif ($action == 'valid') { // {{{ validates the proposition, i.e stores the proposition in the database - // but an admin will still need to validate the survey before it is activated - 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 - $link = (S::has('survey_validate'))? 'admin/validate' : 'survey/admin'; - 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.", $link); - } else { - $this->show_error($page, '', $link); - } - } else { // if no 'survey_id' is in session, we are indeed proposing a new survey - 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 attente de validation par un administrateur du site.", 'survey'); - } else { - $this->show_error($page, '', 'survey'); - } - } - $this->clear_session(); - } else { // asks for a confirmation if it has not been sent - $survey = unserialize(S::v('survey')); - $errors = $survey->checkSyntax(); - if (!is_null($errors)) { - $this->show_error($page, "", 'survey/edit', $errors); - } else { - if (S::has('survey_id')) { - $this->show_confirm($page, "Veuillez confirmer l'enregistrement des modifications apportées à ce sondage.", 'edit', array('action' => 'valid')); - } else { - $this->show_confirm($page, "Veuillez confirmer l'envoi de cette proposition de sondage.", 'edit', array('action' => 'valid')); - } - } - } // }}} - } elseif ($action == 'cancel') { // {{{ cancels the creation/modification of a survey - if (Post::has('survey_submit')) { // needs a confirmation - if (S::has('survey_id')) { // only possible when modifying a survey in admin mode - if (S::has('survey_validate')) { // if a link has been supplied, uses it - $this->clear_session(); - return $this->show_success($page, "Les modifications effectuées ont été annulées", 'admin/validate'); - } else { // else shows the admin index - $this->clear_session(); - return $this->handler_admin($page); - } - } else { - $this->clear_session(); - return $this->handler_index($page); // else shows the 'normal' index - } - } else { // asks for a confirmation if it has not been sent - $this->show_confirm(&$page, "Êtes-vous certain de vouloir annuler totalement l'édition de ce sondage ? Attention, " - ."toutes les données éditées jusque là seront définitivement perdues.", - 'edit', array('action' => $action)); - } - } // }}} - } - // }}} + $question = $qpage->newQuestion("text"); + $question->label = "Super question 2"; - // {{{ function handler_ajax() : some ajax in editing a new question (for now, there may be a little more later) - function handler_ajax(&$page, $type) - { - $this->load('survey.inc.php'); - pl_content_headers("text/html"); - 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', Survey::getTypes()); - $page->assign('survey_type', $type); - } - } - // }}} + $qpage = $survey->newQuestion("section"); + $qpage->parameters = array('type' => 'page'); + $qpage->label = 'Deuxième page'; - // {{{ function clear_session() : clears the data stored in session - function clear_session() - { - S::kill('survey'); - S::kill('survey_id'); - S::kill('survey_validate'); - } - // }}} + $survey->flags = 'validated'; + $survey->insert(true); - // {{{ function store_session() : serializes and stores survey (and survey_id) in session - function store_session($survey, $survey_id = -1, $survey_validate = false) - { - $_SESSION['survey'] = serialize($survey); - if ($survey_id != -1) { - $_SESSION['survey_id'] = $survey_id; - } - if ($survey_validate) { - $_SESSION['survey_validate'] = true; - } + $page->changeTpl('survey/index.tpl'); + $page->assign('active', Survey::iterActive()); } - // }}} - // {{{ function check_surveyPerms() : checks the particular surveys access permissions - function check_surveyPerms(&$page, $survey, $silent = false, $admin_allowed = true) + function handler_vote(PlPage $page, $name) { $this->load('survey.inc.php'); - if ($survey->isMode(Survey::MODE_ALL)) { // if the survey is not reserved to alumni - return true; - } - if (!S::logged()) { - return false; - } - $profile = S::user()->profile(); - if (!$profile) { - return false; - } - // checks promotion - $allowed = false; - foreach ($profile->yearspromo() as $p) { - if ($survey->checkPromo($p)) { - $allowed = true; - break; - } - } - if ($allowed) { - return true; + $page->changeTpl('survey/vote.tpl'); + $survey = Survey::get($name); + if (is_null($survey)) { + return PL_NOT_FOUND; } - if (S::admin() && $admin_allowed) { - if (!$silent) { - $page->trigWarning('Tu as accès à ce sondage car tu es administrateur du site.'); - } - return true; + if (!$survey->canSee(S::user())) { + return PL_FORBIDDEN; } - if (!$silent) { - $page->kill("Tu n'as pas accès à ce sondage car il est réservé à d'autres promotions."); - } - return false; - } - // }}} - - // {{{ function show_survey() : calls the template to display a survey, for editing, voting, or consulting the results - function show_survey(&$page, $survey) - { - $page->changeTpl('survey/show_root.tpl'); - $page->assign('survey', $survey->toArray()); - $page->assign('survey_modes', Survey::getModes()); - } - // }}} - - // {{{ function show_form() : calls the template to display the editing form - function show_form(&$page, $action, $qid, $type = 'new', $current = null) - { - $page->changeTpl('survey/edit_survey.tpl'); - $page->assign('survey_action', $action); - $page->assign('survey_qid', $qid); - $page->assign('survey_formaction', './survey/edit'); - $page->assign('survey_type', $type); - if (!is_null($current) && is_array($current)) { - $page->assign('survey_current', $current); - } elseif ($type == 'new') { - $page->addJsLink('ajax.js'); - $page->assign('survey_types', Survey::getTypes()); - } - if ($type == 'root' || $type == 'newsurvey') { - $page->assign('survey_modes', Survey::getModes()); - } - } - // }}} - - // {{{ function show_confirm() : calls the template to display a confirm form - function show_confirm(&$page, $message, $formaction, $formhidden = null) - { - $page->changeTpl('survey/confirm.tpl'); - $page->assign('survey_message', $message); - $page->assign('survey_formaction', './survey/'.$formaction); - $page->assign('survey_formhidden', $formhidden); - } - // }}} - - // {{{ function show_error() : calls the template to display an error message - function show_error(&$page, $message, $link = "", $errArray = null) - { - $page->changeTpl('survey/error.tpl'); - $page->assign('survey_message', $message); - $page->assign('survey_link', $link); // 'return' link to let the user leave the page - if (!is_null($errArray)) { - $page->assign('survey_errors', $errArray); - } - - } - // }}} - - // {{{ function show_success() : calls the template to display a success message - function show_success(&$page, $message = "", $link = "") - { - $page->changeTpl('survey/success.tpl'); - $page->assign('survey_message', $message); - $page->assign('survey_link', $link); // 'return' link to let the user leave the page + $page->assign('survey', $survey); } - // }}} } // vim:set et sw=4 sts=4 ts=4 foldmethod=marker enc=utf-8: diff --git a/modules/survey/section.inc.php b/modules/survey/section.inc.php new file mode 100644 index 0000000..fec78eb --- /dev/null +++ b/modules/survey/section.inc.php @@ -0,0 +1,33 @@ +type = "section"; + $this->flags = 'noanswer'; + } +} + +// vim:set et sw=4 sts=4 ts=4 foldmethod=marker enc=utf-8: +?> diff --git a/modules/survey/survey.inc.php b/modules/survey/survey.inc.php index cfc2812..c96a44d 100644 --- a/modules/survey/survey.inc.php +++ b/modules/survey/survey.inc.php @@ -19,805 +19,241 @@ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * ***************************************************************************/ -// {{{ class Survey : root of any survey, contains all questions -class Survey +class Survey extends PlDBTableEntry implements SurveyQuestionContainer { - // {{{ 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"); + private $fetchQuestions = true; + public $questions = array(); - 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() - { - return self::$types; - } - - public static function isType($t) - { - return array_key_exists($t, self::$types); - } - // }}} - - // {{{ properties, constructor and basic methods - private $id; - private $title; - private $description; - private $end; - private $mode; - private $promos; - private $valid; - private $questions; - private $creator; - - public function __construct($args, $id = -1, $valid = false, $questions = null) - { - $this->update($args); - $this->id = $id; - $this->valid = $valid; - $this->questions = ($questions == null)? array() : $questions; - } - - public function update($args) - { - $this->title = $args['title']; - $this->description = $args['description']; - $this->end = $args['end']; - $this->mode = (isset($args['mode']))? $args['mode'] : self::MODE_ALL; - $this->creator = $args['uid']; - if ($this->mode == self::MODE_ALL) { - $args['promos'] = ''; - } - $args['promos'] = str_replace(' ', '', $args['promos']); - $this->promos = ($args['promos'] == '' || preg_match('#^(\d{4}-?|(\d{4})?-\d{4})(,(\d{4}-?|(\d{4})?-\d{4}))*$#', $args['promos']))? $args['promos'] : '#'; - } - - public function canSeeEarlyResults(User $user) - { - return $user->id() == $this->creator || $user->checkPerms('admin'); - } - // }}} - - // {{{ functions to access general information - public function isMode($mode) + public function __construct() { - return ($this->mode == $mode); + parent::__construct('surveys'); + $this->registerFieldValidator('shortname', 'ShortNameFieldValidator'); + $this->registerFieldFormatter('voters', 'JSonFieldFormatter'); + $this->registerFieldFormatter('viewers', 'JSonFieldFormatter'); } - public function checkPromo($promo) + protected function postFetch() { - if ($this->promos == '') { + if (!$this->fetchQuestions) { return true; } - $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 || - intval(substr($p, 0, 4)) >= $promo && intval(substr($p, 5)) <= $promo ))) { - return true; - } - } - return false; - } - - public function isValid() - { - return $this->valid; - } - - public function isEnded() - { - return (strtotime($this->end) - time() <= 0); - } - - public function getTitle() - { - return $this->title; - } - // }}} - - // {{{ function toArray() : converts a question (or the whole survey) to array, with results if the survey is ended - public function toArray($i = 'all') - { - 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(); + $selector = new SurveyQuestion($this); + $selector->sid = $this->id; + + $stack = array(); + foreach ($selector as $question) { + $question = $question->typedInstance(); + if (is_null($question->parent)) { + $this->addQuestion($question); } 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; + $pos = count($stack) - 1; + while ($stack[$pos]->qid != $question->parent) { + --$pos; + array_pop($stack); } - $a['questions'] = $qArr; + Platal::assert(count($stack) > 0, "Invalid question structure"); + Platal::assert($stack[$pos] instanceof SurveyQuestionContainer, "Invalid question type"); + $stack[$pos]->addQuestion($question); } - return $a; + array_push($stack, $question); } + return true; } - // }}} - // {{{ function toCSV() : builds a CSV file containing all the results of the survey - public function toCSV($sep = ',', $enc = '"', $asep='|') + protected function postSave() { - $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 - $users = User::getBulkUsersWithUIDs(XDB::fetchAllAssoc('vid', 'SELECT v.id AS vid, v.uid - FROM survey_votes AS v - WHERE v.survey_id = {?} - ORDER BY vid ASC', - $this->id)); - } - $sql = 'SELECT v.id AS vid, a.question_id AS qid, a.answer AS answer - FROM survey_votes AS v - INNER 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 - $vid = -1; - $vid_ = 0; - while (($cur = $res->next()) != 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)) { // and if the user data can be found - $line[1] = $users[$vid]->lastName(); // adds the user data (in the first fields of the line) - $line[2] = $users[$vid]->firstName();; - $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 - } - } - fputcsv($csv, $line, $sep, $enc); // stores the last line into $csv_output - return $csv_output; - } - // }}} + $questions = array(); + $selector = new SurveyQuestion($this); + $selector->sid = $this->id; + $selector->delete(); - // {{{ function factory($type, $args) : builds a question according to the given type - public function factory($t, $args) - { - 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; + $this->reassignQuestionIds(); + foreach ($this->questions as $question) { + $question->sid = $this->id; + $question->insert(); } } - // }}} - // {{{ questions manipulation functions - public function addQuestion($i, $c) + public function addQuestion(SurveyQuestion $question, $pos = null) { - $i = intval($i); - if ($this->valid || $i > count($this->questions)) { - return false; + $question->parent = null; + if (is_null($pos)) { + $this->questions[] = $question; } else { - array_splice($this->questions, $i, 0, array($c)); - return true; + array_splice($this->questions, $pos, 0, $question); } } - public function delQuestion($i) + public function newQuestion($type, $pos = null) { - $i = intval($i); - if ($this->valid || !array_key_exists($i, $this->questions)) { - return false; - } else { - array_splice($this->questions, $i, 1); - return true; - } + $question = SurveyQuestion::instanceForType($this, $type); + $this->addQuestion($question, $pos); + return $question; } - public function editQuestion($i, $a) + public function reassignQuestionIds() { - if ($i == 'root') { - $this->update($a); - } else { - $i = intval($i); - if ($this->valid ||!array_key_exists($i, $this->questions)) { - return false; + $id = 0; + foreach ($this->questions as $question) { + $question->qid = $id; + if ($question instanceof SurveyQuestionContainer) { + $id = $question->reassignQuestionIds(); } else { - $this->questions[$i]->update($a); + $id++; } } - return true; - } - // }}} - - // {{{ 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() - { - $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; + return $id; } - // }}} - // {{{ 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) + public function export() { - 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 surveys - WHERE '.$where.' - ORDER BY end DESC;'; - if ($tpl) { - return XDB::iterator($sql); - } else { - return XDB::iterRow($sql); + $export = parent::export(); + $export['questions'] = array(); + foreach ($this->questions as $question) { + $export['questions'][] = $question->export(); } + return $export; } - // }}} - // {{{ static function retrieveSurvey() : gets a survey in database (and unserialize the survey object structure) - public static function retrieveSurvey($sid) + public function canSee(User $user) { - $sql = 'SELECT questions, title, description, end, mode, promos, uid - FROM surveys - WHERE id={?}'; - $res = XDB::query($sql, $sid); - $data = $res->fetchOneAssoc(); - if (is_null($data) || !is_array($data)) { - return null; + if ($this->uid == $user->id() || $user->hasFlag('admin')) { + return true; } - $survey = new Survey($data, $sid, true, unserialize($data['questions'])); - 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, mode, promos - FROM surveys - WHERE id={?}'; - $res = XDB::query($sql, $sid); - return $res->fetchOneAssoc(); + return false; } - // }}} - // {{{ static function retrieveSurveyReq() : gets a survey request to validate - public static function retrieveSurveyReq($id) + public static function get($name, $fetchQuestions = true) { - $surveyreq = Validate::get_request_by_id($id); - if ($surveyreq == null) { - return null; + if (is_array($name)) { + $name = $name[0]; } - $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; - } - // }}} - - // {{{ function proposeSurvey() : stores a proposition of survey in database (before validation) - public function proposeSurvey() - { - $surveyreq = new SurveyReq($this->title, $this->description, $this->end, $this->mode, $this->promos, $this->questions, S::user()); - return $surveyreq->submit(); - } - // }}} - - // {{{ function updateSurvey() : updates a survey in database (before validation) - public function updateSurvey() - { - if ($this->valid) { - $sql = 'UPDATE 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); + $survey = new Survey(); + $survey->fetchQuestions = $fetchQuestions; + if (can_convert_to_integer($name)) { + $survey->id = $name; } else { - $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); + $survey->shortname = $name; } - } - // }}} - - // {{{ functions vote() and hasVoted() : handles vote to a survey - public function vote($uid, $args) - { - XDB::execute('INSERT INTO survey_votes - SET survey_id = {?}, uid = {?}', - $this->id, ($uid == 0) ? null : $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); - } - } + if (!$survey->fetch()) { + return null; } + return $survey; } - public function hasVoted($uid) - { - $res = XDB::query('SELECT id - FROM survey_votes - WHERE survey_id = {?} AND uid = {?};', $this->id, $uid); // checks whether the user has already voted - return ($res->numRows() != 0); - } - // }}} - - // {{{ static function deleteSurvey() : deletes a survey (and all its votes) - public static function deleteSurvey($sid) - { - $sql = 'DELETE s.*, v.*, a.* - FROM 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); - } - // }}} - - // {{{ static function purgeVotes() : clears all votes concerning a survey (I'm not sure whether it's really useful) - public static function purgeVotes($sid) + public static function iterActive() { - $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); + $survey = new Survey(); + $survey->fetchQuestions = false; + return $survey->iterateOnCondition('begin <= CURDATE() AND end >= CURDATE() + AND FIND_IN_SET(\'validated\', flags)'); } - // }}} - - // }}} } -// }}} -// {{{ abstract class SurveyQuestion -abstract class SurveyQuestion +class ShortNameFieldValidator implements PlDBTableFieldValidator { - // {{{ common properties, constructor, and basic methods - private $question; - private $comment; - - public function __construct($args) + public function __construct(PlDBTableField $field, $value) { - $this->update($args); - } - - public function update($a) - { - $this->question = $a['question']; - $this->comment = $a['comment']; - } - - abstract protected function getQuestionType(); - // }}} - - // {{{ function toArray() : converts to array - public function toArray() - { - return array('type' => $this->getQuestionType(), 'question' => $this->question, 'comment' => $this->comment); - } - // }}} - - // {{{ function checkSyntax() : checks question elements (before storing into database), not currently needed (with new structure) - protected function checkSyntax() - { - return null; - } - // }}} - - // {{{ function checkAnswer : returns a correct answer (or a null value if error) - public function checkAnswer($ans) - { - return null; - } - // }}} - - // {{{ functions regarding the results of a survey - abstract public function getResultArray($sid, $qid); - - public function formatAnswer($ans) - { - return $ans; - } - - public function getCSVColumns() - { - return $this->question; + if (can_convert_to_integer($value) || !preg_match('/^[a-z0-9]+[-_\.a-z0-9]*[a-z0-9]+$/i', $value)) { + throw new PlDBBadValueException($value, $field, + 'The shortname can only contain alphanumerical caracters, dashes, underscores and dots'); + } } - // }}} } -// }}} -// {{{ abstract class SurveySimple and its derived classes : "open" questions -// {{{ abstract class SurveySimple extends SurveyQuestion -abstract class SurveySimple extends SurveyQuestion +interface SurveyQuestionContainer { - public function checkAnswer($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(); - } + public function addQuestion(SurveyQuestion $question, $pos = null); + public function newQuestion($type, $pos = null); + public function reassignQuestionIds(); } -// }}} -// {{{ class SurveyText extends SurveySimple : simple text field, allowing a few words -class SurveyText extends SurveySimple +class SurveyQuestion extends PlDBTableEntry { - public function getQuestionType() - { - return "text"; - } -} -// }}} + protected $survey; + protected $parentQuestion; -// {{{ class SurveyTextarea extends SurveySimple : textarea field, allowing longer comments -class SurveyTextarea extends SurveySimple -{ - public function getQuestionType() + public function __construct(Survey $survey) { - return "textarea"; + parent::__construct('survey_questions'); + $this->registerFieldFormatter('parameters', 'JSonFieldFormatter'); + $this->survey = $survey; } -} -// }}} -// {{{ class SurveyNum extends SurveySimple : allows numerical answers -class SurveyNum extends SurveySimple -{ - public function checkAnswer($ans) + public function typedInstance() { - return array(intval($ans)); + $instance = self::instanceForType($this->survey, $this->type); + $instance->copy($this); + return $instance; } - protected function getQuestionType() + public static function instanceForType(Survey $survey, $type) { - return "num"; + require_once dirname(__FILE__) . '/' . $type . '.inc.php'; + $class = 'SurveyQuestion' . $type; + return new $class($survey); } } -// }}} -// }}} -// {{{ 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 +class SurveyQuestionGroup extends SurveyQuestion implements SurveyQuestionContainer { - protected $choices; - - public function update($args) - { - parent::update($args); - $this->choices = array(); - foreach ($args['choices'] as $val) { - if (trim($val) || trim($val) == '0') { - $this->choices[] = $val; - } - } - } - - public function toArray() - { - $rArr = parent::toArray(); - $rArr['choices'] = $this->choices; - return $rArr; - } + public $children = array(); - public function getResultArray($sid, $qid) + public function __construct(Survey $survey) { - $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(); + parent::__construct($survey); } - public function formatAnswer($ans) + public function addQuestion(SurveyQuestion $question, $pos = null) { - if (array_key_exists($ans, $this->choices)) { - return $this->choices[$ans]; + $question->parentQuestion = $this; + if (is_null($pos)) { + $this->children[] = $question; } else { - return null; - } - } -} -// }}} - -// {{{ class SurveyRadio extends SurveyList : radio question, allows one answer among the list offered -class SurveyRadio extends SurveyList -{ - public function checkAnswer($ans) - { - $a = intval($ans); - return (array_key_exists($a, $this->choices))? array($a) : null; - } - - protected function getQuestionType() - { - return "radio"; - } -} -// }}} - -// {{{ class SurveyCheckbox extends SurveyList : checkbox question, allows any number of answers among the list offered -class SurveyCheckbox extends SurveyList -{ - public function checkAnswer($ans) - { - $rep = array(); - foreach ($ans as $a) { - $a = intval($a); - if (array_key_exists($a, $this->choices)) { - $rep[] = $a; - } + array_splice($this->children, $pos, 0, $question); } - return (count($rep) == 0)? null : $rep; } - protected function getQuestionType() + public function newQuestion($type, $pos = null) { - return "checkbox"; + $question = SurveyQuestion::instanceForType($this->survey, $type); + $this->addQuestion($question, $pos); + return $question; } -} -// }}} -// }}} -// {{{ 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 -{ - protected $subquestions; - - public function update($args) + public function reassignQuestionIds() { - parent::update($args); - $this->subquestions = array(); - foreach ($args['subquestions'] as $val) { - if (trim($val) || trim($val) == '0') { - $this->subquestions[] = $val; + $id = $this->qid + 1; + foreach ($this->children as $question) { + $question->qid = $id; + if ($question instanceof SurveyQuestionContainer) { + $id = $question->reassignQuestionIds(); + } else { + $id++; } } + return $id; } - public function toArray() - { - $rArr = parent::toArray(); - $rArr['subquestions'] = $this->subquestions; - 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::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 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) + protected function postSave() { - $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; - } + foreach ($this->children as $question) { + $question->sid = $this->sid; + $question->parent = $this->qid; + $question->insert(); } - return (count($rep) == 0)? null : $rep; - } - - protected function getQuestionType() - { - return "radiotable"; } -} -// }}} - -// {{{ class SurveyCheckboxTable extends SurveyTable : SurveyTable with checkbox type choices -class SurveyCheckboxTable extends SurveyTable -{ - public function checkAnswer($ans) + public function export() { - $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; - } - } + $export = parent::export(); + $export['children'] = array(); + foreach ($this->children as $child) { + $export['children'][] = $child->export(); } - return (count($rep) == 0)? null : $rep; - } - - protected function getQuestionType() - { - return "checkboxtable"; + return $export; } - } -// }}} -// }}} // vim:set et sw=4 sts=4 ts=4 foldmethod=marker enc=utf-8: ?> diff --git a/modules/survey/text.inc.php b/modules/survey/text.inc.php new file mode 100644 index 0000000..5bb65d0 --- /dev/null +++ b/modules/survey/text.inc.php @@ -0,0 +1,32 @@ +type = "text"; + } +} + +// vim:set et sw=4 sts=4 ts=4 foldmethod=marker enc=utf-8: +?> diff --git a/templates/survey/admin.tpl b/templates/survey/admin.tpl deleted file mode 100644 index 5772098..0000000 --- a/templates/survey/admin.tpl +++ /dev/null @@ -1,75 +0,0 @@ -{**************************************************************************} -{* *} -{* Copyright (C) 2003-2010 Polytechnique.org *} -{* http://opensource.polytechnique.org/ *} -{* *} -{* This program is free software; you can redistribute it and/or modify *} -{* it under the terms of the GNU General Public License as published by *} -{* the Free Software Foundation; either version 2 of the License, or *} -{* (at your option) any later version. *} -{* *} -{* This program is distributed in the hope that it will be useful, *} -{* but WITHOUT ANY WARRANTY; without even the implied warranty of *} -{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *} -{* GNU General Public License for more details. *} -{* *} -{* You should have received a copy of the GNU General Public License *} -{* along with this program; if not, write to the Free Software *} -{* Foundation, Inc., *} -{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *} -{* *} -{**************************************************************************} - -

Sondages

- - - - - - {iterate item=s from=$survey_current} - - - - {assign var="has_cs" value="true"} - {/iterate} - {if !$has_cs} - - - - {/if} -
- Sondages en cours -
- • - - {$s.title} [{$s.end|date_format:"%x"} - {$survey_modes[$s.mode]}] - -
Aucun sondage en cours
- -
- - - - - - {iterate item=s from=$survey_old} - - - - {assign var="has_os" value="true"} - {/iterate} - {if !$has_os} - - - - {/if} -
- Anciens sondages -
- • - - {$s.title} [{$s.end|date_format:"%x"} - {$survey_modes[$s.mode]}] - -
Aucun ancien sondage
- -{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *} diff --git a/templates/survey/confirm.tpl b/templates/survey/confirm.tpl deleted file mode 100644 index b6f5552..0000000 --- a/templates/survey/confirm.tpl +++ /dev/null @@ -1,40 +0,0 @@ -{**************************************************************************} -{* *} -{* Copyright (C) 2003-2010 Polytechnique.org *} -{* http://opensource.polytechnique.org/ *} -{* *} -{* This program is free software; you can redistribute it and/or modify *} -{* it under the terms of the GNU General Public License as published by *} -{* the Free Software Foundation; either version 2 of the License, or *} -{* (at your option) any later version. *} -{* *} -{* This program is distributed in the hope that it will be useful, *} -{* but WITHOUT ANY WARRANTY; without even the implied warranty of *} -{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *} -{* GNU General Public License for more details. *} -{* *} -{* You should have received a copy of the GNU General Public License *} -{* along with this program; if not, write to the Free Software *} -{* Foundation, Inc., *} -{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *} -{* *} -{**************************************************************************} -

Sondages : confirmation

- -
- {if is_array($survey_formhidden)} - {foreach from=$survey_formhidden item=s_value key=s_key} - - {/foreach} - {/if} - {if $survey_message neq ""} - {$survey_message} - {else} - Une confirmation est requise - {/if} -
- - -
- -{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *} diff --git a/templates/survey/edit_checkbox.tpl b/templates/survey/edit_checkbox.tpl deleted file mode 100644 index 3569cb6..0000000 --- a/templates/survey/edit_checkbox.tpl +++ /dev/null @@ -1,25 +0,0 @@ -{**************************************************************************} -{* *} -{* Copyright (C) 2003-2010 Polytechnique.org *} -{* http://opensource.polytechnique.org/ *} -{* *} -{* This program is free software; you can redistribute it and/or modify *} -{* it under the terms of the GNU General Public License as published by *} -{* the Free Software Foundation; either version 2 of the License, or *} -{* (at your option) any later version. *} -{* *} -{* This program is distributed in the hope that it will be useful, *} -{* but WITHOUT ANY WARRANTY; without even the implied warranty of *} -{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *} -{* GNU General Public License for more details. *} -{* *} -{* You should have received a copy of the GNU General Public License *} -{* along with this program; if not, write to the Free Software *} -{* Foundation, Inc., *} -{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *} -{* *} -{**************************************************************************} - -{include file='survey/edit_radio.tpl'} - -{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *} diff --git a/templates/survey/edit_checkboxtable.tpl b/templates/survey/edit_checkboxtable.tpl deleted file mode 100644 index 14b11d9..0000000 --- a/templates/survey/edit_checkboxtable.tpl +++ /dev/null @@ -1,25 +0,0 @@ -{**************************************************************************} -{* *} -{* Copyright (C) 2003-2010 Polytechnique.org *} -{* http://opensource.polytechnique.org/ *} -{* *} -{* This program is free software; you can redistribute it and/or modify *} -{* it under the terms of the GNU General Public License as published by *} -{* the Free Software Foundation; either version 2 of the License, or *} -{* (at your option) any later version. *} -{* *} -{* This program is distributed in the hope that it will be useful, *} -{* but WITHOUT ANY WARRANTY; without even the implied warranty of *} -{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *} -{* GNU General Public License for more details. *} -{* *} -{* You should have received a copy of the GNU General Public License *} -{* along with this program; if not, write to the Free Software *} -{* Foundation, Inc., *} -{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *} -{* *} -{**************************************************************************} - -{include file='survey/edit_radiotable.tpl'} - -{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *} diff --git a/templates/survey/edit_new.tpl b/templates/survey/edit_new.tpl deleted file mode 100644 index ea6d666..0000000 --- a/templates/survey/edit_new.tpl +++ /dev/null @@ -1,38 +0,0 @@ -{**************************************************************************} -{* *} -{* Copyright (C) 2003-2010 Polytechnique.org *} -{* http://opensource.polytechnique.org/ *} -{* *} -{* This program is free software; you can redistribute it and/or modify *} -{* it under the terms of the GNU General Public License as published by *} -{* the Free Software Foundation; either version 2 of the License, or *} -{* (at your option) any later version. *} -{* *} -{* This program is distributed in the hope that it will be useful, *} -{* but WITHOUT ANY WARRANTY; without even the implied warranty of *} -{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *} -{* GNU General Public License for more details. *} -{* *} -{* You should have received a copy of the GNU General Public License *} -{* along with this program; if not, write to the Free Software *} -{* Foundation, Inc., *} -{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *} -{* *} -{**************************************************************************} - - Type - - - - - {if $survey_type == "new"} - {include file='survey/edit_question.tpl'} - {else} - {include file="survey/edit_$survey_type.tpl"} - {/if} - -{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *} diff --git a/templates/survey/edit_newsurvey.tpl b/templates/survey/edit_newsurvey.tpl deleted file mode 100644 index ec9e61e..0000000 --- a/templates/survey/edit_newsurvey.tpl +++ /dev/null @@ -1,31 +0,0 @@ -{**************************************************************************} -{* *} -{* Copyright (C) 2003-2010 Polytechnique.org *} -{* http://opensource.polytechnique.org/ *} -{* *} -{* This program is free software; you can redistribute it and/or modify *} -{* it under the terms of the GNU General Public License as published by *} -{* the Free Software Foundation; either version 2 of the License, or *} -{* (at your option) any later version. *} -{* *} -{* This program is distributed in the hope that it will be useful, *} -{* but WITHOUT ANY WARRANTY; without even the implied warranty of *} -{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *} -{* GNU General Public License for more details. *} -{* *} -{* You should have received a copy of the GNU General Public License *} -{* along with this program; if not, write to the Free Software *} -{* Foundation, Inc., *} -{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *} -{* *} -{**************************************************************************} - - - - Remplissez ici une description générale du sondage, puis cliquer sur "Continuer" - pour passer à l'édition des questions. - - -{include file='survey/edit_root.tpl'} - -{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *} diff --git a/templates/survey/edit_num.tpl b/templates/survey/edit_num.tpl deleted file mode 100644 index b62ed4b..0000000 --- a/templates/survey/edit_num.tpl +++ /dev/null @@ -1,25 +0,0 @@ -{**************************************************************************} -{* *} -{* Copyright (C) 2003-2010 Polytechnique.org *} -{* http://opensource.polytechnique.org/ *} -{* *} -{* This program is free software; you can redistribute it and/or modify *} -{* it under the terms of the GNU General Public License as published by *} -{* the Free Software Foundation; either version 2 of the License, or *} -{* (at your option) any later version. *} -{* *} -{* This program is distributed in the hope that it will be useful, *} -{* but WITHOUT ANY WARRANTY; without even the implied warranty of *} -{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *} -{* GNU General Public License for more details. *} -{* *} -{* You should have received a copy of the GNU General Public License *} -{* along with this program; if not, write to the Free Software *} -{* Foundation, Inc., *} -{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *} -{* *} -{**************************************************************************} - - {include file='survey/edit_question.tpl'} - -{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *} diff --git a/templates/survey/edit_question.tpl b/templates/survey/edit_question.tpl deleted file mode 100644 index 11e0858..0000000 --- a/templates/survey/edit_question.tpl +++ /dev/null @@ -1,61 +0,0 @@ -{**************************************************************************} -{* *} -{* Copyright (C) 2003-2010 Polytechnique.org *} -{* http://opensource.polytechnique.org/ *} -{* *} -{* This program is free software; you can redistribute it and/or modify *} -{* it under the terms of the GNU General Public License as published by *} -{* the Free Software Foundation; either version 2 of the License, or *} -{* (at your option) any later version. *} -{* *} -{* This program is distributed in the hope that it will be useful, *} -{* but WITHOUT ANY WARRANTY; without even the implied warranty of *} -{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *} -{* GNU General Public License for more details. *} -{* *} -{* You should have received a copy of the GNU General Public License *} -{* along with this program; if not, write to the Free Software *} -{* Foundation, Inc., *} -{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *} -{* *} -{**************************************************************************} - - - Question - - - - Commentaire - - - - - - - {icon name=information title="Syntaxe wiki"} Voir la syntaxe wiki autorisée pour le commentaire d'une question - - - - - -{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *} diff --git a/templates/survey/edit_radio.tpl b/templates/survey/edit_radio.tpl deleted file mode 100644 index 8b4e1b2..0000000 --- a/templates/survey/edit_radio.tpl +++ /dev/null @@ -1,39 +0,0 @@ -{**************************************************************************} -{* *} -{* Copyright (C) 2003-2010 Polytechnique.org *} -{* http://opensource.polytechnique.org/ *} -{* *} -{* This program is free software; you can redistribute it and/or modify *} -{* it under the terms of the GNU General Public License as published by *} -{* the Free Software Foundation; either version 2 of the License, or *} -{* (at your option) any later version. *} -{* *} -{* This program is distributed in the hope that it will be useful, *} -{* but WITHOUT ANY WARRANTY; without even the implied warranty of *} -{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *} -{* GNU General Public License for more details. *} -{* *} -{* You should have received a copy of the GNU General Public License *} -{* along with this program; if not, write to the Free Software *} -{* Foundation, Inc., *} -{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *} -{* *} -{**************************************************************************} - - {include file='survey/edit_question.tpl'} - - Choix - - {foreach from=$survey_current.choices key=value item=choice} - - {/foreach} - - - - -{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *} diff --git a/templates/survey/edit_radiotable.tpl b/templates/survey/edit_radiotable.tpl deleted file mode 100644 index 0e034c3..0000000 --- a/templates/survey/edit_radiotable.tpl +++ /dev/null @@ -1,39 +0,0 @@ -{**************************************************************************} -{* *} -{* Copyright (C) 2003-2010 Polytechnique.org *} -{* http://opensource.polytechnique.org/ *} -{* *} -{* This program is free software; you can redistribute it and/or modify *} -{* it under the terms of the GNU General Public License as published by *} -{* the Free Software Foundation; either version 2 of the License, or *} -{* (at your option) any later version. *} -{* *} -{* This program is distributed in the hope that it will be useful, *} -{* but WITHOUT ANY WARRANTY; without even the implied warranty of *} -{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *} -{* GNU General Public License for more details. *} -{* *} -{* You should have received a copy of the GNU General Public License *} -{* along with this program; if not, write to the Free Software *} -{* Foundation, Inc., *} -{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *} -{* *} -{**************************************************************************} - -{include file='survey/edit_radio.tpl'} - - Sous-questions - - {foreach from=$survey_current.subquestions key=value item=subquestion} - - {/foreach} - - - - -{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *} diff --git a/templates/survey/edit_root.tpl b/templates/survey/edit_root.tpl deleted file mode 100644 index 3bc93cf..0000000 --- a/templates/survey/edit_root.tpl +++ /dev/null @@ -1,85 +0,0 @@ -{**************************************************************************} -{* *} -{* Copyright (C) 2003-2010 Polytechnique.org *} -{* http://opensource.polytechnique.org/ *} -{* *} -{* This program is free software; you can redistribute it and/or modify *} -{* it under the terms of the GNU General Public License as published by *} -{* the Free Software Foundation; either version 2 of the License, or *} -{* (at your option) any later version. *} -{* *} -{* This program is distributed in the hope that it will be useful, *} -{* but WITHOUT ANY WARRANTY; without even the implied warranty of *} -{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *} -{* GNU General Public License for more details. *} -{* *} -{* You should have received a copy of the GNU General Public License *} -{* along with this program; if not, write to the Free Software *} -{* Foundation, Inc., *} -{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *} -{* *} -{**************************************************************************} - - - Titre - - - - Commentaire - - - - - - - {icon name=information title="Syntaxe wiki"} Voir la syntaxe wiki autorisée pour le commentaire du sondage - - - - - Date de fin - - {valid_date name="survey_question[end]" value=$survey_current.end to=90} - - - - - Type de sondage - - - - - - Promotions - - - - - - Exemple : 1954,1986-1989,-1942,2000-   restreindra le sondage à toutes les promotions suivantes :
- 1954, 1986 à 1989, toutes jusqu'à 1942 et toutes à partir 2000 (les bornes sont systématiquement incluses).
- Pour sélectionner toutes les promotions, laisser le vide. - - - -{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *} diff --git a/templates/survey/edit_survey.tpl b/templates/survey/edit_survey.tpl deleted file mode 100644 index 0d3160b..0000000 --- a/templates/survey/edit_survey.tpl +++ /dev/null @@ -1,43 +0,0 @@ -{**************************************************************************} -{* *} -{* Copyright (C) 2003-2010 Polytechnique.org *} -{* http://opensource.polytechnique.org/ *} -{* *} -{* This program is free software; you can redistribute it and/or modify *} -{* it under the terms of the GNU General Public License as published by *} -{* the Free Software Foundation; either version 2 of the License, or *} -{* (at your option) any later version. *} -{* *} -{* This program is distributed in the hope that it will be useful, *} -{* but WITHOUT ANY WARRANTY; without even the implied warranty of *} -{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *} -{* GNU General Public License for more details. *} -{* *} -{* You should have received a copy of the GNU General Public License *} -{* along with this program; if not, write to the Free Software *} -{* Foundation, Inc., *} -{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *} -{* *} -{**************************************************************************} -

Sondage : - {if $survey_type == 'newsurvey'} créer un nouveau sondage - {elseif $survey_type == 'new'} ajouter une question - {elseif $survey_type == 'root'} modifier la description - {else} modifier une question - {/if} -

- -
- - - - {include file="survey/edit_$survey_type.tpl"} -
-
- - - -
-
- -{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *} diff --git a/templates/survey/edit_textarea.tpl b/templates/survey/edit_textarea.tpl deleted file mode 100644 index b62ed4b..0000000 --- a/templates/survey/edit_textarea.tpl +++ /dev/null @@ -1,25 +0,0 @@ -{**************************************************************************} -{* *} -{* Copyright (C) 2003-2010 Polytechnique.org *} -{* http://opensource.polytechnique.org/ *} -{* *} -{* This program is free software; you can redistribute it and/or modify *} -{* it under the terms of the GNU General Public License as published by *} -{* the Free Software Foundation; either version 2 of the License, or *} -{* (at your option) any later version. *} -{* *} -{* This program is distributed in the hope that it will be useful, *} -{* but WITHOUT ANY WARRANTY; without even the implied warranty of *} -{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *} -{* GNU General Public License for more details. *} -{* *} -{* You should have received a copy of the GNU General Public License *} -{* along with this program; if not, write to the Free Software *} -{* Foundation, Inc., *} -{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *} -{* *} -{**************************************************************************} - - {include file='survey/edit_question.tpl'} - -{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *} diff --git a/templates/survey/error.tpl b/templates/survey/error.tpl deleted file mode 100644 index 63c96d4..0000000 --- a/templates/survey/error.tpl +++ /dev/null @@ -1,44 +0,0 @@ -{**************************************************************************} -{* *} -{* Copyright (C) 2003-2010 Polytechnique.org *} -{* http://opensource.polytechnique.org/ *} -{* *} -{* This program is free software; you can redistribute it and/or modify *} -{* it under the terms of the GNU General Public License as published by *} -{* the Free Software Foundation; either version 2 of the License, or *} -{* (at your option) any later version. *} -{* *} -{* This program is distributed in the hope that it will be useful, *} -{* but WITHOUT ANY WARRANTY; without even the implied warranty of *} -{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *} -{* GNU General Public License for more details. *} -{* *} -{* You should have received a copy of the GNU General Public License *} -{* along with this program; if not, write to the Free Software *} -{* Foundation, Inc., *} -{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *} -{* *} -{**************************************************************************} -

Sondages : erreur

- -{if !is_null($survey_errors) && is_array($survey_errors)} - - - - - {foreach from=$survey_errors item=survey_error} - - - - - {/foreach} -
Une ou plusieurs erreurs sont survenues
• {$survey_error.error}corriger
-{elseif $survey_message neq ""} - {$survey_message} -{else} -Une erreur inconnue est survenue dans l'édition de ce sondage. N'hésite pas à signaler ce bug s'il persiste. -{/if} -
-Retour - -{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *} diff --git a/templates/survey/index.tpl b/templates/survey/index.tpl index 1110521..5523fc8 100644 --- a/templates/survey/index.tpl +++ b/templates/survey/index.tpl @@ -22,73 +22,21 @@

Sondages

-{* Survey::MODE_ALL equals 0. *} -{assign var=SurveyMODE_ALL value=0} -{if $survey_current->total() > 0 || $smarty.session.auth} +{if $active->total() > 0} - - {iterate item=s from=$survey_current} - {if $smarty.session.auth || $s.mode == $SurveyMODE_ALL} - - - - - - {assign var="has_cs" value="true"} - {/if} - {/iterate} - - - -
+ Sondages en cours
- {$s.title} - {if $s.uid eq $smarty.session.user->id() || hasPerm('admin')} - (résultats partiels) - {/if} - - {$s.end|date_format:"%x"} - - {$survey_modes[$s.mode]} -
- {if $smarty.session.auth}{icon name=page_edit} Proposer un sondage{/if} -
-{/if} - -
- - + {iterate from=$active item=survey} - - - {iterate item=s from=$survey_old} - {if $smarty.session.auth || $s.mode == $SurveyMODE_ALL} - - - - {assign var="has_os" value="true"} - {/if} {/iterate} - {if !$has_os} - - - - {/if}
- Anciens sondages -
- - {$s.title} - - - {$s.end|date_format:"%x"} - - {$survey_modes[$s.mode]} + {$survey->title}
Aucun ancien sondage
+{/if} {* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *} diff --git a/templates/survey/show_checkbox.tpl b/templates/survey/show_checkbox.tpl deleted file mode 100644 index 8fc5388..0000000 --- a/templates/survey/show_checkbox.tpl +++ /dev/null @@ -1,39 +0,0 @@ -{**************************************************************************} -{* *} -{* Copyright (C) 2003-2010 Polytechnique.org *} -{* http://opensource.polytechnique.org/ *} -{* *} -{* This program is free software; you can redistribute it and/or modify *} -{* it under the terms of the GNU General Public License as published by *} -{* the Free Software Foundation; either version 2 of the License, or *} -{* (at your option) any later version. *} -{* *} -{* This program is distributed in the hope that it will be useful, *} -{* but WITHOUT ANY WARRANTY; without even the implied warranty of *} -{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *} -{* GNU General Public License for more details. *} -{* *} -{* You should have received a copy of the GNU General Public License *} -{* along with this program; if not, write to the Free Software *} -{* Foundation, Inc., *} -{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *} -{* *} -{**************************************************************************} - -{if $survey_resultmode} - -{else} - {assign var=sid value=$survey.id} - {assign var=sqid value=$squestion.id} - {if $survey_votemode} - {html_checkboxes name="survey$sid[$sqid]" options=$squestion.choices separator='
'} - {else} - {html_checkboxes name="survey$sid[$sqid]" options=$squestion.choices separator='
' disabled='disabled'} - {/if} -{/if} - -{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *} diff --git a/templates/survey/show_checkboxtable.tpl b/templates/survey/show_checkboxtable.tpl deleted file mode 100644 index b58a0e9..0000000 --- a/templates/survey/show_checkboxtable.tpl +++ /dev/null @@ -1,52 +0,0 @@ -{**************************************************************************} -{* *} -{* Copyright (C) 2003-2010 Polytechnique.org *} -{* http://opensource.polytechnique.org/ *} -{* *} -{* This program is free software; you can redistribute it and/or modify *} -{* it under the terms of the GNU General Public License as published by *} -{* the Free Software Foundation; either version 2 of the License, or *} -{* (at your option) any later version. *} -{* *} -{* This program is distributed in the hope that it will be useful, *} -{* but WITHOUT ANY WARRANTY; without even the implied warranty of *} -{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *} -{* GNU General Public License for more details. *} -{* *} -{* You should have received a copy of the GNU General Public License *} -{* along with this program; if not, write to the Free Software *} -{* Foundation, Inc., *} -{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *} -{* *} -{**************************************************************************} - - - - - {foreach from=$squestion.choices item=schoice} - - {/foreach} - -{foreach from=$squestion.subquestions item=ssubq key=ssqid} - - - {assign var=sid value=$survey.id} - {assign var=sqid value=$squestion.id} - {if $survey_resultmode} - {foreach from=$squestion.choices item=schoice key=value} - - {/foreach} - {else} - {foreach from=$squestion.choices item=schoice key=value} - - {/foreach} - {/if} - -{/foreach} -
{$schoice}
{$ssubq} - {$squestion.result.$ssqid.$value*100/$survey.votes|string_format:"%.1f"}% ({$squestion.result.$ssqid.$value} votes) - - -
- -{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *} diff --git a/templates/survey/show_num.tpl b/templates/survey/show_num.tpl deleted file mode 100644 index 37ca12f..0000000 --- a/templates/survey/show_num.tpl +++ /dev/null @@ -1,25 +0,0 @@ -{**************************************************************************} -{* *} -{* Copyright (C) 2003-2010 Polytechnique.org *} -{* http://opensource.polytechnique.org/ *} -{* *} -{* This program is free software; you can redistribute it and/or modify *} -{* it under the terms of the GNU General Public License as published by *} -{* the Free Software Foundation; either version 2 of the License, or *} -{* (at your option) any later version. *} -{* *} -{* This program is distributed in the hope that it will be useful, *} -{* but WITHOUT ANY WARRANTY; without even the implied warranty of *} -{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *} -{* GNU General Public License for more details. *} -{* *} -{* You should have received a copy of the GNU General Public License *} -{* along with this program; if not, write to the Free Software *} -{* Foundation, Inc., *} -{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *} -{* *} -{**************************************************************************} - -{include file='survey/show_text.tpl'} - -{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *} diff --git a/templates/survey/show_question.tpl b/templates/survey/show_question.tpl deleted file mode 100644 index 4acb162..0000000 --- a/templates/survey/show_question.tpl +++ /dev/null @@ -1,30 +0,0 @@ -{**************************************************************************} -{* *} -{* Copyright (C) 2003-2010 Polytechnique.org *} -{* http://opensource.polytechnique.org/ *} -{* *} -{* This program is free software; you can redistribute it and/or modify *} -{* it under the terms of the GNU General Public License as published by *} -{* the Free Software Foundation; either version 2 of the License, or *} -{* (at your option) any later version. *} -{* *} -{* This program is distributed in the hope that it will be useful, *} -{* but WITHOUT ANY WARRANTY; without even the implied warranty of *} -{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *} -{* GNU General Public License for more details. *} -{* *} -{* You should have received a copy of the GNU General Public License *} -{* along with this program; if not, write to the Free Software *} -{* Foundation, Inc., *} -{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *} -{* *} -{**************************************************************************} - -

{$squestion.question}

-{if $squestion.comment != ''} - {$squestion.comment|miniwiki|smarty:nodefaults}
-{/if} -{assign var='squestion_type' value=$squestion.type} -{include file="survey/show_$squestion_type.tpl"} - -{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *} diff --git a/templates/survey/show_radio.tpl b/templates/survey/show_radio.tpl deleted file mode 100644 index 473bb05..0000000 --- a/templates/survey/show_radio.tpl +++ /dev/null @@ -1,39 +0,0 @@ -{**************************************************************************} -{* *} -{* Copyright (C) 2003-2010 Polytechnique.org *} -{* http://opensource.polytechnique.org/ *} -{* *} -{* This program is free software; you can redistribute it and/or modify *} -{* it under the terms of the GNU General Public License as published by *} -{* the Free Software Foundation; either version 2 of the License, or *} -{* (at your option) any later version. *} -{* *} -{* This program is distributed in the hope that it will be useful, *} -{* but WITHOUT ANY WARRANTY; without even the implied warranty of *} -{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *} -{* GNU General Public License for more details. *} -{* *} -{* You should have received a copy of the GNU General Public License *} -{* along with this program; if not, write to the Free Software *} -{* Foundation, Inc., *} -{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *} -{* *} -{**************************************************************************} - -{if $survey_resultmode} - -{else} - {assign var=sid value=$survey.id} - {assign var=sqid value=$squestion.id} - {if $survey_votemode} - {html_radios name="survey$sid[$sqid]" options=$squestion.choices separator='
'} - {else} - {html_radios name="survey$sid[$sqid]" options=$squestion.choices separator='
' disabled='disabled'} - {/if} -{/if} - -{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *} diff --git a/templates/survey/show_radiotable.tpl b/templates/survey/show_radiotable.tpl deleted file mode 100644 index 9f24aa1..0000000 --- a/templates/survey/show_radiotable.tpl +++ /dev/null @@ -1,52 +0,0 @@ -{**************************************************************************} -{* *} -{* Copyright (C) 2003-2010 Polytechnique.org *} -{* http://opensource.polytechnique.org/ *} -{* *} -{* This program is free software; you can redistribute it and/or modify *} -{* it under the terms of the GNU General Public License as published by *} -{* the Free Software Foundation; either version 2 of the License, or *} -{* (at your option) any later version. *} -{* *} -{* This program is distributed in the hope that it will be useful, *} -{* but WITHOUT ANY WARRANTY; without even the implied warranty of *} -{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *} -{* GNU General Public License for more details. *} -{* *} -{* You should have received a copy of the GNU General Public License *} -{* along with this program; if not, write to the Free Software *} -{* Foundation, Inc., *} -{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *} -{* *} -{**************************************************************************} - - - - - {foreach from=$squestion.choices item=schoice} - - {/foreach} - -{foreach from=$squestion.subquestions item=ssubq key=ssqid} - - - {assign var=sid value=$survey.id} - {assign var=sqid value=$squestion.id} - {if $survey_resultmode} - {foreach from=$squestion.choices item=schoice key=value} - - {/foreach} - {else} - {foreach from=$squestion.choices item=schoice key=value} - - {/foreach} - {/if} - -{/foreach} -
{$schoice}
{$ssubq} - {$squestion.result.$ssqid.$value*100/$survey.votes|string_format:"%.1f"}% ({$squestion.result.$ssqid.$value} votes) - - -
- -{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *} diff --git a/templates/survey/show_root.tpl b/templates/survey/show_root.tpl deleted file mode 100644 index ca606fd..0000000 --- a/templates/survey/show_root.tpl +++ /dev/null @@ -1,117 +0,0 @@ -{**************************************************************************} -{* *} -{* Copyright (C) 2003-2010 Polytechnique.org *} -{* http://opensource.polytechnique.org/ *} -{* *} -{* This program is free software; you can redistribute it and/or modify *} -{* it under the terms of the GNU General Public License as published by *} -{* the Free Software Foundation; either version 2 of the License, or *} -{* (at your option) any later version. *} -{* *} -{* This program is distributed in the hope that it will be useful, *} -{* but WITHOUT ANY WARRANTY; without even the implied warranty of *} -{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *} -{* GNU General Public License for more details. *} -{* *} -{* You should have received a copy of the GNU General Public License *} -{* along with this program; if not, write to the Free Software *} -{* Foundation, Inc., *} -{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *} -{* *} -{**************************************************************************} - -

Sondage : {$survey.title}

-
- - - - {if $survey_editmode && !$survey.valid} - {assign var="survey_editallmode" value=true} - {/if} - {if $survey_editmode} - - {/if} - - {if is_array($survey.questions)} - {foreach from=$survey.questions item=squestion} - - - {if $survey_editallmode} - - {/if} - - {/foreach} - {/if} -
- - - - - - - - - - - - - {if $survey.mode != Survey::MODE_ALL} - - - - - {/if} - {if $survey_warning} - - - - {/if} -
{$survey.description|miniwiki|smarty:nodefaults}
Fin du sondage :{$survey.end|date_format:"%x"}
Type de sondage :{$survey_modes[$survey.mode]}
Promotions : - {if $survey.promos eq "#"} - erreur - {elseif $survey.promos eq ""} - aucune restriction - {else} - {$survey.promos} - {/if} -
{$survey_warning}
- {if $survey_resultmode} -

{$survey.votes} personnes ont répondu à ce sondage.
- Récupérer l'ensemble des résultats au format csv -

- {/if} -
- {icon name=page_edit alt="Modifier" title="Modifier la description"} - {if $survey_editallmode}
{icon name=add title="Ajouter une question au début" alt="Ajouter"}{/if} -
- {include file='survey/show_question.tpl' squestion=$squestion} - - {icon name=page_edit title="Modifier cette question" alt="Modifier"}
- {icon name=delete title="Supprimer cette question" alt="Supprimer"}
- {icon name=add title="Ajouter une question après" alt="Ajouter"} -
-

- {if $smarty.session.survey_validate || ($survey_editmode && !$survey_updatemode)} - - {icon name=tick} - Proposer ce sondage - | - - {icon name=cross} - Annuler totalement la création de ce sondage - - {elseif $survey_adminmode} - {if !$survey.valid}Valider ce sondage | {/if} - {icon name=tick} Modifier ce sondage | - {icon name=cross} Supprimer ce sondage | - Retour - {elseif $survey_votemode} - - - {else} - Retour - {/if} -

-
- -{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *} diff --git a/templates/survey/show_text.tpl b/templates/survey/show_text.tpl deleted file mode 100644 index 595b171..0000000 --- a/templates/survey/show_text.tpl +++ /dev/null @@ -1,47 +0,0 @@ -{**************************************************************************} -{* *} -{* Copyright (C) 2003-2010 Polytechnique.org *} -{* http://opensource.polytechnique.org/ *} -{* *} -{* This program is free software; you can redistribute it and/or modify *} -{* it under the terms of the GNU General Public License as published by *} -{* the Free Software Foundation; either version 2 of the License, or *} -{* (at your option) any later version. *} -{* *} -{* This program is distributed in the hope that it will be useful, *} -{* but WITHOUT ANY WARRANTY; without even the implied warranty of *} -{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *} -{* GNU General Public License for more details. *} -{* *} -{* You should have received a copy of the GNU General Public License *} -{* along with this program; if not, write to the Free Software *} -{* Foundation, Inc., *} -{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *} -{* *} -{**************************************************************************} - -{if $survey_resultmode} - {if count($squestion.result) == 0} - Aucune réponse n'a été donnée. - {else} - {if count($squestion.result) ==1} - Une réponse donnée par une d{else}Quelques réponses données par l{/if}es personnes sondées : - - {/if} -{else} - -{/if} - -{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *} diff --git a/templates/survey/show_textarea.tpl b/templates/survey/show_textarea.tpl deleted file mode 100644 index 6f18e90..0000000 --- a/templates/survey/show_textarea.tpl +++ /dev/null @@ -1,47 +0,0 @@ -{**************************************************************************} -{* *} -{* Copyright (C) 2003-2010 Polytechnique.org *} -{* http://opensource.polytechnique.org/ *} -{* *} -{* This program is free software; you can redistribute it and/or modify *} -{* it under the terms of the GNU General Public License as published by *} -{* the Free Software Foundation; either version 2 of the License, or *} -{* (at your option) any later version. *} -{* *} -{* This program is distributed in the hope that it will be useful, *} -{* but WITHOUT ANY WARRANTY; without even the implied warranty of *} -{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *} -{* GNU General Public License for more details. *} -{* *} -{* You should have received a copy of the GNU General Public License *} -{* along with this program; if not, write to the Free Software *} -{* Foundation, Inc., *} -{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *} -{* *} -{**************************************************************************} - -{if $survey_resultmode} - {if count($squestion.result) == 0} - Aucune réponse n'a été donnée. - {else} - {if count($squestion.result) ==1} - Une réponse donnée par une d{else}Quelques réponses données par l{/if}es personnes sondées : - - {/if} -{else} - -{/if} - -{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *} diff --git a/templates/survey/success.tpl b/templates/survey/success.tpl deleted file mode 100644 index a2ad4bb..0000000 --- a/templates/survey/success.tpl +++ /dev/null @@ -1,32 +0,0 @@ -{**************************************************************************} -{* *} -{* Copyright (C) 2003-2010 Polytechnique.org *} -{* http://opensource.polytechnique.org/ *} -{* *} -{* This program is free software; you can redistribute it and/or modify *} -{* it under the terms of the GNU General Public License as published by *} -{* the Free Software Foundation; either version 2 of the License, or *} -{* (at your option) any later version. *} -{* *} -{* This program is distributed in the hope that it will be useful, *} -{* but WITHOUT ANY WARRANTY; without even the implied warranty of *} -{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *} -{* GNU General Public License for more details. *} -{* *} -{* You should have received a copy of the GNU General Public License *} -{* along with this program; if not, write to the Free Software *} -{* Foundation, Inc., *} -{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *} -{* *} -{**************************************************************************} -

Sondages : succès

- -{if $survey_message neq ""} - {$survey_message} -{else} - Opération réussie -{/if} -
-Retour - -{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *} diff --git a/templates/survey/edit_text.tpl b/templates/survey/vote.tpl similarity index 96% rename from templates/survey/edit_text.tpl rename to templates/survey/vote.tpl index b62ed4b..6ba0d81 100644 --- a/templates/survey/edit_text.tpl +++ b/templates/survey/vote.tpl @@ -20,6 +20,8 @@ {* *} {**************************************************************************} - {include file='survey/edit_question.tpl'} +

{$survey->title}

+ +

{$survey->description|miniwiki}

{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *} diff --git a/upgrade/1.1.0/10_surveys.sql b/upgrade/1.1.0/10_surveys.sql new file mode 100644 index 0000000..010a72b --- /dev/null +++ b/upgrade/1.1.0/10_surveys.sql @@ -0,0 +1,86 @@ +#RENAME TABLE surveys TO old_surveys, +# survey_answers TO old_survey_answers, +# survey_votes TO old_survey_votes; + +DROP TABLE IF EXISTS survey_vote_answers; +DROP TABLE IF EXISTS survey_voters; +DROP TABLE IF EXISTS survey_votes; +DROP TABLE IF EXISTS survey_questions; +DROP TABLE IF EXISTS surveys; + +CREATE TABLE surveys ( + id INT(11) UNSIGNED NOT NULL auto_increment, + uid INT(11) UNSIGNED NOT NULL, + shortname VARCHAR(32) NOT NULL, + title VARCHAR(255) NOT NULL, + description TEXT NOT NULL, + begin DATE NOT NULL, + end DATE NOT NULL, + anonymous TINYINT(1) DEFAULT 0, + + voters TEXT DEFAULT NULL COMMENT "Filter users who can vote", + viewers TEXT DEFAULT NULL COMMENT "Filter users who can see the results", + + flags SET('validated'), + + PRIMARY KEY id (id), + UNIQUE KEY shortname (shortname), + FOREIGN KEY (uid) REFERENCES accounts (uid) + ON UPDATE CASCADE + ON DELETE CASCADE +) ENGINE=InnoDB, CHARSET=utf8, COMMENT="Describe a survey"; + +CREATE TABLE survey_questions ( + sid INT(11) UNSIGNED NOT NULL, + qid INT(11) UNSIGNED NOT NULL, + parent INT(11) UNSIGNED DEFAULT NULL COMMENT "Id of the parent question", + + type VARCHAR(32) NOT NULL, -- XXX: Use an enum of possible types? + label TEXT DEFAULT NULL, + parameters TEXT DEFAULT NULL COMMENT "Parameters of the question", + flags SET('multiple', 'mandatory', 'noanswer') NOT NULL DEFAULT '', + + PRIMARY KEY id (sid, qid), + FOREIGN KEY (sid) REFERENCES surveys (id) + ON UPDATE CASCADE + ON DELETE CASCADE +) ENGINE=InnoDB, CHARSET=utf8, COMMENT="Describe the questions of the surveys"; + +CREATE TABLE survey_votes ( + sid INT(11) UNSIGNED NOT NULL, + vid INT(11) UNSIGNED NOT NULL, + + PRIMARY KEY id (sid, vid), + FOREIGN KEY (sid) REFERENCES surveys (id) + ON UPDATE CASCADE + ON DELETE CASCADE +) ENGINE=InnoDB, CHARSET=utf8, COMMENT="Identify unique votes"; + +CREATE TABLE survey_voters ( + sid INT(11) UNSIGNED NOT NULL, + uid INT(11) UNSIGNED NOT NULL, + vid INT(11) UNSIGNED DEFAULT NULL, -- NULL for anonymous votes + + PRIMARY KEY id (sid, uid), + FOREIGN KEY (uid) REFERENCES accounts (uid) + ON UPDATE CASCADE + ON DELETE CASCADE, + FOREIGN KEY (sid) REFERENCES surveys (id) + ON UPDATE CASCADE + ON DELETE CASCADE +) ENGINE=InnoDB, CHARSET=utf8, COMMENT="List voters"; + +CREATE TABLE survey_vote_answers ( + sid INT(11) UNSIGNED NOT NULL, + vid INT(11) UNSIGNED NOT NULL, + qid INT(11) UNSIGNED NOT NULL, + + answer TEXT DEFAULT NULL, + + PRIMARY KEY id (sid, vid, qid), + FOREIGN KEY (sid, qid) REFERENCES survey_questions (sid, qid) + ON UPDATE CASCADE + ON DELETE CASCADE +) ENGINE=InnoDB, CHARSET=utf8, COMMENT="Answers to the surveys"; + +-- vim:set syntax=mysql: diff --git a/upgrade/1.1.0/old_surveys.inc.php b/upgrade/1.1.0/old_surveys.inc.php new file mode 100644 index 0000000..cfc2812 --- /dev/null +++ b/upgrade/1.1.0/old_surveys.inc.php @@ -0,0 +1,823 @@ + "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() + { + return self::$types; + } + + public static function isType($t) + { + return array_key_exists($t, self::$types); + } + // }}} + + // {{{ properties, constructor and basic methods + private $id; + private $title; + private $description; + private $end; + private $mode; + private $promos; + private $valid; + private $questions; + private $creator; + + public function __construct($args, $id = -1, $valid = false, $questions = null) + { + $this->update($args); + $this->id = $id; + $this->valid = $valid; + $this->questions = ($questions == null)? array() : $questions; + } + + public function update($args) + { + $this->title = $args['title']; + $this->description = $args['description']; + $this->end = $args['end']; + $this->mode = (isset($args['mode']))? $args['mode'] : self::MODE_ALL; + $this->creator = $args['uid']; + if ($this->mode == self::MODE_ALL) { + $args['promos'] = ''; + } + $args['promos'] = str_replace(' ', '', $args['promos']); + $this->promos = ($args['promos'] == '' || preg_match('#^(\d{4}-?|(\d{4})?-\d{4})(,(\d{4}-?|(\d{4})?-\d{4}))*$#', $args['promos']))? $args['promos'] : '#'; + } + + public function canSeeEarlyResults(User $user) + { + return $user->id() == $this->creator || $user->checkPerms('admin'); + } + // }}} + + // {{{ functions to access general information + public function isMode($mode) + { + return ($this->mode == $mode); + } + + public function checkPromo($promo) + { + if ($this->promos == '') { + return true; + } + $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 || + intval(substr($p, 0, 4)) >= $promo && intval(substr($p, 5)) <= $promo ))) { + return true; + } + } + return false; + } + + public function isValid() + { + return $this->valid; + } + + public function isEnded() + { + return (strtotime($this->end) - time() <= 0); + } + + public function getTitle() + { + return $this->title; + } + // }}} + + // {{{ function toArray() : converts a question (or the whole survey) to array, with results if the survey is ended + public function toArray($i = 'all') + { + 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 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 + $users = User::getBulkUsersWithUIDs(XDB::fetchAllAssoc('vid', 'SELECT v.id AS vid, v.uid + FROM survey_votes AS v + WHERE v.survey_id = {?} + ORDER BY vid ASC', + $this->id)); + } + $sql = 'SELECT v.id AS vid, a.question_id AS qid, a.answer AS answer + FROM survey_votes AS v + INNER 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 + $vid = -1; + $vid_ = 0; + while (($cur = $res->next()) != 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)) { // and if the user data can be found + $line[1] = $users[$vid]->lastName(); // adds the user data (in the first fields of the line) + $line[2] = $users[$vid]->firstName();; + $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 + } + } + fputcsv($csv, $line, $sep, $enc); // stores the last line into $csv_output + return $csv_output; + } + // }}} + + // {{{ function factory($type, $args) : builds a question according to the given type + public function factory($t, $args) + { + 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; + } + } + // }}} + + // {{{ questions manipulation functions + public function addQuestion($i, $c) + { + $i = intval($i); + if ($this->valid || $i > count($this->questions)) { + return false; + } else { + array_splice($this->questions, $i, 0, array($c)); + return true; + } + } + + public function delQuestion($i) + { + $i = intval($i); + if ($this->valid || !array_key_exists($i, $this->questions)) { + return false; + } else { + array_splice($this->questions, $i, 1); + return true; + } + } + + public function editQuestion($i, $a) + { + if ($i == 'root') { + $this->update($a); + } else { + $i = intval($i); + if ($this->valid ||!array_key_exists($i, $this->questions)) { + return false; + } else { + $this->questions[$i]->update($a); + } + } + return true; + } + // }}} + + // {{{ 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() + { + $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 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) + { + 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 surveys + WHERE '.$where.' + ORDER BY end DESC;'; + if ($tpl) { + return XDB::iterator($sql); + } else { + return XDB::iterRow($sql); + } + } + // }}} + + // {{{ 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, mode, promos, uid + FROM 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; + } + // }}} + + // {{{ 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, mode, promos + FROM surveys + WHERE id={?}'; + $res = XDB::query($sql, $sid); + return $res->fetchOneAssoc(); + } + // }}} + + // {{{ static function retrieveSurveyReq() : gets a survey request to validate + public static function retrieveSurveyReq($id) + { + $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; + } + // }}} + + // {{{ function proposeSurvey() : stores a proposition of survey in database (before validation) + public function proposeSurvey() + { + $surveyreq = new SurveyReq($this->title, $this->description, $this->end, $this->mode, $this->promos, $this->questions, S::user()); + return $surveyreq->submit(); + } + // }}} + + // {{{ function updateSurvey() : updates a survey in database (before validation) + public function updateSurvey() + { + if ($this->valid) { + $sql = 'UPDATE 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 { + $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); + } + } + // }}} + + // {{{ functions vote() and hasVoted() : handles vote to a survey + public function vote($uid, $args) + { + XDB::execute('INSERT INTO survey_votes + SET survey_id = {?}, uid = {?}', + $this->id, ($uid == 0) ? null : $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 hasVoted($uid) + { + $res = XDB::query('SELECT id + FROM survey_votes + WHERE survey_id = {?} AND uid = {?};', $this->id, $uid); // checks whether the user has already voted + return ($res->numRows() != 0); + } + // }}} + + // {{{ static function deleteSurvey() : deletes a survey (and all its votes) + public static function deleteSurvey($sid) + { + $sql = 'DELETE s.*, v.*, a.* + FROM 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); + } + // }}} + + // {{{ static function purgeVotes() : clears all votes concerning a survey (I'm not sure whether it's really useful) + public static function purgeVotes($sid) + { + $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); + } + // }}} + + // }}} +} +// }}} + +// {{{ abstract class SurveyQuestion +abstract class SurveyQuestion +{ + // {{{ common properties, constructor, and basic methods + private $question; + private $comment; + + public function __construct($args) + { + $this->update($args); + } + + public function update($a) + { + $this->question = $a['question']; + $this->comment = $a['comment']; + } + + abstract protected function getQuestionType(); + // }}} + + // {{{ function toArray() : converts to array + public function toArray() + { + return array('type' => $this->getQuestionType(), 'question' => $this->question, 'comment' => $this->comment); + } + // }}} + + // {{{ function checkSyntax() : checks question elements (before storing into database), not currently needed (with new structure) + protected function checkSyntax() + { + return null; + } + // }}} + + // {{{ function checkAnswer : returns a correct answer (or a null value if error) + public function checkAnswer($ans) + { + return null; + } + // }}} + + // {{{ functions regarding the results of a survey + abstract public function getResultArray($sid, $qid); + + public function formatAnswer($ans) + { + return $ans; + } + + public function getCSVColumns() + { + return $this->question; + } + // }}} +} +// }}} + +// {{{ abstract class SurveySimple and its derived classes : "open" questions +// {{{ abstract class SurveySimple extends SurveyQuestion +abstract class SurveySimple extends SurveyQuestion +{ + public function checkAnswer($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 +{ + public function getQuestionType() + { + return "text"; + } +} +// }}} + +// {{{ class SurveyTextarea extends SurveySimple : textarea field, allowing longer comments +class SurveyTextarea extends SurveySimple +{ + public function getQuestionType() + { + return "textarea"; + } +} +// }}} + +// {{{ class SurveyNum extends SurveySimple : allows numerical answers +class SurveyNum extends SurveySimple +{ + public function checkAnswer($ans) + { + return array(intval($ans)); + } + + protected function getQuestionType() + { + return "num"; + } +} +// }}} +// }}} + +// {{{ 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 +{ + protected $choices; + + public function update($args) + { + parent::update($args); + $this->choices = array(); + foreach ($args['choices'] as $val) { + if (trim($val) || trim($val) == '0') { + $this->choices[] = $val; + } + } + } + + public function toArray() + { + $rArr = parent::toArray(); + $rArr['choices'] = $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 +{ + public function checkAnswer($ans) + { + $a = intval($ans); + return (array_key_exists($a, $this->choices))? array($a) : null; + } + + protected function getQuestionType() + { + return "radio"; + } +} +// }}} + +// {{{ class SurveyCheckbox extends SurveyList : checkbox question, allows any number of answers among the list offered +class SurveyCheckbox extends SurveyList +{ + public function checkAnswer($ans) + { + $rep = array(); + foreach ($ans as $a) { + $a = intval($a); + if (array_key_exists($a, $this->choices)) { + $rep[] = $a; + } + } + return (count($rep) == 0)? null : $rep; + } + + protected function getQuestionType() + { + return "checkbox"; + } +} +// }}} +// }}} + +// {{{ 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 +{ + protected $subquestions; + + public function update($args) + { + parent::update($args); + $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; + } + + 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::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 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 "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 getQuestionType() + { + return "checkboxtable"; + } + +} +// }}} +// }}} + +// vim:set et sw=4 sts=4 ts=4 foldmethod=marker enc=utf-8: +?> diff --git a/upgrade/1.1.0/update.sh b/upgrade/1.1.0/update.sh new file mode 100755 index 0000000..ac34396 --- /dev/null +++ b/upgrade/1.1.0/update.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +. ../inc/pervasive.sh + +########################################################### +[ "$DATABASE" != "x4dat" ] || die "Cannot target x4dat" +copy_db + +confirm "* Running database upgrade scripts" +#mysql_run_directory . -- 2.1.4