]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/WikiPoll.php
Remove rcs_id
[SourceForge/phpwiki.git] / lib / plugin / WikiPoll.php
1 <?php // -*-php-*-
2 // $Id$
3 /*
4  * Copyright 2004 $ThePhpWikiProgrammingTeam
5  * Copyright 2008 Marc-Etienne Vargenau, Alcatel-lucent
6  *
7  * This file is part of PhpWiki.
8  *
9  * PhpWiki is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * PhpWiki is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with PhpWiki; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  */
23 /**
24  * This plugin provides configurable polls.
25  *
26  * Usage:
27 <<WikiPoll require_all=0 require_least=2
28            question[1]="Do you like PhpWiki?"
29              answer[1][1]="Yes" answer[1][2]="Do not know" answer[1][3]="No"
30            question[2]="Do you have PhpWiki installed by your own?"
31              answer[2][1]="Yes" answer[2][2]="No"
32            question[3]="Did you install any other wiki engine?"
33              answer[3][1]="Yes" answer[3][2]="No"
34            question[4]="What wiki engine do you like most?"
35              answer[4][1]="c2Wiki" answer[4][2]="MoinMoin" answer[4][3]="PhpWiki"
36              answer[4][4]="usemod" answer[4][5]="Twiki" answer[4][5]="guiki"
37              answer[4][6]="Mediawiki" answer[4][7]="Other"
38            question[5]="Which PhpWiki version do you use?"
39              answer[5][1]="1.2.x" answer[5][2]="1.3.1-12" answer[5][3]="1.3.13"
40              answer[5][4]="1.3.14"
41 >>
42  *
43  * Administration:
44  * <<WikiPoll page=PhpWikiPoll admin=1 >>
45  * and protect this page properly (e.g. PhpWikiPoll/Admin)
46  *
47  * TODO:
48  *     admin page (view and reset statistics)
49  *     for now only radio, support checkboxes (multiple selections) also?
50  *
51  * Author: ReiniUrban
52  */
53
54 class WikiPlugin_WikiPoll
55 extends WikiPlugin
56 {
57     var $_args;
58
59     function getName () {
60         return _("WikiPoll");
61     }
62
63     function getDescription () {
64         return _("Enable configurable polls");
65     }
66
67     function getDefaultArguments() {
68         return array('page'        => '[pagename]',
69                      'admin'       => false,
70                      'require_all' => 1,   // 1 if all questions must be answered
71                      'require_least' => 0, // how many at least
72                     );
73     }
74
75     function getArgs($argstr, $request=false, $defaults = false) {
76         if ($defaults === false)
77             $defaults = $this->getDefaultArguments();
78         //Fixme: on POST argstr is empty
79         $args = array();
80         list ($argstr_args, $argstr_defaults) = $this->parseArgStr($argstr);
81         if (isset($argstr_args["question_1"])) {
82           $args['question'] = $this->str2array("question",$argstr_args);
83           $args['answer'] = array();
84           for ($i = 0; $i <= count($args['question']); $i++) {
85               if ($array = $this->str2array(sprintf("%s_%d","answer",$i),$argstr_args))
86                   $args['answer'][$i] = $array;
87           }
88         }
89
90         if (!empty($defaults))
91           foreach ($defaults as $arg => $default_val) {
92             if (isset($argstr_args[$arg]))
93                 $args[$arg] = $argstr_args[$arg];
94             elseif ( $request and ($argval = $request->getArg($arg)) !== false )
95                 $args[$arg] = $argval;
96             elseif (isset($argstr_defaults[$arg]))
97                 $args[$arg] = (string) $argstr_defaults[$arg];
98             else
99                 $args[$arg] = $default_val;
100
101             if ($request)
102                 $args[$arg] = $this->expandArg($args[$arg], $request);
103
104             unset($argstr_args[$arg]);
105             unset($argstr_defaults[$arg]);
106         }
107
108         foreach (array_merge($argstr_args, $argstr_defaults) as $arg => $val) {
109             if (!preg_match("/^(answer_|question_)/",$arg))
110                 trigger_error(sprintf(_("argument '%s' not declared by plugin"),
111                                       $arg), E_USER_NOTICE);
112         }
113
114         return $args;
115     }
116
117     function handle_plugin_args_cruft($argstr, $args) {
118             $argstr = str_replace("\n"," ",$argstr);
119             $argstr = str_replace(array("[","]"),array("_",""),$argstr);
120             $this->_args = $this->getArgs($argstr, $GLOBALS['request']);
121         return;
122     }
123
124     function str2array($var, $obarray=false) {
125             if (!$obarray) $obarray = $GLOBALS;
126             $i = 0; $array = array();
127             $name = sprintf("%s_%d",$var,$i);
128             if (isset($obarray[$name])) $array[$i] = $obarray[$name];
129             do {
130           $i++;
131           $name = sprintf("%s_%d",$var,$i);
132           if (isset($obarray[$name])) $array[$i] = $obarray[$name];
133             } while (isset($obarray[$name]));
134             return $array;
135     }
136
137     function run($dbi, $argstr, &$request, $basepage) {
138         if (!isset($_SERVER))
139             $_SERVER =& $GLOBALS['HTTP_SERVER_VARS'];
140             $request->setArg('nocache','purge');
141         $args = $this->getArgs($argstr, $request);
142         if (!$args['page'])
143             return $this->error("No page specified");
144         if (!empty($args['admin']) and $request->_user->isAdmin()) {
145             // reset statistics
146             return $this->doPollAdmin($dbi, $request, $page);
147         }
148         extract($this->_args);
149         $page = $dbi->getPage($args['page']);
150         // check ip and last visit
151         $poll = $page->get("poll");
152         $ip = $_SERVER['REMOTE_ADDR'];
153         $disable_submit = false;
154         if (isset($poll['ip'][$ip]) and ((time() - $poll['ip'][$ip]) < 20*60)) {
155             //view at least the result or disable the Go button
156             $html = HTML(HTML::strong(
157                         _("Sorry! You must wait at least 20 minutes until you can vote again!")));
158             $html->pushContent($this->doPoll($page, $request, $request->getArg('answer'),true));
159             return $html;
160         }
161
162         $poll['ip'][$ip] = time();
163         // purge older ip's
164         foreach ($poll['ip'] as $ip => $time) {
165             if ((time() - $time) > 21*60)
166                 unset($poll['ip'][$ip]);
167         }
168         $html = HTML::form(array('action' => $request->getPostURL(),
169                                  'method' => 'post'));
170
171         if ($request->isPost()) {
172             // checkme: check if all answers are answered
173             if ($request->getArg('answer') and (
174                  ($args['require_all'] and
175                   count($request->getArg('answer')) == count($question))
176                  or
177                  ($args['require_least'] and
178                   count($request->getArg('answer')) >= $args['require_least']))) {
179                 $page->set("poll", $poll);
180                 // update statistics and present them the user
181                 return $this->doPoll($page, $request, $request->getArg('answer'));
182             } else {
183                 $html->pushContent(HTML::p(HTML::strong(_("Not enough questions answered!"))));
184             }
185         }
186
187         $init = isset($question[0]) ? 0 : 1;
188         for ($i = $init; $i <= count($question); $i++) {
189             if (!isset($question[$i])) break;
190             $q = $question[$i];
191             if (!isset($answer[$i]))
192                     trigger_error(fmt("Missing %s for %s","answer"."[$i]","question"."[$i]"),
193                                   E_USER_ERROR);
194             $a = $answer[$i];
195             if (! is_array($a)) {
196                 // a simple checkbox
197                 $html->pushContent(HTML::p(HTML::strong($q)));
198                 $html->pushContent(HTML::div(
199                                        HTML::input(array('type' => 'checkbox',
200                                                          'name' => "answer[$i]",
201                                                          'value' => 1)),
202                                        HTML::raw("&nbsp;"), $a));
203             } else {
204                 $row = HTML();
205                 for ($j=0; $j <= count($a); $j++) {
206                     if (isset($a[$j]))
207                         $row->pushContent(HTML::div(
208                                               HTML::input(array('type' => 'radio',
209                                                                 'name' => "answer[$i]",
210                                                                 'value' => $j)),
211                                               HTML::raw("&nbsp;"), $a[$j]));
212                 }
213                 $html->pushContent(HTML::p(HTML::strong($q)),$row);
214             }
215         }
216         if (!$disable_submit)
217             $html->pushContent(HTML::p(
218                 HTML::input(array('type' => 'submit',
219                                   'name' => "WikiPoll",
220                                   'value' => _("OK"))),
221                 HTML::input(array('type' => 'reset',
222                                   'name' => "reset",
223                                   'value' => _("Reset")))));
224         else
225              $html->pushContent(HTML::p(),HTML::strong(
226                  _("Sorry! You must wait at least 20 minutes until you can vote again!")));
227         return $html;
228     }
229
230     function bar($percent) {
231         global $WikiTheme;
232         return HTML(HTML::img(array('src' => $WikiTheme->getImageUrl('leftbar'),
233                                     'alt' => '<')),
234                     HTML::img(array('src' => $WikiTheme->getImageUrl('mainbar'),
235                                     'alt' => '-',
236                                     'width' => sprintf("%02d",$percent),
237                                     'height' => 14)),
238                     HTML::img(array('src' => $WikiTheme->getImageUrl('rightbar'),
239                                     'alt' => '>')));
240     }
241
242     function doPoll($page, $request, $answers, $readonly = false) {
243             $question = $this->_args['question'];
244             $answer   = $this->_args['answer'];
245         $html = HTML::table(array('cellspacing' => 2));
246         $init = isset($question[0]) ? 0 : 1;
247         for ($i = $init; $i <= count($question); $i++) {
248             if (!isset($question[$i])) break;
249             $poll = $page->get('poll');
250             @$poll['data']['all'][$i]++;
251             $q = $question[$i];
252             if (!isset($answer[$i]))
253                     trigger_error(fmt("Missing %s for %s","answer"."[$i]","question"."[$i]"),
254                                   E_USER_ERROR);
255             if (!$readonly)
256                 $page->set('poll',$poll);
257             $a = $answer[$i];
258             $result = (isset($answers[$i])) ? $answers[$i] : -1;
259             if (! is_array($a) ) {
260                 $checkbox = HTML::input(array('type' => 'checkbox',
261                                               'name' => "answer[$i]",
262                                               'value' => $a));
263                 if ($result >= 0)
264                     $checkbox->setAttr('checked', "checked");
265                 if (!$readonly)
266                     list($percent,$count,$all) = $this->storeResult($page, $i, $result ? 1 : 0);
267                 else
268                     list($percent,$count,$all) = $this->getResult($page, $i, 1);
269                 $print = sprintf(_("  %d%% (%d/%d)"), $percent, $count, $all);
270                 $html->pushContent(HTML::tr(HTML::th(array('colspan' => 4,'align'=>'left'),$q)));
271                 $html->pushContent(HTML::tr(HTML::td($checkbox),
272                                             HTML::td($a),
273                                                    HTML::td($this->bar($percent)),
274                                             HTML::td($print)));
275             } else {
276                 $html->pushContent(HTML::tr(HTML::th(array('colspan' => 4,'align'=>'left'),$q)));
277                 $row = HTML();
278                 if (!$readonly)
279                     $this->storeResult($page, $i, $answers[$i]);
280                 for ($j=0; $j <= count($a); $j++) {
281                     if (isset($a[$j])) {
282                             list($percent,$count,$all) = $this->getResult($page,$i,$j);
283                         $print = sprintf(_("  %d%% (%d/%d)"), $percent, $count, $all);
284                         $radio = HTML::input(array('type' => 'radio',
285                                                    'name' => "answer[$i]",
286                                                    'value' => $j));
287                         if ($result == $j)
288                             $radio->setAttr('checked', "checked");
289                         $row->pushContent(HTML::tr(HTML::td($radio),
290                                                    HTML::td($a[$j]),
291                                                    HTML::td($this->bar($percent)),
292                                                    HTML::td($print)));
293                     }
294                 }
295                 $html->pushContent($row);
296             }
297         }
298         if (!$readonly)
299             return HTML(HTML::h3(_("The result of this poll so far:")),$html,HTML::p(_("Thanks for participating!")));
300         else
301             return HTML(HTML::h3(_("The result of this poll so far:")),$html);
302
303     }
304
305     function getResult($page,$i,$j) {
306             $poll = $page->get("poll");
307             @$count = $poll['data']['count'][$i][$j];
308             @$all = $poll['data']['all'][$i];
309             $percent = sprintf("%d", $count * 100.0 / $all);
310             return array($percent,$count,$all);
311     }
312
313     function storeResult($page, $i, $j) {
314             $poll = $page->get("poll");
315             if (!$poll) {
316                 $poll = array('data' => array('count' => array(),
317                                                   'all'   => array()));
318             }
319             @$poll['data']['count'][$i][$j]++;
320             //@$poll['data']['all'][$i];
321             $page->set("poll",$poll);
322           $percent = sprintf("%d", $poll['data']['count'][$i][$j] * 100.0 / $poll['data']['all'][$i]);
323         return array($percent,$poll['data']['count'][$i][$j],$poll['data']['all'][$i]);
324     }
325
326 };
327
328 // Local Variables:
329 // mode: php
330 // tab-width: 8
331 // c-basic-offset: 4
332 // c-hanging-comment-ender-p: nil
333 // indent-tabs-mode: nil
334 // End:
335 ?>