Add custom unsubscription notification message
[platal.git] / modules / survey / survey.inc.php
CommitLineData
8fe81c50 1<?php
2/***************************************************************************
3 * Copyright (C) 2003-2007 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
5c6e38d7 22// {{{ class Survey : root of any survey, contains all questions
23class Survey
8fe81c50 24{
5c6e38d7 25 // {{{ static properties and functions, regarding survey modes and question types
26 const MODE_ALL = 0;
27 const MODE_XANON = 1;
28 const MODE_XIDENT = 2;
29 private static $longModes = array(self::MODE_ALL => "sondage ouvert &#224; tout le monde, anonyme",
30 self::MODE_XANON => "sondage restreint aux polytechniciens, anonyme",
31 self::MODE_XIDENT => "sondage restreint aux polytechniciens, non anonyme");
32 private static $shortModes = array(self::MODE_ALL => "tout le monde, anonyme",
33 self::MODE_XANON => "polytechniciens, anonyme",
34 self::MODE_XIDENT => "polytechniciens, non anonyme");
8fe81c50 35
5c6e38d7 36 public static function getModes($long = true) {
37 return ($long)? self::$longModes : self::$shortModes;
8fe81c50 38 }
8fe81c50 39
8fe81c50 40 private static $types = array('text' => 'texte court',
41 'textarea' => 'texte long',
42 'num' => 'num&#233;rique',
43 'radio' => 'radio',
44 'checkbox' => 'checkbox',
45 'personal' => 'informations personnelles');
46
47 public static function getTypes()
48 {
49 return self::$types;
50 }
51
52 public static function isType($t)
53 {
54 return array_key_exists($t, self::$types);
55 }
56 // }}}
57
5c6e38d7 58 // {{{ properties, constructor and basic methods
8fe81c50 59 private $id;
5c6e38d7 60 private $title;
61 private $description;
62 private $end;
63 private $mode;
64 private $promos;
65 private $valid;
66 private $questions;
8fe81c50 67
5c6e38d7 68 public function __construct($args, $id = -1, $valid = false, $questions = null)
8fe81c50 69 {
8fe81c50 70 $this->update($args);
5c6e38d7 71 $this->id = $id;
72 $this->valid = $valid;
73 $this->questions = ($questions == null)? array() : $questions;
8fe81c50 74 }
75
5c6e38d7 76 public function update($args)
8fe81c50 77 {
5c6e38d7 78 $this->title = $args['title'];
79 $this->description = $args['description'];
80 if (preg_match('#^\d{2}/\d{2}/\d{4}$#', $args['end'])) {
81 $this->end = preg_replace('#^(\d{2})/(\d{2})/(\d{4})$#', '\3-\2-\1', $args['end']);
8fe81c50 82 } else {
5c6e38d7 83 $this->end = (preg_match('#^\d{4}-\d{2}-\d{2}$#', $args['end']))? $args['end'] : '#';
84 }
85 $this->mode = $args['mode'];
86 if ($args['mode'] == 0) {
87 $args['promos'] = '';
8fe81c50 88 }
5c6e38d7 89 $this->promos = ($args['promos'] == '' || preg_match('#^(\d{4}-?|(\d{4})?-\d{4})(,(\d{4}-?|(\d{4})?-\d{4}))*$#', $args['promos']))? $args['promos'] : '#';
8fe81c50 90 }
91 // }}}
92
5c6e38d7 93 // {{{ functions to access general information
94 public function isMode($mode)
8fe81c50 95 {
5c6e38d7 96 return ($this->mode == $mode);
8fe81c50 97 }
98
5c6e38d7 99 public function checkPromo($promo)
8fe81c50 100 {
5c6e38d7 101 $promos = explode('|', $this->promos);
102 foreach ($promos as $p) {
103 if ((preg_match('#^\d{4}$#', $p) && $p == $promo) ||
104 (preg_match('#^\d{4}-$#', $p) && intval(substr($p, 0, 4)) <= $promo) ||
105 (preg_match('#^-\d{4}$#', $p) && intval(substr($p, 1)) >= $promo) ||
106 (preg_match('#^\d{4}-\d{4}$#', $p) && intval(substr($p, 0, 4)) <= $promo && intval(substr($p, 5)) >= $promo)) {
107 return true;
108 }
8fe81c50 109 }
5c6e38d7 110 return false;
8fe81c50 111 }
112
5c6e38d7 113 public function isValid()
8fe81c50 114 {
5c6e38d7 115 return $this->valid;
8fe81c50 116 }
117
5c6e38d7 118 public function isEnded()
8fe81c50 119 {
5c6e38d7 120 return (strtotime($this->end) - time() <= 0);
8fe81c50 121 }
8fe81c50 122
5c6e38d7 123 public function getTitle()
8fe81c50 124 {
5c6e38d7 125 return $this->title;
8fe81c50 126 }
127 // }}}
128
9f01f40b 129 // {{{ function toArray() : converts a question (or the whole survey) to array, with results if the survey is ended
5c6e38d7 130 public function toArray($i = 'all')
8fe81c50 131 {
9f01f40b 132 if ($i != 'all' && $i != 'root') { // if a specific question is requested, then just returns this question converted to array
5c6e38d7 133 $i = intval($i);
134 if (array_key_exists($i, $this->questions)) {
135 return $this->questions[$i]->toArray();
8fe81c50 136 } else {
5c6e38d7 137 return null;
8fe81c50 138 }
9f01f40b 139 } else { // else returns the root converted to array in any case
5c6e38d7 140 $a = array('title' => $this->title,
141 'description' => $this->description,
142 'end' => $this->end,
143 'mode' => $this->mode,
144 'promos' => $this->promos,
145 'valid' => $this->valid,
146 'type' => 'root');
147 if ($this->id != -1) {
148 $a['id'] = $this->id;
149 }
9f01f40b 150 if ($this->isEnded()) { // if the survey is ended, then adds here the number of votes
151 $sql = 'SELECT COUNT(id)
152 FROM survey_votes
153 WHERE survey_id={?};';
154 $tot = XDB::query($sql, $this->id);
155 $a['votes'] = $tot->fetchOneCell();
156 }
157 if ($i == 'all' && count($this->questions) > 0) { // if the whole survey is requested, then returns all the questions converted to array
5c6e38d7 158 $qArr = array();
159 for ($k = 0; $k < count($this->questions); $k++) {
160 $q = $this->questions[$k]->toArray();
161 $q['id'] = $k;
9f01f40b 162 if ($this->isEnded()) { // if the survey is ended, then adds here the results of this question
163 $sql = $this->questions[$k]->buildResultRequest();
164 if ($sql != '') {
165 $q['result'] = XDB::iterator($sql, $this->id, $k);
166 }
167 }
5c6e38d7 168 $qArr[$k] = $q;
8fe81c50 169 }
5c6e38d7 170 $a['questions'] = $qArr;
8fe81c50 171 }
5c6e38d7 172 return $a;
8fe81c50 173 }
174 }
5c6e38d7 175 // }}}
8fe81c50 176
5c6e38d7 177 // {{{ function factory($type, $args) : builds a question according to the given type
178 public function factory($t, $args)
8fe81c50 179 {
5c6e38d7 180 switch ($t) {
181 case 'text':
182 return new SurveyText($args);
183 case 'textarea':
184 return new SurveyTextarea($args);
185 case 'num':
186 return new SurveyNum($args);
187 case 'radio':
188 return new SurveyRadio($args);
189 case 'checkbox':
190 return new SurveyCheckbox($args);
191 case 'personal':
192 return new SurveyPersonal($args);
193 default:
194 return null;
8fe81c50 195 }
5c6e38d7 196 }
197 // }}}
198
199 // {{{ questions manipulation functions
200 public function addQuestion($i, $c)
201 {
202 if ($this->valid || $i > count($this->questions)) {
203 return false;
204 } else {
205 array_splice($this->questions, $i, 0, array($c));
8fe81c50 206 return true;
207 }
8fe81c50 208 }
209
5c6e38d7 210 public function delQuestion($i)
8fe81c50 211 {
5c6e38d7 212 if ($this->valid || !array_key_exists($i, $this->questions)) {
213 return false;
214 } else {
215 array_splice($this->questions, $i, 1);
8fe81c50 216 return true;
217 }
8fe81c50 218 }
8fe81c50 219
5c6e38d7 220 public function editQuestion($i, $a)
8fe81c50 221 {
5c6e38d7 222 if ($i == 'root') {
8fe81c50 223 $this->update($a);
8fe81c50 224 } else {
5c6e38d7 225 $i = intval($i);
226 if ($this->valid ||!array_key_exists($i, $this->questions)) {
227 return false;
228 } else {
229 $this->questions[$i]->update($a);
8fe81c50 230 }
8fe81c50 231 }
5c6e38d7 232 return true;
8fe81c50 233 }
234 // }}}
235
5c6e38d7 236 // {{{ function checkSyntax() : checks syntax of the questions (currently the root only) before storing the survey in database
237 private static $errorMessages = array(
238 "dateformat" => "la date de fin de sondage est mal formatt&#233;e : elle doit respecter la syntaxe dd/mm/aaaa",
239 "datepassed" => "la date de fin de sondage est d&#233;j&#224; d&#233;pass&#233;e : vous devez pr&#233;ciser une date future",
240 "promoformat" => "les restrictions &#224; certaines promotions sont mal formatt&#233;es"
241 );
242
243 public function checkSyntax()
8fe81c50 244 {
5c6e38d7 245 $rArr = array();
246 if (!preg_match('#^\d{4}-\d{2}-\d{2}$#', $this->end)) {
247 $rArr[] = array('question' => 'root', 'error' => self::$errorMessages["dateformat"]);
8fe81c50 248 } else {
5c6e38d7 249 // checks that the end date given is not already passed
250 // (unless the survey has already been validated : an admin can have a validated survey expired)
251 if (!$this->valid && $this->isEnded()) {
252 $rArr[] = array('question' => 'root', 'error' => self::$errorMessages["datepassed"]);
253 }
254 }
255 if ($this->promos != '' && !preg_match('#^(\d{4}-?|(\d{4})?-\d{4})(,(\d{4}-?|(\d{4})?-\d{4}))*$#', $this->promos)) {
256 $rArr[] = array('question' => 'root', 'error' => self::$errorMessages["promoformat"]);
8fe81c50 257 }
5c6e38d7 258 return (empty($rArr))? null : $rArr;
8fe81c50 259 }
5c6e38d7 260 // }}}
8fe81c50 261
9f01f40b 262 // {{{ functions that manipulate surveys in database
5c6e38d7 263 // {{{ static function retrieveList() : gets the list of available survey (current, old and not validated surveys)
264 public static function retrieveList($type, $tpl = true)
8fe81c50 265 {
5c6e38d7 266 switch ($type) {
267 case 'w':
268 case 'waiting' :
269 $where = 'valid=0';
270 break;
271 case 'c':
272 case 'current':
273 $where = 'valid=1 AND end > NOW()';
274 break;
275 case 'o':
276 case 'old':
277 $where = 'valid=1 AND end <= NOW()';
278 break;
279 default:
8fe81c50 280 return null;
281 }
5c6e38d7 282 $sql = 'SELECT id, title, end, mode
283 FROM survey_surveys
284 WHERE '.$where.';';
285 if ($tpl) {
286 return XDB::iterator($sql);
287 } else {
288 return XDB::iterRow($sql);
289 }
8fe81c50 290 }
291 // }}}
292
5c6e38d7 293 // {{{ static function retrieveSurvey() : gets a survey in database (and unserialize the survey object structure)
294 public static function retrieveSurvey($sid)
8fe81c50 295 {
5c6e38d7 296 $sql = 'SELECT questions, title, description, end, mode, promos, valid
297 FROM survey_surveys
298 WHERE id={?}';
299 $res = XDB::query($sql, $sid);
300 $data = $res->fetchOneAssoc();
301 if (is_null($data) || !is_array($data)) {
302 return null;
8fe81c50 303 }
5c6e38d7 304 $survey = new Survey($data, $sid, (boolean) $data['valid'], unserialize($data['questions']));
305 return $survey;
8fe81c50 306 }
307 // }}}
308
5c6e38d7 309 // {{{ static function retrieveSurveyInfo() : gets information about a survey (title, description, end date, restrictions) but does not unserialize the survey object structure
310 public static function retrieveSurveyInfo($sid)
8fe81c50 311 {
5c6e38d7 312 $sql = 'SELECT title, description, end, mode, promos, valid
313 FROM survey_surveys
314 WHERE id={?}';
315 $res = XDB::query($sql, $sid);
316 return $res->fetchOneAssoc();
8fe81c50 317 }
318 // }}}
8fe81c50 319
5c6e38d7 320 // {{{ function proposeSurvey() : stores a proposition of survey in database (before validation)
321 public function proposeSurvey()
8fe81c50 322 {
5c6e38d7 323 $sql = 'INSERT INTO survey_surveys
324 SET questions={?},
325 title={?},
326 description={?},
327 author_id={?},
328 end={?},
329 mode={?},
330 promos={?},
331 valid=0;';
332 return XDB::execute($sql, serialize($this->questions), $this->title, $this->description, S::v('uid'), $this->end, $this->mode, $this->promos);
8fe81c50 333 }
5c6e38d7 334 // }}}
8fe81c50 335
5c6e38d7 336 // {{{ function updateSurvey() : updates a survey in database (before validation)
337 public function updateSurvey()
8fe81c50 338 {
5c6e38d7 339 if ($this->id == -1) {
340 return false;
8fe81c50 341 }
5c6e38d7 342 $sql = 'UPDATE survey_surveys
343 SET questions={?},
344 title={?},
345 description={?},
346 end={?},
347 mode={?},
348 promos={?}
349 WHERE id={?};';
350 return XDB::execute($sql, serialize($this->questions), $this->title, $this->description, $this->end, $this->mode, $this->promos, $this->id);
8fe81c50 351 }
5c6e38d7 352 // }}}
8fe81c50 353
5c6e38d7 354 // {{{ static function validateSurvey() : validates a survey
355 public static function validateSurvey($sid)
8fe81c50 356 {
5c6e38d7 357 $sql = 'UPDATE survey_surveys
358 SET valid=1
359 WHERE id={?};';
360 return XDB::execute($sql, $sid);
8fe81c50 361 }
5c6e38d7 362 // }}}
8fe81c50 363
5c6e38d7 364 // {{{ functions vote() and hasVoted() : handles vote to a survey
365 public function vote($uid, $args)
366 {
367 XDB::execute('INSERT INTO survey_votes
368 SET survey_id={?}, user_id={?};', $this->id, $uid); // notes the user as having voted
369 $vid = XDB::insertId();
370 for ($i = 0; $i < count($this->questions); $i++) {
371 $ans = $this->questions[$i]->checkAnswer($args[$i]);
9f01f40b 372 if (!is_null($ans) && is_array($ans)) {
373 foreach ($ans as $a) {
374 XDB::execute('INSERT INTO survey_answers
375 SET vote_id = {?},
376 question_id = {?},
377 answer = {?}', $vid, $i, $a);
378 }
5c6e38d7 379 }
380 }
8fe81c50 381 }
382
5c6e38d7 383 public function hasVoted($uid)
8fe81c50 384 {
5c6e38d7 385 $res = XDB::query('SELECT id
386 FROM survey_votes
387 WHERE survey_id={?} AND user_id={?};', $this->id, $uid); // checks whether the user has already voted
388 return ($res->numRows() != 0);
8fe81c50 389 }
5c6e38d7 390 // }}}
8fe81c50 391
5c6e38d7 392 // {{{ static function deleteSurvey() : deletes a survey (and all its votes)
393 public static function deleteSurvey($sid)
8fe81c50 394 {
5c6e38d7 395 $sql = 'DELETE s.*, v.*, a.*
396 FROM survey_surveys AS s
397 LEFT JOIN survey_votes AS v
398 ON v.survey_id=s.id
399 LEFT JOIN survey_answers AS a
400 ON a.vote_id=v.id
401 WHERE s.id={?};';
402 return XDB::execute($sql, $sid);
8fe81c50 403 }
404 // }}}
405
5c6e38d7 406 // {{{ static function purgeVotes() : clears all votes concerning a survey (I'm not sure whether it's really useful)
407 public static function purgeVotes($sid)
8fe81c50 408 {
5c6e38d7 409 $sql = 'DELETE v.*, a.*
410 FROM survey_votes AS v
411 LEFT JOIN survey_answers AS a
412 ON a.vote_id=v.id
413 WHERE v.survey_id={?};';
414 return XDB::execute($sql, $sid);
8fe81c50 415 }
416 // }}}
417
5c6e38d7 418 // }}}
419}
420// }}}
8fe81c50 421
5c6e38d7 422// {{{ abstract class SurveyQuestion
423abstract class SurveyQuestion
424{
425 // {{{ common properties, constructor, and basic methods
426 private $question;
427 private $comment;
8fe81c50 428
5c6e38d7 429 public function __construct($args)
8fe81c50 430 {
5c6e38d7 431 $this->update($args);
8fe81c50 432 }
433
5c6e38d7 434 public function update($a)
8fe81c50 435 {
5c6e38d7 436 $this->question = $a['question'];
437 $this->comment = $a['comment'];
8fe81c50 438 }
439
5c6e38d7 440 abstract protected function getQuestionType();
441 // }}}
442
443 // {{{ function toArray() : converts to array
8fe81c50 444 public function toArray()
445 {
5c6e38d7 446 return array('type' => $this->getQuestionType(), 'question' => $this->question, 'comment' => $this->comment);
8fe81c50 447 }
5c6e38d7 448 // }}}
8fe81c50 449
5c6e38d7 450 // {{{ function checkSyntax() : checks question elements (before storing into database), not currently needed (with new structure)
451 protected function checkSyntax()
8fe81c50 452 {
5c6e38d7 453 return null;
8fe81c50 454 }
455 // }}}
456
5c6e38d7 457 // {{{ function checkAnswer : returns a correctly formatted answer (or nothing empty string if error)
458 public function checkAnswer($ans)
8fe81c50 459 {
9f01f40b 460 return null;
8fe81c50 461 }
462 // }}}
463
9f01f40b 464 // {{{ function buildResultRequest() : statistics on the results of the survey
465 public function buildResultRequest()
466 {
467 return '';
468 }
8fe81c50 469 // }}}
470}
471// }}}
472
9f01f40b 473// {{{ abstract class SurveySimple and its derived classes : "opended" questions
474// {{{ abstract class SurveySimple extends SurveyQuestion
8fe81c50 475abstract class SurveySimple extends SurveyQuestion
476{
5c6e38d7 477 public function checkAnswer($ans)
8fe81c50 478 {
9f01f40b 479 return array($ans);
480 }
481
482 public function buildResultRequest()
483 {
484 $sql = 'SELECT answer
485 FROM survey_answers
486 WHERE vote_id IN (SELECT id FROM survey_votes WHERE survey_id={?})
487 AND question_id={?}
488 ORDER BY RAND()
489 LIMIT 5;';
490 return $sql;
8fe81c50 491 }
492}
9f01f40b 493// }}}
8fe81c50 494
495// {{{ class SurveyText extends SurveySimple : simple text field, allowing a few words
496class SurveyText extends SurveySimple
497{
5c6e38d7 498 public function getQuestionType()
8fe81c50 499 {
500 return "text";
501 }
502}
503// }}}
504
505// {{{ class SurveyTextarea extends SurveySimple : textarea field, allowing longer comments
506class SurveyTextarea extends SurveySimple
507{
5c6e38d7 508 public function getQuestionType()
8fe81c50 509 {
510 return "textarea";
511 }
512}
513// }}}
514
515// {{{ class SurveyNum extends SurveySimple : allows numerical answers
516class SurveyNum extends SurveySimple
517{
5c6e38d7 518 public function checkAnswer($ans)
8fe81c50 519 {
9f01f40b 520 return array(intval($ans));
8fe81c50 521 }
522
523 protected function getQuestionType()
524 {
525 return "num";
526 }
527}
528// }}}
529// }}}
530
9f01f40b 531// {{{ abstract class SurveyList and its derived classes : restricted questions that allows only a list of possible answers
532// {{{ abstract class SurveyList extends SurveyQuestion
5c6e38d7 533abstract class SurveyList extends SurveyQuestion
8fe81c50 534{
5c6e38d7 535 protected $choices;
8fe81c50 536
5c6e38d7 537 public function update($args)
8fe81c50 538 {
539 parent::update($args);
540 $this->choices = explode('|', $args['options']);
541 }
542
5c6e38d7 543 public function toArray()
8fe81c50 544 {
5c6e38d7 545 $rArr = parent::toArray();
8fe81c50 546 $rArr['choices'] = $this->choices;
547 $rArr['options'] = implode('|', $this->choices);
548 return $rArr;
549 }
550
9f01f40b 551 public function buildResultRequest()
552 {
553 $sql = 'SELECT answer, COUNT(id) AS count
554 FROM survey_answers
555 WHERE vote_id IN (SELECT id FROM survey_votes WHERE survey_id={?})
556 AND question_id={?}
557 GROUP BY answer ASC';
558 return $sql;
559 }
8fe81c50 560}
9f01f40b 561// }}}
8fe81c50 562
563// {{{ class SurveyRadio extends SurveyList : radio question, allows one answer among the list offered
564class SurveyRadio extends SurveyList
565{
5c6e38d7 566 public function checkAnswer($ans)
8fe81c50 567 {
9f01f40b 568 return (array_key_exists($ans, $this->choices))? array($ans) : null;
8fe81c50 569 }
570
571 protected function getQuestionType()
572 {
573 return "radio";
574 }
575}
576// }}}
577
578// {{{ class SurveyCheckbox extends SurveyList : checkbox question, allows any number of answers among the list offered
579class SurveyCheckbox extends SurveyList
580{
5c6e38d7 581 public function checkAnswer($ans)
8fe81c50 582 {
9f01f40b 583 $rep = array();
5c6e38d7 584 foreach ($ans as $a) {
9f01f40b 585 $a = intval($a);
586 if (array_key_exists($a, $this->choices)) {
587 $rep[] = $a;
8fe81c50 588 }
589 }
9f01f40b 590 return (count($rep) == 0)? null : $rep;
8fe81c50 591 }
592
593 protected function getQuestionType()
594 {
595 return "checkbox";
596 }
597}
598// }}}
599// }}}
600
601// {{{ class SurveyPersonal extends SurveyQuestion : allows easy and verified access to user's personal data (promotion, name...)
5c6e38d7 602// actually this type of question should be suppressed (non anonymous surveys are possible with survey modes)
603// and anyway it is not finished (checkAnswer implementation) : currently it does not store anything when a user votes
8fe81c50 604class SurveyPersonal extends SurveyQuestion
605{
606 private $perm;
607
5c6e38d7 608 public function update($args)
8fe81c50 609 {
610 $args['question'] = "Informations personnelles";
611 parent::update($args);
612 $this->perm['promo'] = isset($args['promo'])? 1 : 0;
613 $this->perm['name'] = isset($args['name'])? 1 : 0;
614 }
615
5c6e38d7 616 public function checkAnswer($ans)
8fe81c50 617 {
618 if (intval($ans) == 1) {
619 // requete mysql qvb
9f01f40b 620 return null;
8fe81c50 621 } else {
9f01f40b 622 return null;
8fe81c50 623 }
624 }
625
626 protected function getQuestionType()
627 {
628 return "personal";
629 }
630
5c6e38d7 631 public function toArray()
8fe81c50 632 {
5c6e38d7 633 $a = parent::toArray();
8fe81c50 634 $a['promo'] = $this->perm['promo'];
635 $a['name'] = $this->perm['name'];
636 return $a;
637 }
638}
639// }}}
640
641// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
642?>